Files
tiny-forge/internal/auth/middleware.go
alexei.dolgolyov 32de5b26a8 feat(docker-watcher): phase 12 - hardening
Blue-green zero-downtime deploys, promote flow validation.
Dual auth: local (bcrypt + JWT) and OAuth2/OIDC (any provider).
Auth middleware, login page, auth settings UI.
Structured logging (slog JSON), config export to YAML.
Graceful shutdown with deploy draining.
Multi-stage Dockerfile and production docker-compose.yml.
Swap phase order: Volumes & Env before UI Polish.
2026-03-27 23:20:56 +03:00

69 lines
2.2 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
}
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")
}