fix: auth and ratelimit middleware return JSON errors instead of text/plain
This commit is contained in:
+5
-5
@@ -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)
|
||||
|
||||
Reference in New Issue
Block a user