feat(backend): update auth middleware
Ultraworked with [Sisyphus](https://github.com/code-yeongyu/oh-my-openagent) Co-authored-by: Sisyphus <clio-agent@sisyphuslabs.ai>
This commit is contained in:
+15
-3
@@ -2,6 +2,7 @@ package mw
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
@@ -50,7 +51,9 @@ func OptionalAuth(next http.Handler) http.Handler {
|
||||
tokenString := strings.TrimPrefix(authHeader, "Bearer ")
|
||||
|
||||
userID, role, jti, err := auth.VerifyToken(tokenString, r.Context())
|
||||
if err == nil {
|
||||
if err != nil {
|
||||
log.Printf("OptionalAuth: invalid token: %v", err)
|
||||
} else {
|
||||
ctx := context.WithValue(r.Context(), UserIDKey, userID)
|
||||
ctx = context.WithValue(ctx, UserRoleKey, role)
|
||||
ctx = context.WithValue(ctx, JTIKey, jti)
|
||||
@@ -97,9 +100,18 @@ func RequireVerified(next http.Handler) http.Handler {
|
||||
return RequireRole("verified_email", "admin")(next)
|
||||
}
|
||||
|
||||
// RequireAdmin middleware - only allows admin
|
||||
// RequireAdmin middleware - only allows admin and validates the user ID is present
|
||||
// in context, so handlers don't need to re-check. The user ID is always set by
|
||||
// RequireAuth before this runs, but this adds a defensive safety net.
|
||||
func RequireAdmin(next http.Handler) http.Handler {
|
||||
return RequireRole("admin")(next)
|
||||
return RequireRole("admin")(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
uid, ok := r.Context().Value(UserIDKey).(string)
|
||||
if !ok || uid == "" {
|
||||
http.Error(w, "Authentication required", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
next.ServeHTTP(w, r)
|
||||
}))
|
||||
}
|
||||
|
||||
// Helper functions to get user info from context
|
||||
|
||||
Reference in New Issue
Block a user