fix: resolve context key cycle for admin check

This commit is contained in:
2026-04-22 21:23:38 +02:00
parent 77f0daca26
commit ee05ad7511
8 changed files with 23 additions and 36 deletions

View File

@@ -7,12 +7,7 @@ import (
"mal/api/auth"
"mal/internal/db"
)
type contextKey string
const (
UserContextKey contextKey = "user"
webcontext "mal/web/context"
)
func Auth(authService *auth.Service) func(http.Handler) http.Handler {
@@ -20,20 +15,17 @@ func Auth(authService *auth.Service) func(http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
cookie, err := r.Cookie("session_id")
if err != nil {
// No session cookie, user is unauthenticated. Proceed, but not logged in.
next.ServeHTTP(w, r)
return
}
user, err := authService.ValidateSession(r.Context(), cookie.Value)
if err != nil {
// Invalid session, proceed as unauthenticated
next.ServeHTTP(w, r)
return
}
// Valid session, bind user to context
ctx := context.WithValue(r.Context(), UserContextKey, user)
ctx := context.WithValue(r.Context(), webcontext.UserKey, user)
next.ServeHTTP(w, r.WithContext(ctx))
})
}
@@ -41,7 +33,7 @@ func Auth(authService *auth.Service) func(http.Handler) http.Handler {
func RequireAuth(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
user, ok := r.Context().Value(UserContextKey).(*database.User)
user, ok := r.Context().Value(webcontext.UserKey).(*database.User)
if !ok || user == nil {
if strings.HasPrefix(r.URL.Path, "/api/") {
w.Header().Set("HX-Redirect", "/login")
@@ -56,9 +48,9 @@ func RequireAuth(next http.Handler) http.Handler {
}
func GetUser(ctx context.Context) *database.User {
user, ok := ctx.Value(UserContextKey).(*database.User)
user, ok := ctx.Value(webcontext.UserKey).(*database.User)
if !ok {
return nil
}
return user
}
}