fix(auth): register CAP scope, 400 on captcha, 403 for permission

Navigating from login reused a send_email_code token on register.
Captcha failure used 401 so the client stored /register as the
post-login target and never left the page. Permission denials now
return 403, and the API client no longer wipes the session on 401.
This commit is contained in:
ryan
2026-09-02 18:26:22 +08:00
parent df7ad453cc
commit b7e5e811d1
11 changed files with 129 additions and 52 deletions
+3 -3
View File
@@ -17,19 +17,19 @@ func VerifyMiddleware(mgr *Manager, scope string) gin.HandlerFunc {
return
}
if mgr == nil {
response.AbortUnauthorized(c, errCapTokenInvalidOrExpired)
response.AbortBadRequest(c, errCapTokenInvalidOrExpired)
return
}
token := c.GetHeader("X-Cap-Token")
if token == "" {
response.AbortUnauthorized(c, errCapTokenMissing)
response.AbortBadRequest(c, errCapTokenMissing)
return
}
valid, err := mgr.VerifyToken(c.Request.Context(), token, scope)
if err != nil || !valid {
response.AbortUnauthorized(c, errCapTokenInvalidOrExpired)
response.AbortBadRequest(c, errCapTokenInvalidOrExpired)
return
}
@@ -0,0 +1,32 @@
// Copyright 2026 Arctel.net
// SPDX-License-Identifier: Apache-2.0
package cap
import (
"Wavelet/pkg/response"
"net/http"
"net/http/httptest"
"testing"
"github.com/gin-gonic/gin"
)
func TestVerifyMiddlewareMissingTokenIsBadRequest(t *testing.T) {
gin.SetMode(gin.TestMode)
restore := InstallTestRuntimeSettings(RuntimeSettings{LoginEnabled: true})
t.Cleanup(restore)
engine := gin.New()
engine.Use(response.ErrorHandlerMiddleware())
engine.POST("/register", VerifyMiddleware(GetDefaultManager(), "register"), func(c *gin.Context) {
c.Status(http.StatusOK)
})
req := httptest.NewRequest(http.MethodPost, "/register", nil)
rec := httptest.NewRecorder()
engine.ServeHTTP(rec, req)
if rec.Code != http.StatusBadRequest {
t.Errorf("VerifyMiddleware() status = %d, want %d", rec.Code, http.StatusBadRequest)
}
}