From 461584c76f09cf9ef74f99e98c5367b55e594cd8 Mon Sep 17 00:00:00 2001 From: Anand Suthar Date: Fri, 31 May 2024 18:37:04 +0530 Subject: [PATCH] Added userlog-activity --- lib/logs/index.tsx | 59 ++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 lib/logs/index.tsx diff --git a/lib/logs/index.tsx b/lib/logs/index.tsx new file mode 100644 index 00000000..0e05c8ee --- /dev/null +++ b/lib/logs/index.tsx @@ -0,0 +1,59 @@ +import dbConfig from "../db"; +import { sendEmail } from "../email"; +import { render } from "@react-email/render"; +import { UserActivityTemplate } from "../emails/templates"; + +type userlogType = { + username: string; + name: string; + email: string; + role: string; +}; + +async function logUserActivity(userlog: userlogType, req: Request) { + const db = await dbConfig(); + + try { + const logs_collection = db.collection("user_logs"); + + const user_log = { + username: userlog.username, + name: userlog.name, + email: userlog.email, + action: "Login", + userType: userlog.role, + timing: new Date().toISOString(), + device: req.headers.get("user-agent") || "", + ip: (req.headers.get("x-forwarded-for") ?? "127.0.0.1") + .split(",")[0] + .trim(), + location: await fetchLocationByIP(), + }; + + //stores in user_logs + await logs_collection.insertOne(user_log); + + await sendEmail({ + to: process.env.LOGGER_EMAIL || "yourmail@example.com", + subject: "Alert: User Login Activity Notification", + html: render(UserActivityTemplate(user_log)), + from: { + name: "Patient Fitness Tracker", + address: "support@patientfitnesstracker.com", + }, + }); + } catch (error: any) { + console.error(`While logging user activities got an error : ${error.msg}`); + } +} + +async function fetchLocationByIP() { + const request = await fetch( + `https://ipinfo.io/json?token=${process.env.IP_INFO_TOKEN}` + ); + const jsonResponse = await request.json(); + const location = `${jsonResponse.city}, ${jsonResponse.region}, ${jsonResponse.country}`; + return location; +} + +export default logUserActivity;