Skip to content

Commit

Permalink
Removing role selection while signin
Browse files Browse the repository at this point in the history
  • Loading branch information
akadeepesh committed Sep 19, 2024
1 parent 966f1ae commit c286ea8
Show file tree
Hide file tree
Showing 4 changed files with 48 additions and 38 deletions.
42 changes: 38 additions & 4 deletions src/app/api/loan-application/[id]/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,7 +56,15 @@ export async function PUT(
}

const { id } = params;
const body = await req.json();
let body;
try {
body = await req.json();
} catch (error) {
return NextResponse.json(
{ message: "Invalid JSON in request body" },
{ status: 400 }
);
}

try {
await dbConnect();
Expand All @@ -82,23 +90,46 @@ export async function PUT(
}

const { amount, purpose } = body;
if (typeof amount !== "number" || amount <= 0) {
return NextResponse.json(
{ message: "Amount must be a positive number" },
{ status: 400 }
);
}
if (typeof purpose !== "string" || purpose.trim() === "") {
return NextResponse.json(
{ message: "Purpose must be a non-empty string" },
{ status: 400 }
);
}

const updatedApplication = await LoanApplication.findByIdAndUpdate(
id,
{ amount, purpose, updatedAt: new Date() },
{ new: true }
{ new: true, runValidators: true }
).populate("userId", "name email");

return NextResponse.json(updatedApplication);
} else if (["verifier", "admin"].includes(session.user.role as string)) {
const { status } = body;
if (
typeof status !== "string" ||
!["approved", "rejected", "pending"].includes(status)
) {
return NextResponse.json(
{ message: "Status must be 'approved', 'rejected', or 'pending'" },
{ status: 400 }
);
}

const updatedApplication = await LoanApplication.findByIdAndUpdate(
id,
{
status,
verifiedBy: session.user.id,
updatedAt: new Date(),
},
{ new: true }
{ new: true, runValidators: true }
)
.populate("userId", "name email")
.populate("verifiedBy", "name email");
Expand All @@ -108,7 +139,10 @@ export async function PUT(

return NextResponse.json({ message: "Unauthorized" }, { status: 401 });
} catch (error) {
console.error(error);
console.error("Error in PUT handler:", error);
if (error instanceof Error) {
return NextResponse.json({ message: error.message }, { status: 400 });
}
return NextResponse.json({ message: "An error occurred" }, { status: 500 });
}
}
Expand Down
14 changes: 9 additions & 5 deletions src/app/api/loan-application/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,13 +23,17 @@ export async function GET() {
.sort({ createdAt: -1 })
.lean(); // Use lean() for better performance

// Fetch all verifiers in one query
const verifiers = await User.find({ role: "verifier" })
// Fetch all verifiers and admins in one query
const verifiersAndAdmins = await User.find({
role: { $in: ["verifier", "admin"] },
})
.select("_id name email")
.lean();

// Create a map of verifier IDs to verifier objects
const verifierMap = new Map(verifiers.map((v) => [v._id.toString(), v]));
// Create a map of verifier and admin IDs to their objects
const verifierAdminMap = new Map(
verifiersAndAdmins.map((v) => [v._id.toString(), v])
);

const populatedApplications = await Promise.all(
loanApplications.map(async (app) => {
Expand All @@ -39,7 +43,7 @@ export async function GET() {

let verifiedBy = null;
if (app.verifiedBy) {
verifiedBy = verifierMap.get(app.verifiedBy.toString()) || null;
verifiedBy = verifierAdminMap.get(app.verifiedBy.toString()) || null;
}

return {
Expand Down
20 changes: 0 additions & 20 deletions src/app/auth/signin/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ import Link from "next/link";
export default function SignIn() {
const [email, setEmail] = useState("");
const [password, setPassword] = useState("");
const [role, setRole] = useState<"user" | "verifier" | "admin">("user");
const [error, setError] = useState("");
const router = useRouter();

Expand All @@ -19,7 +18,6 @@ export default function SignIn() {
redirect: false,
email,
password,
role,
});

if (result?.error) {
Expand Down Expand Up @@ -78,24 +76,6 @@ export default function SignIn() {
onChange={(e) => setPassword(e.target.value)}
/>
</div>
<div>
<label htmlFor="role" className="sr-only">
Role
</label>
<select
id="role"
name="role"
value={role}
onChange={(e) =>
setRole(e.target.value as "user" | "verifier" | "admin")
}
className="relative block w-full appearance-none rounded-lg border border-primary-200 px-3 py-2 text-primary-900 focus:z-10 focus:border-primary-600 focus:outline-none focus:ring-primary-600 sm:text-sm"
>
<option value="user">User</option>
<option value="verifier">Verifier</option>
<option value="admin">Admin</option>
</select>
</div>
</div>

{error && (
Expand Down
10 changes: 1 addition & 9 deletions src/lib/authoptions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,14 +11,9 @@ export const authOptions: AuthOptions = {
credentials: {
email: { label: "Email", type: "text" },
password: { label: "Password", type: "password" },
role: { label: "Role", type: "text" },
},
async authorize(credentials) {
if (
!credentials?.email ||
!credentials?.password ||
!credentials?.role
) {
if (!credentials?.email || !credentials?.password) {
throw new Error("Invalid credentials");
}
await dbConnect();
Expand All @@ -35,9 +30,6 @@ export const authOptions: AuthOptions = {
if (!isCorrectPassword) {
throw new Error("Invalid credentials");
}
if (user.role !== credentials.role) {
throw new Error("Invalid role");
}
return {
id: (user._id as ObjectId).toString(),
email: user.email,
Expand Down

0 comments on commit c286ea8

Please sign in to comment.