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())
}

View File

@@ -27,7 +27,7 @@ func TestCreateProjectHandlerPersistsMetadata(t *testing.T) {
"description": "RSS exploration workspace",
})
require.NoError(t, err)
req := httptest.NewRequest(http.MethodPost, "/api/projects", bytes.NewReader(body))
req := httptest.NewRequest(http.MethodPost, "/api/v1/projects", bytes.NewReader(body))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer test-token")
rec := httptest.NewRecorder()
@@ -47,7 +47,7 @@ func TestCreateTaskHandlerPersistsTask(t *testing.T) {
router, project, _ := newProjectsHandlerTestRouter(t)
body, err := json.Marshal(gin.H{"title": "整理需求", "description": "形成任务清单", "dueAt": "2026-07-21T09:30:00Z", "tag": "需求"})
require.NoError(t, err)
req := httptest.NewRequest(http.MethodPost, "/api/projects/1/tasks", bytes.NewReader(body))
req := httptest.NewRequest(http.MethodPost, "/api/v1/projects/1/tasks", bytes.NewReader(body))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer test-token")
rec := httptest.NewRecorder()
@@ -72,7 +72,7 @@ func TestUploadSourceHandlerStoresFileAndSource(t *testing.T) {
_, err = fileWriter.Write([]byte("hello"))
require.NoError(t, err)
require.NoError(t, writer.Close())
req := httptest.NewRequest(http.MethodPost, "/api/projects/1/sources", body)
req := httptest.NewRequest(http.MethodPost, "/api/v1/projects/1/sources", body)
req.Header.Set("Content-Type", writer.FormDataContentType())
req.Header.Set("Authorization", "Bearer test-token")
rec := httptest.NewRecorder()
@@ -91,7 +91,7 @@ func TestCreateCronPlanHandlerPersistsPlan(t *testing.T) {
router, project, _ := newProjectsHandlerTestRouter(t)
body, err := json.Marshal(gin.H{"title": "每日整理", "schedule": "0 9 * * *", "enabled": true, "nextRunAt": "2026-07-22T08:00:00Z"})
require.NoError(t, err)
req := httptest.NewRequest(http.MethodPost, "/api/projects/1/cron-plans", bytes.NewReader(body))
req := httptest.NewRequest(http.MethodPost, "/api/v1/projects/1/cron-plans", bytes.NewReader(body))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer test-token")
rec := httptest.NewRecorder()
@@ -110,7 +110,7 @@ func TestCreateTagHandlerPersistsProjectTag(t *testing.T) {
router, project, _ := newProjectsHandlerTestRouter(t)
body, err := json.Marshal(gin.H{"name": "Design"})
require.NoError(t, err)
req := httptest.NewRequest(http.MethodPost, "/api/projects/1/tags", bytes.NewReader(body))
req := httptest.NewRequest(http.MethodPost, "/api/v1/projects/1/tags", bytes.NewReader(body))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer test-token")
rec := httptest.NewRecorder()
@@ -126,7 +126,7 @@ func TestCreateTagHandlerPersistsProjectTag(t *testing.T) {
func TestListTagsHandlerReturnsProjectTags(t *testing.T) {
router, project, _ := newProjectsHandlerTestRouter(t)
require.NoError(t, models.DBService.Create(&models.SenlinAgentTag{ProjectID: project.ID, Name: "Design"}).Error)
req := httptest.NewRequest(http.MethodGet, "/api/projects/1/tags", nil)
req := httptest.NewRequest(http.MethodGet, "/api/v1/projects/1/tags", nil)
req.Header.Set("Authorization", "Bearer test-token")
rec := httptest.NewRecorder()
@@ -145,7 +145,7 @@ func TestUpdateTaskHandlerPersistsTagAndStatus(t *testing.T) {
require.NoError(t, models.DBService.Create(&task).Error)
body, err := json.Marshal(gin.H{"title": "Draft v2", "description": "Updated", "completed": true, "tag": "Important"})
require.NoError(t, err)
req := httptest.NewRequest(http.MethodPatch, "/api/projects/1/tasks/1", bytes.NewReader(body))
req := httptest.NewRequest(http.MethodPatch, "/api/v1/projects/1/tasks/1", bytes.NewReader(body))
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer test-token")
rec := httptest.NewRecorder()