Files
garage/backend/internal/auth/middleware.go
T
2026-08-06 18:26:45 +12:00

43 lines
1.2 KiB
Go

package auth
import (
"context"
"net/http"
)
type contextKey string
const userIDContextKey contextKey = "userID"
// RequireAuth reads the session cookie, verifies the JWT, and injects the
// internal user ID into the request context. Responds 401 if missing/invalid.
// This is the only route guard the app needs — every non-auth API route is
// wrapped with it.
func RequireAuth(jwtSecret string) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
cookie, err := r.Cookie(SessionCookieName)
if err != nil {
http.Error(w, "unauthorized", http.StatusUnauthorized)
return
}
claims, err := ParseSessionJWT(jwtSecret, cookie.Value)
if err != nil {
http.Error(w, "unauthorized", http.StatusUnauthorized)
return
}
ctx := context.WithValue(r.Context(), userIDContextKey, claims.Subject)
next.ServeHTTP(w, r.WithContext(ctx))
})
}
}
// UserIDFromContext returns the authenticated user's internal UUID. Only
// valid on requests that passed through RequireAuth.
func UserIDFromContext(ctx context.Context) (string, bool) {
id, ok := ctx.Value(userIDContextKey).(string)
return id, ok
}