Files
gems/opal-task/internal/api/middleware.go
T
joakim 4eb18388db feat(backend): add OAuth2/JWT authentication support
- Add OAuth2 client for Authentik integration
- Implement JWT token generation and validation
- Add refresh token support with database storage
- Update database schema with oauth_subject, oauth_provider, and refresh_tokens table
- Create auth package with config, jwt, oauth, and token management
- Add OAuth endpoints: /auth/login, /auth/callback, /auth/refresh, /auth/logout
- Update AuthMiddleware to support both JWT and API key authentication
- Add user helper functions for OAuth user creation and retrieval
- Add .env.example with OAuth configuration template

API keys still work for CLI compatibility while JWT tokens support web/mobile clients.
2026-01-06 15:42:03 +01:00

93 lines
2.4 KiB
Go

package api
import (
"context"
"net/http"
"strings"
"git.jnss.me/joakim/opal/internal/auth"
"git.jnss.me/joakim/opal/internal/engine"
)
type contextKey string
const userIDKey contextKey = "userID"
// AuthMiddleware validates JWT tokens or API keys and adds userID to context
func AuthMiddleware() func(http.Handler) http.Handler {
authCfg := auth.LoadConfig()
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Get Authorization header
authHeader := r.Header.Get("Authorization")
if authHeader == "" {
Error(w, http.StatusUnauthorized, "missing authorization header")
return
}
// Parse "Bearer <token>"
parts := strings.SplitN(authHeader, " ", 2)
if len(parts) != 2 || parts[0] != "Bearer" {
Error(w, http.StatusUnauthorized, "invalid authorization header format")
return
}
token := parts[1]
// Try JWT first if OAuth is enabled
if authCfg.OAuthEnabled {
if claims, err := auth.ValidateJWT(token, authCfg); err == nil {
// Valid JWT - add userID to context
ctx := context.WithValue(r.Context(), userIDKey, claims.UserID)
next.ServeHTTP(w, r.WithContext(ctx))
return
}
}
// Fall back to API key validation (for CLI compatibility)
valid, userID, err := engine.ValidateAPIKey(token)
if err != nil {
Error(w, http.StatusInternalServerError, "failed to validate credentials")
return
}
if !valid {
Error(w, http.StatusUnauthorized, "invalid credentials")
return
}
// Add userID to context
ctx := context.WithValue(r.Context(), userIDKey, userID)
next.ServeHTTP(w, r.WithContext(ctx))
})
}
}
// GetUserID extracts userID from request context
func GetUserID(r *http.Request) int {
userID, ok := r.Context().Value(userIDKey).(int)
if !ok {
return 0
}
return userID
}
// CORSMiddleware adds CORS headers for future web frontend
func CORSMiddleware() func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization")
if r.Method == "OPTIONS" {
w.WriteHeader(http.StatusOK)
return
}
next.ServeHTTP(w, r)
})
}
}