Skip to content

Commit

Permalink
feat(auth): Enhance verify OTP API route
Browse files Browse the repository at this point in the history
- Implemented the �erifyOTP API route to handle user OTP verification
- Utilized the �llowedroles constant from the @Constants module to restrict access to the �erifyOTP endpoint based on user roles
- Leveraged the getModelByRole utility function from the @utils module to dynamically retrieve the appropriate user model based on the user's role
  • Loading branch information
ad956 committed Jul 14, 2024
1 parent c898a98 commit e40ecbe
Showing 1 changed file with 8 additions and 27 deletions.
35 changes: 8 additions & 27 deletions app/api/auth/verifyotp/route.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import { setSession } from "@sessions/sessionUtils";
import dbConfig from "@utils/db";
import { dbConfig, getModelByRole } from "@utils/index";
import { allowedRoles } from "@constants/index";
import logUserActivity from "@lib/logs";
import { Doctor, Hospital, Patient, Receptionist } from "@models/index";

type bodyType = {
email: string;
Expand All @@ -10,8 +10,6 @@ type bodyType = {
action: string;
};

const allowedRoles = ["patient", "receptionist", "doctor", "hospital"];

export async function POST(req: Request) {
try {
const body: bodyType = await req.json();
Expand All @@ -37,7 +35,12 @@ export async function POST(req: Request) {
async function checkOTP(body: bodyType, req: Request) {
await dbConfig();

const user = await getUserModel(body.email, body.role);
const UserModel = getModelByRole(body.role);

const user = await UserModel.findOne(
{ email: body.email },
{ _id: 0, username: 1, firstname: 1, lastname: 1, otp: 1 }
);

if (!user || user.otp !== body.otp)
return Response.json({ error: "OTP Verification Failed" });
Expand All @@ -60,25 +63,3 @@ async function checkOTP(body: bodyType, req: Request) {

return Response.json({ message: "ok" }, { status: 200 });
}
// retrieves a user from the database based on email and role
async function getUserModel(email: string, role: string) {
const projection = {
_id: 0,
username: 1,
firstname: 1,
lastname: 1,
otp: 1,
};
switch (role) {
case "patient":
return await Patient.findOne({ email }, projection);
case "receptionist":
return await Receptionist.findOne({ email }, projection);
case "doctor":
return await Doctor.findOne({ email }, projection);
case "hospital":
return await Hospital.findOne({ email }, projection);
default:
return null;
}
}

0 comments on commit e40ecbe

Please sign in to comment.