From ac84571c55da65ec058d5ad26f71832dfd28385f Mon Sep 17 00:00:00 2001 From: Tiago Yamamoto Date: Wed, 24 Dec 2025 15:14:46 -0300 Subject: [PATCH] debug(auth): add detailed logging to HeaderAuthGuard middleware --- .../api/middleware/auth_middleware.go | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/backend/internal/api/middleware/auth_middleware.go b/backend/internal/api/middleware/auth_middleware.go index f3b42d1..0784cc3 100644 --- a/backend/internal/api/middleware/auth_middleware.go +++ b/backend/internal/api/middleware/auth_middleware.go @@ -2,6 +2,7 @@ package middleware import ( "context" + "fmt" "net/http" "strings" @@ -27,13 +28,21 @@ func NewMiddleware(authService ports.AuthService) *Middleware { // HeaderAuthGuard ensures valid JWT token is present. func (m *Middleware) HeaderAuthGuard(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + fmt.Printf("[AUTH DEBUG] === HeaderAuthGuard START ===\n") + fmt.Printf("[AUTH DEBUG] Method: %s, Path: %s\n", r.Method, r.URL.Path) + authHeader := r.Header.Get("Authorization") var token string + fmt.Printf("[AUTH DEBUG] Authorization Header: '%s'\n", authHeader) + if authHeader != "" { parts := strings.Split(authHeader, " ") if len(parts) == 2 && parts[0] == "Bearer" { token = parts[1] + fmt.Printf("[AUTH DEBUG] Token from Header (first 20 chars): '%s...'\n", token[:min(20, len(token))]) + } else { + fmt.Printf("[AUTH DEBUG] Invalid header format: %d parts, first part: '%s'\n", len(parts), parts[0]) } } @@ -42,24 +51,34 @@ func (m *Middleware) HeaderAuthGuard(next http.Handler) http.Handler { cookie, err := r.Cookie("jwt") if err == nil { token = cookie.Value + fmt.Printf("[AUTH DEBUG] Token from Cookie (first 20 chars): '%s...'\n", token[:min(20, len(token))]) + } else { + fmt.Printf("[AUTH DEBUG] No jwt cookie found: %v\n", err) } } if token == "" { + fmt.Printf("[AUTH DEBUG] No token found - returning 401\n") http.Error(w, "Missing Authorization Header or Cookie", http.StatusUnauthorized) return } + + fmt.Printf("[AUTH DEBUG] Validating token...\n") claims, err := m.authService.ValidateToken(token) if err != nil { + fmt.Printf("[AUTH DEBUG] Token validation FAILED: %v\n", err) http.Error(w, "Invalid Token: "+err.Error(), http.StatusUnauthorized) return } + fmt.Printf("[AUTH DEBUG] Token VALID! Claims: sub=%v, tenant=%v, roles=%v\n", claims["sub"], claims["tenant"], claims["roles"]) + // Inject into Context ctx := context.WithValue(r.Context(), ContextUserID, claims["sub"]) ctx = context.WithValue(ctx, ContextTenantID, claims["tenant"]) ctx = context.WithValue(ctx, ContextRoles, claims["roles"]) + fmt.Printf("[AUTH DEBUG] === HeaderAuthGuard SUCCESS ===\n") next.ServeHTTP(w, r.WithContext(ctx)) }) }