Refactor: Centralize template loading and improve error handling

- Introduced helpers.LoadTemplateFiles() for consistent layout + topbar rendering
- Replaced repeated template.ParseFiles() calls across handlers
- Created generic RenderError(w, r, statusCode) helper
- Replaced old Render403 with flexible RenderError
- Updated AdminOnly middleware to render 403 errors with context
- Added 500.html template for graceful panic fallback
- Prepared structure for future error codes (404, 429, etc.)
This commit is contained in:
2025-04-02 09:12:13 +01:00
parent f5653f737d
commit 2498b33a9c
16 changed files with 69 additions and 106 deletions

View File

@@ -7,12 +7,12 @@ import (
"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)
log.Printf("⛔️ Unauthorized admin attempt: user_id=%v, IP=%s, Path=%s", userID, r.RemoteAddr, r.URL.Path)
helpers.RenderError(w, r, http.StatusForbidden)
return
}
@@ -20,7 +20,6 @@ func AdminOnly(db *sql.DB, next http.HandlerFunc) http.HandlerFunc {
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 (?, ?, ?, ?)`,
@@ -30,9 +29,10 @@ func AdminOnly(db *sql.DB, next http.HandlerFunc) http.HandlerFunc {
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)
})
}
// ToDo need to look into audit/access log tables and consolidate