refactor(api): introduce v1 response contract

This commit is contained in:
2026-07-21 13:45:04 +08:00
parent 1d35fcf4a1
commit 7803b2faf0
13 changed files with 303 additions and 48 deletions

View File

@@ -24,12 +24,12 @@ func (h *Handler) login(c *gin.Context) {
Password string `json:"password"`
}
if err := c.ShouldBindJSON(&input); err != nil {
c.JSON(http.StatusBadRequest, gin.H{"error": "invalid request"})
abortWithError(c, http.StatusBadRequest, "invalid_request", "请求参数无效")
return
}
token, err := h.service.Login(input.Email, input.Password)
if err != nil {
c.JSON(http.StatusUnauthorized, gin.H{"error": "invalid credentials"})
abortWithError(c, http.StatusUnauthorized, "invalid_credentials", "邮箱或密码错误")
return
}
c.JSON(http.StatusOK, gin.H{"token": token})

View File

@@ -28,7 +28,7 @@ func TestLoginHandlerReturnsSessionToken(t *testing.T) {
body, err := json.Marshal(gin.H{"email": "demo@senlin.ai", "password": "password123"})
require.NoError(t, err)
req := httptest.NewRequest(http.MethodPost, "/api/auth/login", bytes.NewReader(body))
req := httptest.NewRequest(http.MethodPost, "/api/v1/auth/login", bytes.NewReader(body))
req.Header.Set("Content-Type", "application/json")
rec := httptest.NewRecorder()
@@ -53,13 +53,28 @@ func TestLoginHandlerRejectsInvalidCredentials(t *testing.T) {
body, err := json.Marshal(gin.H{"email": "demo@senlin.ai", "password": "wrong"})
require.NoError(t, err)
req := httptest.NewRequest(http.MethodPost, "/api/auth/login", bytes.NewReader(body))
req := httptest.NewRequest(http.MethodPost, "/api/v1/auth/login", bytes.NewReader(body))
req.Header.Set("Content-Type", "application/json")
rec := httptest.NewRecorder()
router.ServeHTTP(rec, req)
require.Equal(t, http.StatusUnauthorized, rec.Code)
require.JSONEq(t, `{"error":{"code":"invalid_credentials","message":"邮箱或密码错误"}}`, rec.Body.String())
}
func TestLoginHandlerRejectsInvalidJSONWithStableError(t *testing.T) {
newTestDB(t)
service := auth.NewService("test-secret")
router := httpx.NewProtectedRouter(config.Config{Env: "test"}, service.VerifySession, auth.NewHandler(service))
req := httptest.NewRequest(http.MethodPost, "/api/v1/auth/login", bytes.NewBufferString(`{"email":`))
req.Header.Set("Content-Type", "application/json")
rec := httptest.NewRecorder()
router.ServeHTTP(rec, req)
require.Equal(t, http.StatusBadRequest, rec.Code)
require.JSONEq(t, `{"error":{"code":"invalid_request","message":"请求参数无效"}}`, rec.Body.String())
}
func newTestDB(t *testing.T) *gorm.DB {

View File

@@ -11,7 +11,7 @@ const CurrentUserIDKey = "currentUserID"
func RequireUser(tokenVerifier func(string) (uint, error)) gin.HandlerFunc {
return func(c *gin.Context) {
if c.Request.Method == http.MethodPost && c.Request.URL.Path == "/api/auth/login" {
if c.Request.Method == http.MethodPost && c.Request.URL.Path == "/api/v1/auth/login" {
c.Next()
return
}
@@ -19,12 +19,12 @@ func RequireUser(tokenVerifier func(string) (uint, error)) gin.HandlerFunc {
header := c.GetHeader("Authorization")
token := strings.TrimPrefix(header, "Bearer ")
if token == "" || token == header {
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "missing bearer token"})
abortWithError(c, http.StatusUnauthorized, "missing_bearer_token", "请先登录后再操作")
return
}
userID, err := tokenVerifier(token)
if err != nil {
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "invalid bearer token"})
abortWithError(c, http.StatusUnauthorized, "invalid_bearer_token", "登录状态无效或已过期,请重新登录")
return
}
c.Set(CurrentUserIDKey, userID)
@@ -32,6 +32,13 @@ func RequireUser(tokenVerifier func(string) (uint, error)) gin.HandlerFunc {
}
}
// 认证包不能反向依赖路由包;此处保持与 httpx.Error 相同的安全错误边界。
func abortWithError(c *gin.Context, status int, code, message string) {
c.AbortWithStatusJSON(status, gin.H{
"error": gin.H{"code": code, "message": message},
})
}
func CurrentUserID(c *gin.Context) (uint, bool) {
value, ok := c.Get(CurrentUserIDKey)
if !ok {

View File

@@ -0,0 +1,40 @@
package auth_test
import (
"errors"
"net/http"
"net/http/httptest"
"testing"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/require"
"senlinai-agent/backend/internal/logic/auth"
)
func TestRequireUserReturnsStableErrorWhenBearerTokenIsMissing(t *testing.T) {
gin.SetMode(gin.TestMode)
router := gin.New()
router.Use(auth.RequireUser(func(string) (uint, error) { return 0, nil }))
router.GET("/private", func(c *gin.Context) { c.Status(http.StatusOK) })
recorder := httptest.NewRecorder()
router.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/private", nil))
require.Equal(t, http.StatusUnauthorized, recorder.Code)
require.JSONEq(t, `{"error":{"code":"missing_bearer_token","message":"请先登录后再操作"}}`, recorder.Body.String())
}
func TestRequireUserReturnsStableErrorWhenBearerTokenIsInvalid(t *testing.T) {
gin.SetMode(gin.TestMode)
router := gin.New()
router.Use(auth.RequireUser(func(string) (uint, error) { return 0, errors.New("invalid") }))
router.GET("/private", func(c *gin.Context) { c.Status(http.StatusOK) })
recorder := httptest.NewRecorder()
req := httptest.NewRequest(http.MethodGet, "/private", nil)
req.Header.Set("Authorization", "Bearer invalid")
router.ServeHTTP(recorder, req)
require.Equal(t, http.StatusUnauthorized, recorder.Code)
require.JSONEq(t, `{"error":{"code":"invalid_bearer_token","message":"登录状态无效或已过期,请重新登录"}}`, recorder.Body.String())
}