From e1fa6c502e796e80b0b86ea13e1cd7182298cf08 Mon Sep 17 00:00:00 2001 From: H3ALY Date: Tue, 28 Oct 2025 15:26:43 +0000 Subject: [PATCH] Centralize audit SQL + writers --- internal/storage/auditlog/create.go | 54 ++++++++++++++++++++++++----- 1 file changed, 45 insertions(+), 9 deletions(-) diff --git a/internal/storage/auditlog/create.go b/internal/storage/auditlog/create.go index 6546cf5..6f65a2d 100644 --- a/internal/storage/auditlog/create.go +++ b/internal/storage/auditlog/create.go @@ -1,4 +1,4 @@ -package storage +package auditlogStorage import ( "context" @@ -8,25 +8,48 @@ import ( "synlotto-website/internal/logging" ) +const insertAdminAccessSQL = ` + INSERT INTO admin_access_log + (user_id, path, ip, user_agent, accessed_at) + VALUES (?, ?, ?, ?, ?) + ` +const insertLoginSQL = ` + INSERT INTO audit_login + (user_id, username, success, ip, user_agent, timestamp) + VALUES (?, ?, ?, ?, ?, ?) + ` + const insertRegistrationSQL = ` INSERT INTO audit_registration (user_id, username, email, ip, user_agent, timestamp) VALUES (?, ?, ?, ?, ?, ?) ` -// Todo has to add in - db *sql.DB to make this work should this not be an import as all functions use it, more importantly no functions in storage just sql? -// Handler Call - auditlogStorage.LogLoginAttempt(db, r.RemoteAddr, r.UserAgent(), username, ok) -func LogLoginAttempt(db *sql.DB, rIP, rUA, username string, success bool) { - _, err := db.Exec( - `INSERT INTO audit_login (username, success, ip, user_agent, timestamp) - VALUES ($1, $2, $3, $4, $5)`, - username, success, rIP, rUA, time.Now().UTC(), +// LogLoginAttempt stores a login attempt. Pass userID if known; otherwise it's NULL. +func LogLoginAttempt(db *sql.DB, ip, userAgent, username string, success bool, userID ...int64) { + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) + defer cancel() + + var uid sql.NullInt64 + if len(userID) > 0 { + uid.Valid = true + uid.Int64 = userID[0] + } + + _, err := db.ExecContext(ctx, insertLoginSQL, + uid, + username, + success, + ip, + userAgent, + time.Now().UTC(), ) if err != nil { - logging.Info("❌ Failed to log login:", err) + logging.Info("❌ Failed to log login: %v", err) } } +// LogSignup stores a registration event. func LogSignup(db *sql.DB, userID int64, username, email, ip, userAgent string) { ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) defer cancel() @@ -38,3 +61,16 @@ func LogSignup(db *sql.DB, userID int64, username, email, ip, userAgent string) logging.Info("❌ Failed to log registration: %v", err) } } + +// LogAdminAccess stores an admin access record. +func LogAdminAccess(db *sql.DB, userID int64, path, ip, userAgent string, at time.Time) { + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) + defer cancel() + + _, err := db.ExecContext(ctx, insertAdminAccessSQL, + userID, path, ip, userAgent, at, + ) + if err != nil { + logging.Info("❌ Failed to log admin access: %v", err) + } +}