37 lines
1.3 KiB
TypeScript
37 lines
1.3 KiB
TypeScript
import { createClient } from "@/lib/supabase/server"
|
|
import { createAdminClient } from "@/lib/supabase/admin"
|
|
import { headers } from "next/headers"
|
|
|
|
export type SecurityEventType = 'login_success' | 'login_failed' | 'otp_sent' | 'otp_verified' | 'otp_failed' | 'logout' | 'master_otp_used'
|
|
|
|
export async function logActivity(
|
|
userId: string | null,
|
|
eventType: SecurityEventType,
|
|
details: Record<string, unknown> = {}
|
|
) {
|
|
try {
|
|
// Use Admin Client to bypass RLS for inserting logs
|
|
// This is crucial because logging often happens when user is not yet authenticated (e.g. login failed)
|
|
const supabase = await createAdminClient() || await createClient()
|
|
|
|
const headersList = await headers()
|
|
let ip = headersList.get("x-forwarded-for") || headersList.get("x-real-ip") || 'unknown'
|
|
if (ip.includes(',')) ip = ip.split(',')[0].trim()
|
|
if (ip === '::1') ip = '127.0.0.1'
|
|
const userAgent = headersList.get("user-agent") || 'unknown'
|
|
|
|
await supabase.from('auth_logs').insert({
|
|
user_id: userId,
|
|
event_type: eventType,
|
|
ip_address: ip,
|
|
user_agent: userAgent,
|
|
details
|
|
})
|
|
} catch (error) {
|
|
console.error('Failed to log activity:', error)
|
|
// Fail silently to not block user flow
|
|
}
|
|
}
|
|
|
|
|