Skip to content

Commit

Permalink
Added user-log-activity and minor fixes
Browse files Browse the repository at this point in the history
  • Loading branch information
ad956 committed May 31, 2024
1 parent 461584c commit 0aa9c69
Show file tree
Hide file tree
Showing 3 changed files with 20 additions and 6 deletions.
2 changes: 1 addition & 1 deletion app/api/auth/login/route.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import dbConfig from "@lib/db";
import OtpTemplate from "@lib/emails/templates";
import { OtpTemplate } from "@lib/emails/templates";
import { sendEmail } from "@lib/email";
import { render } from "@react-email/render";
import { generateSecureOTP } from "@utils/generateOtp";
Expand Down
2 changes: 1 addition & 1 deletion app/api/auth/signup/route.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import dbConfig from "@lib/db";
import OtpTemplate from "@/lib/emails/templates";
import { OtpTemplate } from "@/lib/emails/templates";
import { sendEmail } from "@lib/email";
import { render } from "@react-email/render";
import { generateSecureOTP } from "@utils/generateOtp";
Expand Down
22 changes: 18 additions & 4 deletions app/api/auth/verifyotp/route.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { setSession } from "@sessions/sessionUtils";
import dbConfig from "@lib/db";
import logUserActivity from "@lib/logs";

type bodyType = {
email: string;
Expand All @@ -23,33 +24,46 @@ export async function POST(req: Request) {
return Response.json({ error: "User role isn't valid." });
}

const result = await checkOTP(body);
const result = await checkOTP(body, req);
return result;
} catch (error) {
console.error("Error during otp verification:", error);
return Response.json({ error: "Internal Server Error" });
}
}
async function checkOTP(body: bodyType) {
async function checkOTP(body: bodyType, req: Request) {
const db = await dbConfig();

const collection = db.collection(body.role);
const email = body.email;

const projection = {
_id: 0,
username: 1,
firstname: 1,
lastname: 1,
otp: 1,
};

const userOTP = await collection.findOne({ email }, { projection });
const user = await collection.findOne({ email }, { projection });

if (!userOTP || userOTP.otp !== body.otp)
if (!user || user.otp !== body.otp)
return Response.json({ error: "OTP Verification Failed" });

await collection.updateOne({ email }, { $set: { otp: "" } });

// setting session for user (stores jwt token in cookies named session)
await setSession(email, body.role);

const userlog = {
username: user.username,
name: `${user.firstname} ${user.lastname}`,
email,
role: body.role,
};

// storing user logs in db
await logUserActivity(userlog, req);

return Response.json({ message: "ok" }, { status: 200 });
}

0 comments on commit 0aa9c69

Please sign in to comment.