77 lines
1.9 KiB
Go
77 lines
1.9 KiB
Go
package auditlogStorage
|
|
|
|
import (
|
|
"context"
|
|
"database/sql"
|
|
"time"
|
|
|
|
"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 (?, ?, ?, ?, ?, ?)
|
|
`
|
|
|
|
// 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: %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()
|
|
|
|
_, err := db.ExecContext(ctx, insertRegistrationSQL,
|
|
userID, username, email, ip, userAgent, time.Now().UTC(),
|
|
)
|
|
if err != nil {
|
|
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)
|
|
}
|
|
}
|