fix: auth and ratelimit middleware return JSON errors instead of text/plain

This commit is contained in:
2026-07-11 16:05:56 +01:00
parent e4a56ab04d
commit ce0bb43ebf
2 changed files with 6 additions and 6 deletions
+5 -5
View File
@@ -23,7 +23,7 @@ func RequireAuth(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
authHeader := r.Header.Get("Authorization")
if authHeader == "" || !strings.HasPrefix(authHeader, "Bearer ") {
http.Error(w, "missing or invalid authorization header", http.StatusUnauthorized)
RespondJSON(w, http.StatusUnauthorized, map[string]string{"error": "missing or invalid authorization header"})
return
}
@@ -31,7 +31,7 @@ func RequireAuth(next http.Handler) http.Handler {
userID, role, jti, err := auth.VerifyToken(tokenString, r.Context())
if err != nil {
http.Error(w, "invalid token", http.StatusUnauthorized)
RespondJSON(w, http.StatusUnauthorized, map[string]string{"error": "invalid token"})
return
}
@@ -73,7 +73,7 @@ func RequireRole(allowedRoles ...string) func(http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
role, ok := r.Context().Value(UserRoleKey).(string)
if !ok {
http.Error(w, "unauthorized", http.StatusUnauthorized)
RespondJSON(w, http.StatusUnauthorized, map[string]string{"error": "unauthorized"})
return
}
@@ -81,7 +81,7 @@ func RequireRole(allowedRoles ...string) func(http.Handler) http.Handler {
hasRole := slices.Contains(allowedRoles, role)
if !hasRole {
http.Error(w, "forbidden", http.StatusForbidden)
RespondJSON(w, http.StatusForbidden, map[string]string{"error": "forbidden"})
return
}
@@ -102,7 +102,7 @@ func RequireAdmin(next http.Handler) http.Handler {
return RequireRole("admin")(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
uid, ok := r.Context().Value(UserIDKey).(string)
if !ok || uid == "" {
http.Error(w, "Authentication required", http.StatusUnauthorized)
RespondJSON(w, http.StatusUnauthorized, map[string]string{"error": "Authentication required"})
return
}
next.ServeHTTP(w, r)
+1 -1
View File
@@ -134,7 +134,7 @@ func RateLimit(limit int, window time.Duration) func(http.Handler) http.Handler
}
if !limiter.Allow(ip) {
http.Error(w, "Rate limit exceeded", http.StatusTooManyRequests)
RespondJSON(w, http.StatusTooManyRequests, map[string]string{"error": "Rate limit exceeded"})
return
}