39 lines
899 B
Go
39 lines
899 B
Go
package middleware
|
|
|
|
import (
|
|
"database/sql"
|
|
"log"
|
|
"net/http"
|
|
"synlotto-website/helpers"
|
|
)
|
|
|
|
// Wraps an existing handler but checks is_admin before executing
|
|
func AdminOnly(db *sql.DB, next http.HandlerFunc) http.HandlerFunc {
|
|
return Auth(true)(func(w http.ResponseWriter, r *http.Request) {
|
|
userID, ok := helpers.GetCurrentUserID(r)
|
|
if !ok || !helpers.IsAdmin(db, userID) {
|
|
http.Redirect(w, r, "/", http.StatusSeeOther)
|
|
return
|
|
}
|
|
|
|
ip := r.RemoteAddr
|
|
ua := r.UserAgent()
|
|
path := r.URL.Path
|
|
|
|
// Store log entry in DB
|
|
_, 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)
|
|
}
|
|
|
|
// Optional: still log to console
|
|
log.Printf("🛡️ Admin access: user_id=%d IP=%s Path=%s", userID, ip, path)
|
|
|
|
next(w, r)
|
|
})
|
|
}
|