-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
1 changed file
with
59 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; |