From 6795fa130b3521e245be196809feceb6e29b66a0 Mon Sep 17 00:00:00 2001 From: Lea Date: Fri, 19 Jan 2024 14:18:23 +0100 Subject: [PATCH] log login events --- src/app/api/auth/[...nextauth]/route.ts | 8 ++++++++ src/lib/audit.ts | 22 +++++++++++++--------- 2 files changed, 21 insertions(+), 9 deletions(-) diff --git a/src/app/api/auth/[...nextauth]/route.ts b/src/app/api/auth/[...nextauth]/route.ts index f984a0d..33fce79 100644 --- a/src/app/api/auth/[...nextauth]/route.ts +++ b/src/app/api/auth/[...nextauth]/route.ts @@ -3,6 +3,7 @@ import CredentialProvider from "next-auth/providers/credentials"; import { sha256sum } from "@/lib/util"; import { validateCredentials } from "@/lib/db"; import { GRAVATAR_DEFAULT } from "@/lib/constants"; +import { auditLogRaw } from "@/lib/audit"; const authOptions: AuthOptions = { providers: [ @@ -17,8 +18,15 @@ const authOptions: AuthOptions = { if (credentials && await validateCredentials(credentials.email, credentials.password)) { console.log(`[${credentials.email}] Authentication succeeded`); + const emailHash = sha256sum(credentials.email.trim().toLowerCase()); + await auditLogRaw({ + user: credentials.email, + ts: new Date().toISOString(), + action: "login", + }); + return { id: credentials.email, email: credentials.email, diff --git a/src/lib/audit.ts b/src/lib/audit.ts index 29ea040..4cf893e 100644 --- a/src/lib/audit.ts +++ b/src/lib/audit.ts @@ -8,7 +8,7 @@ export type AuditLog = { user?: string | null, ts: string, action: AuditLogAction, - data: any, + data?: any, } export function auditLog(action: AuditLogAction, data?: any) { @@ -23,16 +23,20 @@ export function auditLog(action: AuditLogAction, data?: any) { data: data, }; - console.log("Audit event:", log); - - if (process.env.AUDIT_FILE_PATH) { - await fs.appendFile( - process.env.AUDIT_FILE_PATH, - JSON.stringify(log) + "\n", - ); - } + await auditLogRaw(log); } catch (e) { console.error("Failed to write to log file:", e); } })(); } + +export async function auditLogRaw(log: AuditLog) { + console.log("Audit event:", log); + + if (process.env.AUDIT_FILE_PATH) { + await fs.appendFile( + process.env.AUDIT_FILE_PATH, + JSON.stringify(log) + "\n", + ); + } +}