API契约:迁移二维码与密码登录错误

This commit is contained in:
Christ committed 2026-08-14 14:28:04 +08:00
1 parent 82da4d8bb5
commit 1a14f18b07
6 files changed
+149 -30

No files matched your search

+6 -5
View File
@@ -14,10 +14,11 @@ func (s *Server) mountPasswordLogin(r chi.Router) {
r.Delete("/password-login/cancel/{session_id}", s.passwordLoginDisabled)
}
// passwordLoginDisabled 返回密码登录已禁用的统一错误响应,保留旧路径兼容性。
func (s *Server) passwordLoginDisabled(w http.ResponseWriter, _ *http.Request) {
writeJSON(w, http.StatusOK, map[string]any{
"success": false,
"status": "disabled",
"message": "Go 客户端仅支持扫码登录,密码登录已禁用",
})
writeErrCode(
w,
http.StatusNotImplemented,
"password_login_disabled",
"Go 客户端仅支持扫码登录,密码登录已禁用", "")
}
@@ -23,14 +23,14 @@ func TestPasswordLoginAPIsArePermanentlyDisabled(t *testing.T) {
req.AddCookie(authCookie)
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
if rec.Code != http.StatusNotImplemented {
t.Fatalf("%s %s status=%d body=%s", req.Method, req.URL.Path, rec.Code, rec.Body.String())
}
var result map[string]any
if err := json.Unmarshal(rec.Body.Bytes(), &result); err != nil {
t.Fatal(err)
}
if result["success"] != false || result["status"] != "disabled" {
if result["code"] != "password_login_disabled" || result["message"] == "" {
t.Fatalf("%s %s 应永久禁用: %+v", req.Method, req.URL.Path, result)
}
}
+116
View File
@@ -0,0 +1,116 @@
package server
import (
"encoding/json"
"errors"
"net/http"
"net/http/httptest"
"testing"
"xianyu-go/internal/httpapi"
)
// TestAPIContractQRLoginGenerationFailure 验证二维码生成上游失败返回非 2xx 统一错误 DTO。
func TestAPIContractQRLoginGenerationFailure(t *testing.T) {
// srv 是用于验证二维码生成错误契约的 HTTP 测试服务。
srv, _, cleanup := newTestServer(t)
defer cleanup()
srv.QRLogin = &fakeQRLoginService{generateErr: errors.New("二维码服务不可用")}
// handler 是当前测试使用的完整路由树。
handler := srv.Router()
// sessionCookie 是管理员登录后得到的认证会话。
sessionCookie := loginHelper(t, handler)
// req 是触发二维码上游失败的生成请求。
req := httptest.NewRequest(http.MethodPost, "/qr-login/generate", nil)
req.AddCookie(sessionCookie)
// recorder 是捕获二维码错误响应的测试记录器。
recorder := httptest.NewRecorder()
handler.ServeHTTP(recorder, req)
if recorder.Code != http.StatusBadGateway {
t.Fatalf("status=%d body=%s", recorder.Code, recorder.Body.String())
}
// response 是二维码生成失败的统一错误 DTO。
var response httpapi.ErrorResponse
// decodeErr 表示二维码错误响应 JSON 反序列化失败的原因。
if decodeErr := json.Unmarshal(recorder.Body.Bytes(), &response); decodeErr != nil {
t.Fatalf("decode response: %v", decodeErr)
}
if response.Code != "qr_login_generate_failed" || response.Message == "" {
t.Fatalf("response=%+v", response)
}
}
// TestAPIContractQRLoginPersistFailure 验证扫码成功但本地持久化失败返回统一内部错误。
func TestAPIContractQRLoginPersistFailure(t *testing.T) {
// srv 是用于验证扫码持久化错误契约的 HTTP 测试服务。
srv, store, cleanup := newTestServer(t)
defer cleanup()
srv.Manager = nil
srv.QRLogin = &fakeQRLoginService{status: map[string]any{"status": "success"}}
ownQRSession(t, srv, store, "persist-failure")
// handler 是当前测试使用的完整路由树。
handler := srv.Router()
// sessionCookie 是管理员登录后得到的认证会话。
sessionCookie := loginHelper(t, handler)
// req 是触发扫码结果缺少凭证的状态查询请求。
req := httptest.NewRequest(http.MethodGet, "/qr-login/status/persist-failure", nil)
req.AddCookie(sessionCookie)
// recorder 是捕获扫码持久化错误响应的测试记录器。
recorder := httptest.NewRecorder()
handler.ServeHTTP(recorder, req)
if recorder.Code != http.StatusInternalServerError {
t.Fatalf("status=%d body=%s", recorder.Code, recorder.Body.String())
}
// response 是扫码持久化失败的统一错误 DTO。
var response httpapi.ErrorResponse
// decodeErr 表示扫码持久化错误响应 JSON 反序列化失败的原因。
if decodeErr := json.Unmarshal(recorder.Body.Bytes(), &response); decodeErr != nil {
t.Fatalf("decode response: %v", decodeErr)
}
if response.Code != "qr_login_persist_failed" || response.Message == "" {
t.Fatalf("response=%+v", response)
}
}
// TestAPIContractQRVerificationFailure 验证风控验证上游失败返回统一网关错误。
func TestAPIContractQRVerificationFailure(t *testing.T) {
// srv 是用于验证扫码风控错误契约的 HTTP 测试服务。
srv, store, cleanup := newTestServer(t)
defer cleanup()
srv.QRLogin = &fakeQRLoginService{completeErr: errors.New("验证服务不可用")}
ownQRSession(t, srv, store, "verification-failure")
// handler 是当前测试使用的完整路由树。
handler := srv.Router()
// sessionCookie 是管理员登录后得到的认证会话。
sessionCookie := loginHelper(t, handler)
// req 是触发风控验证上游失败的请求。
req := httptest.NewRequest(http.MethodPost, "/qr-login/complete-verification/verification-failure", nil)
req.AddCookie(sessionCookie)
// recorder 是捕获风控验证错误响应的测试记录器。
recorder := httptest.NewRecorder()
handler.ServeHTTP(recorder, req)
if recorder.Code != http.StatusBadGateway {
t.Fatalf("status=%d body=%s", recorder.Code, recorder.Body.String())
}
// response 是风控验证失败的统一错误 DTO。
var response httpapi.ErrorResponse
// decodeErr 表示风控验证错误响应 JSON 反序列化失败的原因。
if decodeErr := json.Unmarshal(recorder.Body.Bytes(), &response); decodeErr != nil {
t.Fatalf("decode response: %v", decodeErr)
}
if response.Code != "qr_verification_failed" || response.Message == "" {
t.Fatalf("response=%+v", response)
}
}
// TestAPIContractPasswordLoginDisabled 验证历史密码登录兼容入口使用明确的未实现错误。
func TestAPIContractPasswordLoginDisabled(t *testing.T) {
// srv 是用于验证密码登录禁用契约的 HTTP 测试服务。
srv, _, cleanup := newTestServer(t)
defer cleanup()
// handler 是当前测试使用的完整路由树。
handler := srv.Router()
// sessionCookie 是管理员登录后得到的认证会话。
sessionCookie := loginHelper(t, handler)
assertUnifiedAPIError(t, handler, http.MethodPost, "/password-login", `{}`, sessionCookie, http.StatusNotImplemented, "password_login_disabled", "Go 客户端仅支持扫码登录,密码登录已禁用", false)
}
+20 -20
View File
@@ -51,10 +51,10 @@ func (s *Server) generateQRLogin(w http.ResponseWriter, r *http.Request) {
default:
s.Logger.Error("生成二维码失败", "err", err)
}
writeJSON(w, http.StatusOK, map[string]any{
"success": false,
"message": message,
})
writeErrCode(
w,
http.StatusBadGateway, "qr_login_generate_failed",
message, "")
return
}
s.qrMu.Lock()
@@ -106,10 +106,10 @@ func (s *Server) checkQRLoginStatusAndPersist(w http.ResponseWriter, r *http.Req
if s.Logger != nil {
s.Logger.Warn("保存扫码登录结果失败", "session_id", sessionID, "err", err)
}
result["success"] = false
result["status"] = "error"
result["message"] = "保存扫码登录结果失败: " + err.Error()
writeJSON(w, http.StatusOK, publicQRStatus(result))
writeErrCode(
w,
http.StatusInternalServerError, "qr_login_persist_failed",
"保存扫码登录结果失败: "+err.Error(), "")
return
}
result["success"] = true
@@ -131,10 +131,10 @@ func (s *Server) completeQRVerification(w http.ResponseWriter, r *http.Request)
cookies, unb, err := s.QRLogin.CompleteVerification(r.Context(), sessionID)
if err != nil {
s.Logger.Error("验证完成处理失败", "err", err)
writeJSON(w, http.StatusOK, map[string]any{
"success": false,
"message": err.Error(),
})
writeErrCode(
w,
http.StatusBadGateway, "qr_verification_failed",
err.Error(), "")
return
}
var req struct {
@@ -148,11 +148,11 @@ func (s *Server) completeQRVerification(w http.ResponseWriter, r *http.Request)
}
req.TargetAccountID = strings.TrimSpace(req.TargetAccountID)
if req.TargetAccountID != "" && req.TargetAccountID != unb {
writeJSON(w, http.StatusOK, map[string]any{
"success": false,
"scanned_account_id": unb,
"message": "扫码账号与待重新授权账号不一致,已拒绝覆盖;请使用正确账号重新扫码",
})
writeErrDetails(
w, http.StatusConflict,
"qr_account_mismatch",
"扫码账号与待重新授权账号不一致,已拒绝覆盖;请使用正确账号重新扫码",
"", map[string]any{"scanned_account_id": unb})
return
}
resp := map[string]any{
@@ -176,9 +176,9 @@ func (s *Server) completeQRVerification(w http.ResponseWriter, r *http.Request)
if s.Logger != nil {
s.Logger.Warn("保存扫码验证结果失败", "session_id", sessionID, "err", persistErr)
}
resp["success"] = false
resp["message"] = "保存扫码登录结果失败: " + persistErr.Error()
writeJSON(w, http.StatusOK, resp)
writeErrCode(
w, http.StatusInternalServerError, "qr_login_persist_failed",
"保存扫码登录结果失败: "+persistErr.Error(), "")
return
}
resp["account_id"] = persisted.AccountID
+2 -2
View File
@@ -329,7 +329,7 @@ func TestCompleteQRVerificationRejectsDifferentTarget(t *testing.T) {
req.AddCookie(cookie)
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
if rec.Code != http.StatusConflict {
t.Fatalf("status=%d body=%s", rec.Code, rec.Body.String())
}
var result map[string]any
@@ -340,7 +340,7 @@ func TestCompleteQRVerificationRejectsDifferentTarget(t *testing.T) {
}
result := request()
if result["success"] != false || result["scanned_account_id"] != "scanned-other" {
if result["code"] != "qr_account_mismatch" || result["details"].(map[string]any)["scanned_account_id"] != "scanned-other" {
t.Fatalf("response=%+v", result)
}
original, _ := store.Cookies.GetValue(context.Background(), "acc1")