caddyauth: Set authentication provider error in placeholder for handle_errors directive

This commit is contained in:
Steffen Busch 2025-03-29 10:36:33 +01:00
parent ea77a9ab67
commit c500c55375

View File

@ -17,6 +17,7 @@ package caddyauth
import ( import (
"fmt" "fmt"
"net/http" "net/http"
"strings"
"go.uber.org/zap" "go.uber.org/zap"
"go.uber.org/zap/zapcore" "go.uber.org/zap/zapcore"
@ -71,6 +72,7 @@ func (a *Authentication) Provision(ctx caddy.Context) error {
} }
func (a Authentication) ServeHTTP(w http.ResponseWriter, r *http.Request, next caddyhttp.Handler) error { func (a Authentication) ServeHTTP(w http.ResponseWriter, r *http.Request, next caddyhttp.Handler) error {
repl := r.Context().Value(caddy.ReplacerCtxKey).(*caddy.Replacer)
var user User var user User
var authed bool var authed bool
var err error var err error
@ -80,6 +82,10 @@ func (a Authentication) ServeHTTP(w http.ResponseWriter, r *http.Request, next c
if c := a.logger.Check(zapcore.ErrorLevel, "auth provider returned error"); c != nil { if c := a.logger.Check(zapcore.ErrorLevel, "auth provider returned error"); c != nil {
c.Write(zap.String("provider", provName), zap.Error(err)) c.Write(zap.String("provider", provName), zap.Error(err))
} }
// Set the error from the authentication provider in a placeholder,
// so it can be used in the handle_errors directive.
sanitizedProvName := strings.ReplaceAll(provName, " ", "_")
repl.Set(fmt.Sprintf("http.auth.%s.error", sanitizedProvName), err.Error())
continue continue
} }
if authed { if authed {
@ -90,7 +96,6 @@ func (a Authentication) ServeHTTP(w http.ResponseWriter, r *http.Request, next c
return caddyhttp.Error(http.StatusUnauthorized, fmt.Errorf("not authenticated")) return caddyhttp.Error(http.StatusUnauthorized, fmt.Errorf("not authenticated"))
} }
repl := r.Context().Value(caddy.ReplacerCtxKey).(*caddy.Replacer)
repl.Set("http.auth.user.id", user.ID) repl.Set("http.auth.user.id", user.ID)
for k, v := range user.Metadata { for k, v := range user.Metadata {
repl.Set("http.auth.user."+k, v) repl.Set("http.auth.user."+k, v)