package middleware import ( "context" "net/http" "strings" "aggios-app/backend/internal/config" "github.com/golang-jwt/jwt/v5" ) type contextKey string const UserIDKey contextKey = "userID" const TenantIDKey contextKey = "tenantID" // Auth validates JWT tokens func Auth(cfg *config.Config) func(http.Handler) http.Handler { return func(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { authHeader := r.Header.Get("Authorization") if authHeader == "" { http.Error(w, "Unauthorized", http.StatusUnauthorized) return } bearerToken := strings.Split(authHeader, " ") if len(bearerToken) != 2 || bearerToken[0] != "Bearer" { http.Error(w, "Invalid token format", http.StatusUnauthorized) return } token, err := jwt.Parse(bearerToken[1], func(token *jwt.Token) (interface{}, error) { return []byte(cfg.JWT.Secret), nil }) if err != nil || !token.Valid { http.Error(w, "Invalid token", http.StatusUnauthorized) return } claims, ok := token.Claims.(jwt.MapClaims) if !ok { http.Error(w, "Invalid token claims", http.StatusUnauthorized) return } // Verificar se user_id existe e é do tipo correto userIDClaim, ok := claims["user_id"] if !ok || userIDClaim == nil { http.Error(w, "Missing user_id in token", http.StatusUnauthorized) return } userID, ok := userIDClaim.(string) if !ok { http.Error(w, "Invalid user_id format in token", http.StatusUnauthorized) return } // tenant_id pode ser nil para SuperAdmin var tenantID string if tenantIDClaim, ok := claims["tenant_id"]; ok && tenantIDClaim != nil { tenantID, _ = tenantIDClaim.(string) } ctx := context.WithValue(r.Context(), UserIDKey, userID) ctx = context.WithValue(ctx, TenantIDKey, tenantID) next.ServeHTTP(w, r.WithContext(ctx)) }) } }