feae2e19a1
Update Auth middleware to accept a fallbackToken parameter. When no per-user cookie token is present and GITEA_TOKEN is set in the environment, the middleware uses the env token instead of redirecting to /settings. Cookie tokens still take precedence over the fallback. Add three new unit tests covering: fallback used when no cookie, cookie takes precedence over fallback, and redirect when neither is set. Closes leeworks-agents/gitea-mobile#125 Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
65 lines
2.1 KiB
Go
65 lines
2.1 KiB
Go
package middleware
|
|
|
|
import (
|
|
"context"
|
|
"log/slog"
|
|
"net/http"
|
|
|
|
"gitea.leeworks.dev/0xwheatyz/gitea-mobile/internal/auth"
|
|
)
|
|
|
|
// contextKey is a private type for context keys in this package.
|
|
type contextKey string
|
|
|
|
const (
|
|
// TokenContextKey is the context key for the Gitea API token.
|
|
TokenContextKey contextKey = "gitea_token"
|
|
)
|
|
|
|
// TokenFromContext extracts the Gitea API token from the request context.
|
|
func TokenFromContext(ctx context.Context) string {
|
|
token, _ := ctx.Value(TokenContextKey).(string)
|
|
return token
|
|
}
|
|
|
|
// Auth returns middleware that checks for a valid token cookie.
|
|
// If no cookie token is found and fallbackToken is non-empty, the fallback
|
|
// token is used instead (useful for single-user or service-account deployments
|
|
// where GITEA_TOKEN is set in the environment).
|
|
// Unauthenticated requests are redirected to the settings page.
|
|
// The /health, /settings, and /static/ paths are exempt from auth.
|
|
func Auth(sessionSecret, fallbackToken string) func(http.Handler) http.Handler {
|
|
return func(next http.Handler) http.Handler {
|
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
// Skip auth for exempt paths.
|
|
path := r.URL.Path
|
|
if path == "/health" || path == "/settings" || hasPrefix(path, "/static/") {
|
|
next.ServeHTTP(w, r)
|
|
return
|
|
}
|
|
|
|
token, err := auth.GetToken(r, sessionSecret)
|
|
if err != nil || token == "" {
|
|
// Fall back to environment token if available.
|
|
if fallbackToken != "" {
|
|
slog.Debug("using fallback token from environment", "path", path)
|
|
ctx := context.WithValue(r.Context(), TokenContextKey, fallbackToken)
|
|
next.ServeHTTP(w, r.WithContext(ctx))
|
|
return
|
|
}
|
|
slog.Debug("unauthenticated request, redirecting to settings", "path", path, "error", err)
|
|
http.Redirect(w, r, "/settings", http.StatusSeeOther)
|
|
return
|
|
}
|
|
|
|
// Inject token into request context.
|
|
ctx := context.WithValue(r.Context(), TokenContextKey, token)
|
|
next.ServeHTTP(w, r.WithContext(ctx))
|
|
})
|
|
}
|
|
}
|
|
|
|
func hasPrefix(s, prefix string) bool {
|
|
return len(s) >= len(prefix) && s[:len(prefix)] == prefix
|
|
}
|