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.
This commit is contained in:
2026-01-06 15:42:03 +01:00
parent e506d76e6a
commit 4eb18388db
27 changed files with 965 additions and 6 deletions
+19 -6
View File
@@ -5,6 +5,7 @@ import (
"net/http"
"strings"
"git.jnss.me/joakim/opal/internal/auth"
"git.jnss.me/joakim/opal/internal/engine"
)
@@ -12,8 +13,10 @@ type contextKey string
const userIDKey contextKey = "userID"
// AuthMiddleware validates API keys and adds userID to context
// 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
@@ -30,17 +33,27 @@ func AuthMiddleware() func(http.Handler) http.Handler {
return
}
apiKey := parts[1]
token := parts[1]
// Validate API key
valid, userID, err := engine.ValidateAPIKey(apiKey)
// 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 API key")
Error(w, http.StatusInternalServerError, "failed to validate credentials")
return
}
if !valid {
Error(w, http.StatusUnauthorized, "invalid API key")
Error(w, http.StatusUnauthorized, "invalid credentials")
return
}