Skip to content

Commit

Permalink
Added userlog-activity
Browse files Browse the repository at this point in the history
  • Loading branch information
ad956 committed May 31, 2024
1 parent acf0c57 commit 461584c
Showing 1 changed file with 59 additions and 0 deletions.
59 changes: 59 additions & 0 deletions lib/logs/index.tsx
Original file line number Diff line number Diff line change
@@ -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 || "[email protected]",
subject: "Alert: User Login Activity Notification",
html: render(UserActivityTemplate(user_log)),
from: {
name: "Patient Fitness Tracker",
address: "[email protected]",
},
});
} 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;

0 comments on commit 461584c

Please sign in to comment.