Files
tiny-forge/internal/auth/middleware.go
T
alexei.dolgolyov 98ee2bcd9a feat: auth system hardening with token revocation, password management, and error sanitization
- Add token revocation with in-memory blacklist and periodic cleanup (SEC-M1)
- Add POST /api/auth/logout endpoint
- Fix OIDC auth_token cookie to HttpOnly with exchange endpoint (SEC-H3)
- Add password complexity validation (min 8 chars) (SEC-M2)
- Prevent admin self-deletion (SEC-M3)
- Add PUT /api/auth/users/{uid} for role/email updates (FUNC-M1)
- Add PUT /api/auth/users/{uid}/password for password changes (FUNC-H1)
- Sanitize error messages in auth handlers (SEC-M4)
2026-04-04 12:43:45 +03:00

74 lines
2.3 KiB
Go

package auth
import (
"context"
"net/http"
"strings"
)
// contextKey is the type for context value keys used by the auth package.
type contextKey string
const claimsKey contextKey = "auth_claims"
// Middleware returns an HTTP middleware that protects routes by requiring a valid JWT.
// It extracts the token from the Authorization header (Bearer scheme) or the "token"
// query parameter (for SSE connections).
// Unauthenticated requests receive a 401 JSON response.
func Middleware(la *LocalAuth) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
tokenStr := ExtractToken(r)
if tokenStr == "" {
http.Error(w, `{"success":false,"error":"authentication required"}`, http.StatusUnauthorized)
return
}
claims, err := la.ValidateToken(tokenStr)
if err != nil {
http.Error(w, `{"success":false,"error":"invalid or expired token"}`, http.StatusUnauthorized)
return
}
if la.IsRevoked(tokenStr) {
http.Error(w, `{"success":false,"error":"token has been revoked"}`, http.StatusUnauthorized)
return
}
ctx := context.WithValue(r.Context(), claimsKey, claims)
next.ServeHTTP(w, r.WithContext(ctx))
})
}
}
// AdminOnly returns an HTTP middleware that requires the authenticated user to have
// the "admin" role.
func AdminOnly(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
claims, ok := ClaimsFromContext(r.Context())
if !ok || claims.Role != "admin" {
http.Error(w, `{"success":false,"error":"admin access required"}`, http.StatusForbidden)
return
}
next.ServeHTTP(w, r)
})
}
// ClaimsFromContext retrieves the authenticated user's claims from the request context.
func ClaimsFromContext(ctx context.Context) (Claims, bool) {
claims, ok := ctx.Value(claimsKey).(Claims)
return claims, ok
}
// ExtractToken gets the JWT from the Authorization header or "token" query param.
func ExtractToken(r *http.Request) string {
// Try Authorization: Bearer <token>
authHeader := r.Header.Get("Authorization")
if strings.HasPrefix(authHeader, "Bearer ") {
return strings.TrimPrefix(authHeader, "Bearer ")
}
// Fall back to query parameter (used by SSE and browser-based connections).
return r.URL.Query().Get("token")
}