57 lines
1.4 KiB
Go
57 lines
1.4 KiB
Go
package storage
|
|
|
|
import (
|
|
"database/sql"
|
|
"log"
|
|
"net/http"
|
|
"time"
|
|
|
|
securityHelpers "synlotto-website/internal/helpers/security"
|
|
templateHelpers "synlotto-website/internal/helpers/template"
|
|
"synlotto-website/internal/logging"
|
|
|
|
"synlotto-website/internal/http/middleware"
|
|
)
|
|
|
|
func AdminOnly(db *sql.DB, next http.HandlerFunc) http.HandlerFunc {
|
|
return middleware.Auth(true)(func(w http.ResponseWriter, r *http.Request) {
|
|
userID, ok := securityHelpers.GetCurrentUserID(r)
|
|
if !ok || !securityHelpers.IsAdmin(db, userID) {
|
|
log.Printf("⛔️ Unauthorized admin attempt: user_id=%v, IP=%s, Path=%s", userID, r.RemoteAddr, r.URL.Path)
|
|
templateHelpers.RenderError(w, r, http.StatusForbidden)
|
|
return
|
|
}
|
|
|
|
ip := r.RemoteAddr
|
|
ua := r.UserAgent()
|
|
path := r.URL.Path
|
|
|
|
_, err := db.Exec(`
|
|
INSERT INTO admin_access_log (user_id, path, ip, user_agent)
|
|
VALUES (?, ?, ?, ?)`,
|
|
userID, path, ip, ua,
|
|
)
|
|
if err != nil {
|
|
log.Printf("⚠️ Failed to log admin access: %v", err)
|
|
}
|
|
|
|
log.Printf("🛡️ Admin access: user_id=%d IP=%s Path=%s", userID, ip, path)
|
|
|
|
next(w, r)
|
|
})
|
|
}
|
|
|
|
func LogLoginAttempt(r *http.Request, username string, success bool) {
|
|
ip := r.RemoteAddr
|
|
userAgent := r.UserAgent()
|
|
|
|
_, err := db.Exec(
|
|
`INSERT INTO audit_login (username, success, ip, user_agent, timestamp)
|
|
VALUES (?, ?, ?, ?, ?)`,
|
|
username, success, ip, userAgent, time.Now().UTC(),
|
|
)
|
|
if err != nil {
|
|
logging.Info("❌ Failed to log login:", err)
|
|
}
|
|
}
|