API契约:迁移剩余认证与公共错误
This commit is contained in:
1 parent
4e7abf61be
commit
1efe44e921
5 files changed
+89
-10
No files matched your search
@@ -1,9 +1,12 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
|
||||
"github.com/go-chi/chi/v5/middleware"
|
||||
|
||||
"xianyu-go/internal/db"
|
||||
"xianyu-go/internal/httpapi"
|
||||
)
|
||||
|
||||
@@ -87,3 +90,12 @@ func writeErrCode(w http.ResponseWriter, status int, code, msg, requestID string
|
||||
}
|
||||
httpapi.WriteError(w, status, code, msg, requestID)
|
||||
}
|
||||
|
||||
// writeCredentialVerificationError 将当前密码校验失败区分为认证失败或内部故障。
|
||||
func writeCredentialVerificationError(w http.ResponseWriter, err error) {
|
||||
if errors.Is(err, db.ErrPasswordMismatch) {
|
||||
writeErrCode(w, http.StatusUnauthorized, "authentication_failed", "当前密码错误", "")
|
||||
return
|
||||
}
|
||||
writeErr(w, http.StatusInternalServerError, "验证当前密码失败")
|
||||
}
|
||||
@@ -1,6 +1,7 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
@@ -116,3 +117,67 @@ func TestAPIContractAccountList(t *testing.T) {
|
||||
t.Fatalf("account list exposes credential field: %s", rec.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
// assertUnifiedAPIError 验证指定请求返回统一错误 DTO 和预期 HTTP 状态。
|
||||
func assertUnifiedAPIError(t *testing.T, handler http.Handler, method, path, body string, sessionCookie *http.Cookie, status int, code, message string, requireRequestID bool) {
|
||||
t.Helper()
|
||||
// req 是待验证统一错误契约的 HTTP 请求。
|
||||
req := httptest.NewRequest(method, path, strings.NewReader(body))
|
||||
if sessionCookie != nil {
|
||||
req.AddCookie(sessionCookie)
|
||||
}
|
||||
// rec 是捕获错误响应的测试记录器。
|
||||
rec := httptest.NewRecorder()
|
||||
handler.ServeHTTP(rec, req)
|
||||
if rec.Code != status {
|
||||
t.Fatalf("%s %s status=%d body=%s", method, path, rec.Code, rec.Body.String())
|
||||
}
|
||||
// response 是统一错误响应 DTO。
|
||||
var response httpapi.ErrorResponse
|
||||
// decodeErr 表示错误响应 JSON 反序列化失败的原因。
|
||||
if decodeErr := json.Unmarshal(rec.Body.Bytes(), &response); decodeErr != nil {
|
||||
t.Fatalf("%s %s decode error: %v", method, path, decodeErr)
|
||||
}
|
||||
if response.Code != code || response.Message != message {
|
||||
t.Fatalf("%s %s response=%+v", method, path, response)
|
||||
}
|
||||
if requireRequestID && response.RequestID == "" {
|
||||
t.Fatalf("%s %s 缺少 request_id: %+v", method, path, response)
|
||||
}
|
||||
}
|
||||
|
||||
// TestAPIContractRemainingAuthenticationErrors 验证初始化和密码凭据错误统一使用非 2xx 响应。
|
||||
func TestAPIContractRemainingAuthenticationErrors(t *testing.T) {
|
||||
// srv 是用于验证剩余认证错误边界的 HTTP 测试服务。
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
// handler 是当前测试使用的完整路由树。
|
||||
handler := srv.Router()
|
||||
// sessionCookie 是管理员登录后得到的认证会话。
|
||||
sessionCookie := loginHelper(t, handler)
|
||||
// created 表示用于验证用户名冲突的占位用户是否成功创建。
|
||||
created, createErr := srv.Store.Users.Create(context.Background(), "taken-user", "[email protected]", "pw")
|
||||
if createErr != nil || !created {
|
||||
t.Fatalf("create conflict user: created=%v err=%v", created, createErr)
|
||||
}
|
||||
assertUnifiedAPIError(t, handler, http.MethodPost, "/initialize", `{"password":"another-password"}`, nil, http.StatusConflict, httpapi.CodeConflict, "系统已经初始化,请直接登录", false)
|
||||
assertUnifiedAPIError(t, handler, http.MethodPost, "/change-admin-password", `{"current_password":"wrong","new_password":"newpw123"}`, sessionCookie, http.StatusUnauthorized, "authentication_failed", "当前密码错误", false)
|
||||
assertUnifiedAPIError(t, handler, http.MethodPost, "/change-password", `{"current_password":"wrong","new_password":"newpw123"}`, sessionCookie, http.StatusUnauthorized, "authentication_failed", "当前密码错误", false)
|
||||
assertUnifiedAPIError(t, handler, http.MethodPut, "/account/credentials", `{"current_password":"wrong","new_username":"admin-renamed"}`, sessionCookie, http.StatusUnauthorized, "authentication_failed", "当前密码错误", false)
|
||||
assertUnifiedAPIError(t, handler, http.MethodPut, "/account/credentials", `{"current_password":"pw","new_username":"taken-user"}`, sessionCookie, http.StatusConflict, "username_taken", "用户名已被占用", false)
|
||||
}
|
||||
|
||||
// TestAPIContractPublicAndSPAErrors 验证公开设置故障和 SPA API 404 均返回统一错误 DTO。
|
||||
func TestAPIContractPublicAndSPAErrors(t *testing.T) {
|
||||
// srv 和 store 是用于模拟公开 API 数据库故障的测试服务及其存储。
|
||||
srv, store, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
// handler 是当前测试使用的完整路由树。
|
||||
handler := srv.Router()
|
||||
// closeErr 表示主动关闭测试数据库连接的结果。
|
||||
if closeErr := store.DB.Close(); closeErr != nil {
|
||||
t.Fatalf("close test database: %v", closeErr)
|
||||
}
|
||||
assertUnifiedAPIError(t, handler, http.MethodGet, "/system-settings/public", "", nil, http.StatusInternalServerError, httpapi.CodeInternalError, "查询失败", false)
|
||||
assertUnifiedAPIError(t, handler, http.MethodGet, "/api/not-found", "", nil, http.StatusNotFound, httpapi.CodeNotFound, "接口不存在", true)
|
||||
}
|
||||
@@ -195,11 +195,11 @@ func (s *Server) changeAdminPassword(w http.ResponseWriter, r *http.Request) {
|
||||
// 校验当前密码。
|
||||
user, ok, _ := s.Store.Users.VerifyAndUpgrade(ctx, sess.Username, req.CurrentPassword)
|
||||
if !ok || user == nil {
|
||||
writeJSON(w, http.StatusOK, map[string]any{"success": false, "message": "当前密码错误"})
|
||||
writeErrCode(w, http.StatusUnauthorized, "authentication_failed", "当前密码错误", "")
|
||||
return
|
||||
}
|
||||
if _, err := s.Store.Users.UpdatePassword(ctx, sess.Username, req.NewPassword); err != nil {
|
||||
writeJSON(w, http.StatusOK, map[string]any{"success": false, "message": "更新失败"})
|
||||
writeErr(w, http.StatusInternalServerError, "更新失败")
|
||||
return
|
||||
}
|
||||
s.Auth.ClearSessionCookie(w)
|
||||
@@ -228,11 +228,11 @@ func (s *Server) changePassword(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
user, _, _ := s.Store.Users.VerifyAndUpgrade(ctx, sess.Username, req.CurrentPassword)
|
||||
if user == nil {
|
||||
writeJSON(w, http.StatusOK, map[string]any{"success": false, "message": "当前密码错误"})
|
||||
writeErrCode(w, http.StatusUnauthorized, "authentication_failed", "当前密码错误", "")
|
||||
return
|
||||
}
|
||||
if _, err := s.Store.Users.UpdatePassword(ctx, sess.Username, req.NewPassword); err != nil {
|
||||
writeJSON(w, http.StatusOK, map[string]any{"success": false, "message": "更新失败"})
|
||||
writeErr(w, http.StatusInternalServerError, "更新失败")
|
||||
return
|
||||
}
|
||||
s.Auth.ClearSessionCookie(w)
|
||||
@@ -275,16 +275,16 @@ func (s *Server) updateCredentials(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
user, ok, err := s.Store.Users.VerifyAndUpgrade(r.Context(), sess.Username, req.CurrentPassword)
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "验证当前密码失败")
|
||||
writeCredentialVerificationError(w, err)
|
||||
return
|
||||
}
|
||||
if !ok || user == nil || user.ID != sess.UserID {
|
||||
writeJSON(w, http.StatusOK, map[string]any{"success": false, "message": "当前密码错误"})
|
||||
writeErrCode(w, http.StatusUnauthorized, "authentication_failed", "当前密码错误", "")
|
||||
return
|
||||
}
|
||||
if err := s.Store.Users.UpdateCredentials(r.Context(), sess.UserID, username, req.NewPassword); err != nil {
|
||||
if errors.Is(err, db.ErrUsernameTaken) {
|
||||
writeJSON(w, http.StatusConflict, map[string]any{"success": false, "message": "用户名已被占用"})
|
||||
writeErrCode(w, http.StatusConflict, "username_taken", "用户名已被占用", "")
|
||||
return
|
||||
}
|
||||
writeErr(w, http.StatusInternalServerError, "更新登录凭据失败")
|
||||
|
||||
@@ -70,7 +70,7 @@ func (s *Server) setSettings(w http.ResponseWriter, r *http.Request) {
|
||||
func (s *Server) publicSettings(w http.ResponseWriter, r *http.Request) {
|
||||
m, err := s.Store.Settings.Public(r.Context())
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusInternalServerError, "查询失败")
|
||||
writeErrRequest(w, r, http.StatusInternalServerError, "查询失败")
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, m)
|
||||
|
||||
Reference in new issue
Block a user