From 1780cea340a8aedd546f0a5139cc17e5581e4735 Mon Sep 17 00:00:00 2001 From: cclohmar Date: Sun, 14 Jun 2026 14:58:02 +0000 Subject: [PATCH] fix(auth): export IsAdmin, fix bearer token fallback chain --- src/core/auth/middleware.go | 6 +++--- src/main.go | 33 +++++++++++++++++---------------- 2 files changed, 20 insertions(+), 19 deletions(-) diff --git a/src/core/auth/middleware.go b/src/core/auth/middleware.go index aba3ac5..56e4f7b 100644 --- a/src/core/auth/middleware.go +++ b/src/core/auth/middleware.go @@ -25,7 +25,7 @@ func (rc *RoleChecker) RequireAdmin(next http.Handler) http.Handler { return } - isAdmin, err := rc.isAdmin(userID) + isAdmin, err := rc.IsAdmin(userID) if err != nil || !isAdmin { http.Error(w, `{"error":"forbidden"}`, http.StatusForbidden) return @@ -35,8 +35,8 @@ func (rc *RoleChecker) RequireAdmin(next http.Handler) http.Handler { }) } -// isAdmin checks if a user has the admin role. -func (rc *RoleChecker) isAdmin(username string) (bool, error) { +// IsAdmin checks if a user has the admin role. +func (rc *RoleChecker) IsAdmin(username string) (bool, error) { var role string err := rc.db.QueryRow("SELECT role FROM users WHERE username = ?", username).Scan(&role) if err == sql.ErrNoRows { diff --git a/src/main.go b/src/main.go index bfe1c6d..1c1a077 100644 --- a/src/main.go +++ b/src/main.go @@ -1,6 +1,7 @@ package main import ( + "context" "flag" "fmt" "log/slog" @@ -130,26 +131,26 @@ func main() { } uiHandler.RegisterRoutes(mux, combinedAuth) - // --- Admin routes: session+role OR bearer token --- - adminRoleAuth := func(next http.Handler) http.Handler { - return sessionStore.SessionMiddleware(roleChecker.RequireAdmin(next)) - } + // --- Admin auth: session (with admin role) OR bearer token --- bearerAuth := admin.TokenAuthMiddleware(cfg.Admin.SecretToken) - - // Combined: try session+role first, fall back to bearer token adminAuth := func(next http.Handler) http.Handler { - return adminRoleAuth(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - // Check if session user exists and has admin role - userID, ok := auth.GetUserID(r) - if ok { - // Session is valid — already verified by RequireAdmin - _ = userID - next.ServeHTTP(w, r) - return + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + // First, try session-based authentication + cookie, err := r.Cookie("nextwks_session") + if err == nil && cookie != nil { + session, err := sessionStore.ValidateSession(cookie.Value) + if err == nil && session != nil { + isAdmin, _ := roleChecker.IsAdmin(session.UserID) + if isAdmin { + ctx := context.WithValue(r.Context(), auth.ContextUserID, session.UserID) + next.ServeHTTP(w, r.WithContext(ctx)) + return + } + } } - // No valid session — try bearer token + // Fall back to bearer token bearerAuth(next).ServeHTTP(w, r) - })) + }) } adminHandler.RegisterRoutes(mux, adminAuth)