账号登录应用服务:提取登录与凭证用例边界
This commit is contained in:
1 parent
de723ee306
commit
df914fc0f7
6 files changed
+540
-592
No files matched your search
+192
-432
File diff suppressed because it is too large.
Load diff
@@ -156,7 +156,8 @@ app shell / routes
|
||||
- 已完成阶段 4 第一个 PR 切片“订单应用服务边界提取”:订单列表、详情、更新、删除、批量导入、手动发货和批量刷新已由不依赖 `net/http` 的 `orderApplicationService` 编排;handler 仅保留 HTTP 解析、鉴权上下文和 DTO 编码;保留订单所有权、事务回滚、MTOP 凭证锁、Cookie Jar 持久化、Session 续期和逐单部分失败语义;新增服务层直接调用测试并通过 Go 全量门禁与 server race;
|
||||
- 已完成阶段 4 第二个 PR 切片“订单响应 DTO 映射收口”:订单列表状态/图片映射、详情商品补全、单订单刷新和批量刷新响应均由应用服务返回稳定视图;更新校验改用业务错误分类,HTTP 层不再依赖错误文本判断状态码;旧/版本化入口契约测试和全量门禁通过;
|
||||
- 已完成阶段 4 第三个 PR 切片“商品发布应用服务边界提取”:新增不依赖 `net/http` 的商品发布应用服务,覆盖单商品发布、类目推荐、批量预检持久化、批次启动/查询/取消/删除/失败重试;HTTP 层仅保留请求解析、鉴权和契约映射,保留 worker、锁、cancel map、租约和远端发布顺序;新增服务层直接调用测试并通过全量门禁,合并为一个可回滚提交;
|
||||
- 阶段 4 下一 PR 切片为“账号登录应用服务边界提取”:围绕二维码会话所有权、结果持久化、资料刷新、Cookie 合并、账号重启和登录审计提取不依赖 `net/http` 的应用服务,保持持久化锁和生命周期不变量,不拆分单个 handler 提交;
|
||||
- 已完成阶段 4 第四个 PR 切片“账号登录应用服务边界提取”:新增不依赖 `net/http` 的账号登录应用服务,覆盖扫码结果幂等持久化、Cookie Jar/扁平 Cookie 合并、账号新增与更新、资料刷新、登录审计和运行时重启;HTTP handler 仅保留请求解析、所有权校验和契约映射,保留扫码会话锁与账号凭证锁不变量;新增服务层测试并通过全量门禁,合并为一个可回滚提交;
|
||||
- 阶段 4 下一 PR 切片为“聊天与通知应用服务边界提取”:围绕聊天消息发送、账号任务事件、通知渠道绑定、消息读取和发送失败重试提取不依赖 `net/http` 的应用服务,保持 WebSocket、通知 outbox 和事件幂等不变量,不拆分单个 handler 提交;
|
||||
- 禁止跳过当前入口直接开始 Engine、Automation 或 DB 的大规模拆分。
|
||||
|
||||
## 6. 阶段 0:治理文档与强约束
|
||||
@@ -562,3 +563,4 @@ npm --prefix frontend run build
|
||||
| 2026-08-14 | 完成阶段 4 第一个 PR 切片“订单应用服务边界提取” | 新增不依赖 `net/http` 的订单应用服务,覆盖列表、详情、更新、删除、导入、手动发货、批量刷新和单订单刷新;保留权限、事务、凭证锁、Cookie Jar 和 Session 续期语义;服务层测试、全量测试、race、vet、lint、注释门禁通过并合并为一个可回滚提交 | 阶段 4:订单响应 DTO 映射收口 |
|
||||
| 2026-08-14 | 完成阶段 4 第二个 PR 切片“订单响应 DTO 映射收口” | 列表/详情/刷新响应视图由应用服务统一生成;错误分类模型替代 HTTP handler 中的错误文本判断;旧/版本化订单契约、全量测试、race、vet、lint、注释和 diff 门禁通过,合并为一个可回滚提交 | 阶段 4:商品发布应用服务边界提取 |
|
||||
| 2026-08-14 | 完成阶段 4 第三个 PR 切片“商品发布应用服务边界提取” | 新增不依赖 `net/http` 的商品发布应用服务,覆盖单商品发布、类目推荐、批量预检持久化、批次启动/查询/取消/删除/失败重试;保留 worker、凭证锁、cancel map、租约、远端发布与自动化规则时序;新增服务层测试,Go 全量测试、vet、lint、注释和 diff 门禁通过并合并为一个可回滚提交 | 阶段 4:账号登录应用服务边界提取 |
|
||||
| 2026-08-14 | 完成阶段 4 第四个 PR 切片“账号登录应用服务边界提取” | 新增不依赖 `net/http` 的账号登录应用服务,覆盖扫码结果幂等持久化、Cookie Jar/扁平 Cookie 合并、账号新增与更新、资料刷新、登录审计和运行时重启;保留扫码会话锁、账号凭证锁和旧/版本化 HTTP 契约;新增服务层测试,Go 全量测试、race、vet、lint、注释和 diff 门禁通过并合并为一个可回滚提交 | 阶段 4:聊天与通知应用服务边界提取 |
|
||||
@@ -0,0 +1,291 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"xianyu-go/internal/db"
|
||||
"xianyu-go/internal/xianyu/cookierefresh"
|
||||
"xianyu-go/internal/xianyu/protocol"
|
||||
)
|
||||
|
||||
// accountLoginService 是账号登录相关应用服务,负责凭证写入、登录审计、资料刷新和运行时重启编排。
|
||||
type accountLoginService struct {
|
||||
// server 提供账号存储、运行时管理器和扫码会话持久化依赖。
|
||||
server *Server
|
||||
}
|
||||
|
||||
// accountLoginInput 是新增账号登录凭证用例的业务输入。
|
||||
type accountLoginInput struct {
|
||||
// AccountID 是待创建的账号标识。
|
||||
AccountID string
|
||||
// Cookies 是平台登录 Cookie 字符串。
|
||||
Cookies string
|
||||
// UserID 是当前用户标识。
|
||||
UserID int64
|
||||
// LoginMethod 是账号登录方式。
|
||||
LoginMethod string
|
||||
}
|
||||
|
||||
// accountCookieUpdateInput 是更新账号登录凭证用例的业务输入。
|
||||
type accountCookieUpdateInput struct {
|
||||
// AccountID 是待更新的账号标识。
|
||||
AccountID string
|
||||
// Cookies 是新的平台登录 Cookie 字符串。
|
||||
Cookies string
|
||||
// UserID 是当前用户标识。
|
||||
UserID int64
|
||||
// LoginMethod 是可选的登录方式。
|
||||
LoginMethod string
|
||||
}
|
||||
|
||||
// accountProfileResult 是账号资料刷新后的展示结果。
|
||||
type accountProfileResult struct {
|
||||
// Nickname 是平台昵称或本地兜底昵称。
|
||||
Nickname string
|
||||
// AvatarURL 是平台头像地址或本地兜底地址。
|
||||
AvatarURL string
|
||||
// ErrorMessage 是资料刷新失败时的可展示错误。
|
||||
ErrorMessage string
|
||||
}
|
||||
|
||||
// accountLoginApplication 返回当前 Server 绑定的账号登录应用服务。
|
||||
func (s *Server) accountLoginApplication() *accountLoginService {
|
||||
return &accountLoginService{server: s}
|
||||
}
|
||||
|
||||
// CreateCookie 创建账号凭证并完成登录审计、资料刷新和运行时重启。
|
||||
func (svc *accountLoginService) CreateCookie(ctx context.Context, input accountLoginInput) error {
|
||||
// s 是当前账号登录应用服务依赖的 Server。
|
||||
s := svc.server
|
||||
// unlock 保护账号凭证的创建与后续登录状态清理。
|
||||
unlock := s.Store.LockAccountCredentials(input.AccountID)
|
||||
// err 表示账号凭证创建错误。
|
||||
if err := s.Store.Cookies.CreateOwned(ctx, input.AccountID, input.Cookies, input.UserID); err != nil {
|
||||
unlock()
|
||||
return err
|
||||
}
|
||||
if s.Store.Tokens != nil {
|
||||
// err 表示清理旧连接凭证的错误,仅记录不阻断登录。
|
||||
if err := s.Store.Tokens.Clear(ctx, input.AccountID); err != nil && s.Logger != nil {
|
||||
s.Logger.Warn("新增账号后清理旧连接凭证失败", "cookie_id", input.AccountID, "err", err)
|
||||
}
|
||||
}
|
||||
// loginMethod 是归一化后的登录方式。
|
||||
loginMethod := normalizeLoginMethod(input.LoginMethod)
|
||||
if loginMethod == "" {
|
||||
loginMethod = loginMethodManual
|
||||
}
|
||||
s.markSuccessfulLogin(ctx, input.AccountID, input.UserID, loginMethod, "账号登录成功")
|
||||
unlock()
|
||||
svc.refreshAndRestartAccount(ctx, input.UserID, input.AccountID)
|
||||
return nil
|
||||
}
|
||||
|
||||
// UpdateCookie 更新账号凭证并完成登录审计、资料刷新和运行时重启。
|
||||
func (svc *accountLoginService) UpdateCookie(ctx context.Context, input accountCookieUpdateInput) error {
|
||||
// s 是当前账号登录应用服务依赖的 Server。
|
||||
s := svc.server
|
||||
// unlock 保护账号凭证更新、连接凭证清理和登录审计。
|
||||
unlock := s.Store.LockAccountCredentials(input.AccountID)
|
||||
// detail 和 err 保存账号凭证详情查询结果。
|
||||
detail, err := s.loadCookiePlatformDetail(ctx, input.AccountID)
|
||||
if err != nil || detail == nil || detail.UserID != input.UserID {
|
||||
unlock()
|
||||
if err == nil {
|
||||
return db.ErrNotFound
|
||||
}
|
||||
return err
|
||||
}
|
||||
// err 表示扁平 Cookie 更新错误。
|
||||
if err := s.updateFlatCookieOwnedLocked(ctx, detail, input.Cookies); err != nil {
|
||||
unlock()
|
||||
return err
|
||||
}
|
||||
if s.Store.Tokens != nil {
|
||||
// err 表示清理旧连接凭证的错误,仅记录不阻断登录。
|
||||
if err := s.Store.Tokens.Clear(ctx, input.AccountID); err != nil && s.Logger != nil {
|
||||
s.Logger.Warn("更新账号后清理旧连接凭证失败", "cookie_id", input.AccountID, "err", err)
|
||||
}
|
||||
}
|
||||
// loginMethod 是可选的归一化登录方式。
|
||||
if loginMethod := normalizeLoginMethod(input.LoginMethod); loginMethod != "" {
|
||||
s.markSuccessfulLogin(ctx, input.AccountID, input.UserID, loginMethod, "账号登录成功")
|
||||
}
|
||||
unlock()
|
||||
svc.refreshAndRestartAccount(ctx, input.UserID, input.AccountID)
|
||||
return nil
|
||||
}
|
||||
|
||||
// RefreshProfile 按用户归属读取账号摘要并刷新平台资料。
|
||||
func (svc *accountLoginService) RefreshProfile(ctx context.Context, userID int64, accountID string) (accountProfileResult, error) {
|
||||
// detail 和 err 保存资料刷新所需的非敏感账号摘要。
|
||||
detail, err := svc.server.loadCookieSummaryDetail(ctx, userID, accountID)
|
||||
if err != nil {
|
||||
return accountProfileResult{}, err
|
||||
}
|
||||
// nickname、avatarURL 和 profileErr 保存平台资料刷新结果。
|
||||
nickname, avatarURL, profileErr := svc.server.refreshAccountProfile(ctx, detail)
|
||||
return accountProfileResult{Nickname: nickname, AvatarURL: avatarURL, ErrorMessage: profileErr}, nil
|
||||
}
|
||||
|
||||
// PersistQRLoginSuccess 持久化扫码登录结果,复用会话级幂等锁和账号重启流程。
|
||||
func (svc *accountLoginService) PersistQRLoginSuccess(ctx context.Context, userID int64, sessionID string, result map[string]any, targetAccountID string) (qrLoginPersistence, error) {
|
||||
return svc.persistQRLoginSuccessCore(ctx, userID, sessionID, result, targetAccountID)
|
||||
}
|
||||
|
||||
// persistQRLoginSuccessCore 执行扫码结果校验、凭证合并、登录审计和账号重启。
|
||||
func (svc *accountLoginService) persistQRLoginSuccessCore(ctx context.Context, userID int64, sessionID string, result map[string]any, targetAccountID string) (qrLoginPersistence, error) {
|
||||
// s 是当前账号登录应用服务依赖的 Server。
|
||||
s := svc.server
|
||||
// lockValue 和 persistMu 保证同一扫码会话只执行一次持久化。
|
||||
lockValue, _ := s.qrPersistLocks.LoadOrStore(sessionID, &sync.Mutex{})
|
||||
// persistMu 是当前扫码会话的串行化锁。
|
||||
persistMu := lockValue.(*sync.Mutex)
|
||||
persistMu.Lock()
|
||||
defer persistMu.Unlock()
|
||||
|
||||
s.qrMu.Lock()
|
||||
if s.qrPersisted == nil {
|
||||
s.qrPersisted = make(map[string]qrLoginPersistence)
|
||||
}
|
||||
// persisted 和 ok 保存已完成的幂等结果及其存在性。
|
||||
if persisted, ok := s.qrPersisted[sessionID]; ok {
|
||||
s.qrMu.Unlock()
|
||||
if persisted.UserID != userID {
|
||||
return qrLoginPersistence{}, errors.New("扫码会话不属于当前用户")
|
||||
}
|
||||
return persisted, nil
|
||||
}
|
||||
s.qrMu.Unlock()
|
||||
// cookies、cookieSnapshot 和 snapshotComplete 保存平台登录凭证及其完整 Cookie Jar。
|
||||
cookies := qrString(result, "cookies")
|
||||
// cookieSnapshot 和 snapshotComplete 保存平台返回的完整 Cookie Jar。
|
||||
cookieSnapshot, snapshotComplete := qrCookieSnapshot(result)
|
||||
// scannedAccountID 是扫码结果中的平台账号标识。
|
||||
scannedAccountID := strings.TrimSpace(firstNonEmpty(qrString(result, "unb"), protocol.TransCookies(cookies)["unb"]))
|
||||
if cookies == "" || scannedAccountID == "" {
|
||||
return qrLoginPersistence{}, errors.New("扫码结果缺少 cookies 或 unb")
|
||||
}
|
||||
// accountID 是最终写入的账号标识。
|
||||
accountID := strings.TrimSpace(targetAccountID)
|
||||
if accountID == "" {
|
||||
accountID = scannedAccountID
|
||||
} else if accountID != scannedAccountID {
|
||||
return qrLoginPersistence{}, errors.New("扫码账号与待重新授权账号不一致,已拒绝覆盖")
|
||||
}
|
||||
|
||||
// isNew 标记本次扫码是否创建了新账号。
|
||||
isNew := false
|
||||
// credentialUnlock 保护账号凭证写入和登录审计。
|
||||
credentialUnlock := s.Store.LockAccountCredentials(accountID)
|
||||
// saveErr 保存账号凭证、Cookie Jar 和登录审计的事务错误。
|
||||
saveErr := func() error {
|
||||
defer credentialUnlock()
|
||||
// detail 和 err 保存待更新账号的凭证详情。
|
||||
detail, err := s.loadCookiePlatformDetail(ctx, accountID)
|
||||
switch {
|
||||
case errors.Is(err, db.ErrNotFound):
|
||||
if targetAccountID != "" {
|
||||
return errors.New("待重新授权账号不存在")
|
||||
}
|
||||
isNew = true
|
||||
// err 表示创建扫码账号的错误。
|
||||
if err := s.Store.Cookies.CreateOwned(ctx, accountID, cookies, userID); err != nil {
|
||||
return err
|
||||
}
|
||||
if snapshotComplete {
|
||||
// metadata 是新账号的完整 Cookie Jar 元数据。
|
||||
metadata := cookierefresh.MetadataWithSnapshot("", cookieSnapshot)
|
||||
// err 表示保存新账号 Cookie Jar 的错误。
|
||||
if err := s.Store.Cookies.UpdateRenewalCookie(ctx, accountID, cookies, metadata, time.Now().Unix()); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
case err != nil:
|
||||
return err
|
||||
case detail == nil:
|
||||
return db.ErrNotFound
|
||||
case detail.UserID != userID:
|
||||
if targetAccountID != "" {
|
||||
return errors.New("待重新授权账号不属于当前用户")
|
||||
}
|
||||
return db.ErrForbidden
|
||||
default:
|
||||
if snapshotComplete {
|
||||
// metadata 是已有账号合并后的 Cookie Jar 元数据。
|
||||
metadata := cookierefresh.MetadataWithSnapshot(detail.MetadataJSON, cookieSnapshot)
|
||||
// err 表示保存已有账号 Cookie Jar 的错误。
|
||||
if err := s.Store.Cookies.UpdateRenewalCookie(ctx, detail.ID, cookies, metadata, time.Now().Unix()); err != nil {
|
||||
return err
|
||||
}
|
||||
// err 表示合并扁平 Cookie 的错误。
|
||||
} else if err := s.updateFlatCookieOwnedLocked(ctx, detail, cookies); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
s.markSuccessfulLogin(ctx, accountID, userID, loginMethodQRScan, "扫码登录成功")
|
||||
if s.Store.Tokens != nil {
|
||||
// err 表示清理旧连接凭证的错误,仅记录不阻断扫码登录。
|
||||
if err := s.Store.Tokens.Clear(ctx, accountID); err != nil && s.Logger != nil {
|
||||
s.Logger.Warn("扫码登录保存后清理旧连接凭证失败", "cookie_id", accountID, "err", err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}()
|
||||
if saveErr != nil {
|
||||
if errors.Is(saveErr, db.ErrForbidden) {
|
||||
return qrLoginPersistence{}, errors.New("该账号ID已存在且不属于当前用户")
|
||||
}
|
||||
if errors.Is(saveErr, db.ErrAlreadyExists) {
|
||||
return qrLoginPersistence{}, errors.New("该账号ID已被并发创建,请重新获取账号状态")
|
||||
}
|
||||
return qrLoginPersistence{}, saveErr
|
||||
}
|
||||
// detail 和 err 保存登录成功后的资料摘要查询结果。
|
||||
if detail, err := s.loadCookieSummaryDetail(ctx, userID, accountID); err == nil {
|
||||
s.refreshAccountProfile(ctx, detail)
|
||||
}
|
||||
s.wakeCredentialBlockedAutomation(ctx, accountID)
|
||||
if s.Manager != nil && s.Store.Cookies.GetStatus(ctx, accountID) {
|
||||
// err 表示扫码登录后的账号运行时重启错误。
|
||||
if err := s.Manager.Restart(ctx, accountID); err != nil && s.Logger != nil {
|
||||
s.Logger.Warn("扫码登录后重启账号失败", "cookie_id", accountID, "err", err)
|
||||
}
|
||||
}
|
||||
// persisted 是扫码会话幂等返回值。
|
||||
persisted := qrLoginPersistence{AccountID: accountID, IsNew: isNew, UserID: userID, CreatedAt: time.Now().UTC()}
|
||||
s.qrMu.Lock()
|
||||
s.qrPersisted[sessionID] = persisted
|
||||
s.qrMu.Unlock()
|
||||
s.qrPersistLocks.Delete(sessionID)
|
||||
return persisted, nil
|
||||
}
|
||||
|
||||
// refreshAndRestartAccount 在凭证锁释放后刷新资料并按账号状态重启运行时。
|
||||
func (svc *accountLoginService) refreshAndRestartAccount(ctx context.Context, userID int64, accountID string) {
|
||||
// s 是当前账号登录应用服务依赖的 Server。
|
||||
s := svc.server
|
||||
// detail 和 err 保存资料摘要查询结果。
|
||||
detail, err := s.loadCookieSummaryDetail(ctx, userID, accountID)
|
||||
if err == nil {
|
||||
s.refreshAccountProfile(ctx, detail)
|
||||
}
|
||||
if s.Manager != nil && s.Store.Cookies.GetStatus(ctx, accountID) {
|
||||
// err 表示账号运行时重启错误。
|
||||
if err := s.Manager.Restart(ctx, accountID); err != nil && s.Logger != nil {
|
||||
s.Logger.Warn("账号登录后重启账号失败", "cookie_id", accountID, "err", err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ValidateCookieInput 校验账号标识和 Cookie 输入,供 HTTP 适配层复用一致规则。
|
||||
func (svc *accountLoginService) ValidateCookieInput(input accountLoginInput) error {
|
||||
if strings.TrimSpace(input.AccountID) == "" || strings.TrimSpace(input.Cookies) == "" {
|
||||
return errors.New("缺少账号 ID 或 Cookie")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
package server
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
)
|
||||
|
||||
// TestAccountLoginServiceValidateCookieInput 验证账号登录输入的基础校验规则。
|
||||
func TestAccountLoginServiceValidateCookieInput(t *testing.T) {
|
||||
// service 使用空 Server 即可测试纯输入校验。
|
||||
service := (&Server{}).accountLoginApplication()
|
||||
// err 表示空账号输入的校验结果。
|
||||
if err := service.ValidateCookieInput(accountLoginInput{AccountID: "", Cookies: "cookie"}); err == nil {
|
||||
t.Fatal("空账号 ID 应该校验失败")
|
||||
}
|
||||
// err 表示有效账号输入的校验结果。
|
||||
if err := service.ValidateCookieInput(accountLoginInput{AccountID: "acc1", Cookies: "cookie"}); err != nil {
|
||||
t.Fatalf("有效账号登录输入不应失败: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestAccountLoginServiceRefreshProfileNotFound 验证资料刷新服务不会越权读取不存在账号。
|
||||
func TestAccountLoginServiceRefreshProfileNotFound(t *testing.T) {
|
||||
// srv、store 和 cleanup 构造并释放测试服务。
|
||||
srv, _, cleanup := newTestServer(t)
|
||||
defer cleanup()
|
||||
// err 保存资料刷新服务返回的账号查询错误。
|
||||
_, err := srv.accountLoginApplication().RefreshProfile(context.Background(), 1, "missing-account")
|
||||
if err == nil {
|
||||
t.Fatal("不存在账号的资料刷新应该返回错误")
|
||||
}
|
||||
}
|
||||
|
||||
// TestAccountLoginServicePersistQRLoginRejectsIncompleteResult 验证扫码结果缺少凭证时不会写入账号。
|
||||
func TestAccountLoginServicePersistQRLoginRejectsIncompleteResult(t *testing.T) {
|
||||
// service 使用空 Server 即可在凭证校验前验证失败结果。
|
||||
service := (&Server{}).accountLoginApplication()
|
||||
// err 保存扫码结果校验错误。
|
||||
_, err := service.PersistQRLoginSuccess(context.Background(), 1, "session", map[string]any{"status": "success"}, "")
|
||||
if err == nil {
|
||||
t.Fatal("缺少 cookies 或 unb 的扫码结果应该失败")
|
||||
}
|
||||
}
|
||||
@@ -447,14 +447,13 @@ func (s *Server) refreshCookieProfile(w http.ResponseWriter, r *http.Request) {
|
||||
writeErr(w, http.StatusForbidden, "无权限操作该账号")
|
||||
return
|
||||
}
|
||||
d, err := s.loadCookieSummaryDetail(r.Context(), sess.UserID, cid) // d 和 err 是资料刷新所需的非敏感摘要及查询错误。
|
||||
profile, err := s.accountLoginApplication().RefreshProfile(r.Context(), sess.UserID, cid)
|
||||
if err != nil {
|
||||
writeErr(w, http.StatusNotFound, "账号不存在")
|
||||
return
|
||||
}
|
||||
nickname, avatarURL, profileErr := s.refreshAccountProfile(r.Context(), d) // 三个值是刷新后的资料及错误信息。
|
||||
writeJSON(w, http.StatusOK, cookieProfileResponse{
|
||||
Success: profileErr == "", ID: d.ID, Nickname: nickname, AvatarURL: avatarURL, ProfileError: profileErr,
|
||||
Success: profile.ErrorMessage == "", ID: cid, Nickname: profile.Nickname, AvatarURL: profile.AvatarURL, ProfileError: profile.ErrorMessage,
|
||||
})
|
||||
}
|
||||
|
||||
@@ -488,9 +487,7 @@ func (s *Server) addCookie(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
sess := auth.SessionFromContext(r.Context())
|
||||
credentialUnlock := s.Store.LockAccountCredentials(req.ID)
|
||||
if err := s.Store.Cookies.CreateOwned(r.Context(), req.ID, req.Value, sess.UserID); err != nil {
|
||||
credentialUnlock()
|
||||
if err := s.accountLoginApplication().CreateCookie(r.Context(), accountLoginInput{AccountID: req.ID, Cookies: req.Value, UserID: sess.UserID, LoginMethod: req.LoginMethod}); err != nil {
|
||||
if errors.Is(err, db.ErrForbidden) {
|
||||
writeErr(w, http.StatusForbidden, "该账号ID已存在且不属于当前用户")
|
||||
return
|
||||
@@ -502,32 +499,13 @@ func (s *Server) addCookie(w http.ResponseWriter, r *http.Request) {
|
||||
writeErr(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
if s.Store.Tokens != nil {
|
||||
if err := s.Store.Tokens.Clear(r.Context(), req.ID); err != nil {
|
||||
s.Logger.Warn("新增账号后清理旧连接凭证失败", "cookie_id", req.ID, "err", err)
|
||||
}
|
||||
}
|
||||
loginMethod := normalizeLoginMethod(req.LoginMethod)
|
||||
if loginMethod == "" {
|
||||
loginMethod = loginMethodManual
|
||||
}
|
||||
s.markSuccessfulLogin(r.Context(), req.ID, sess.UserID, loginMethod, "账号登录成功")
|
||||
credentialUnlock()
|
||||
if d, err := s.loadCookiePlatformDetail(r.Context(), req.ID); err == nil {
|
||||
s.refreshAccountProfile(r.Context(), d)
|
||||
}
|
||||
if s.Manager != nil && s.Store.Cookies.GetStatus(r.Context(), req.ID) {
|
||||
if err := s.Manager.Restart(r.Context(), req.ID); err != nil {
|
||||
s.Logger.Error("更新后重启账号失败", "cookie_id", req.ID, "err", err)
|
||||
}
|
||||
}
|
||||
writeJSON(w, http.StatusOK, accountMutationResponse{Success: true, ID: req.ID})
|
||||
}
|
||||
|
||||
// updateCookie 更新 cookie 值。
|
||||
func (s *Server) updateCookie(w http.ResponseWriter, r *http.Request) {
|
||||
cid := chi.URLParam(r, "cid")
|
||||
ownedDetail, ok := s.requireCookieOwner(w, r, cid)
|
||||
_, ok := s.requireCookieOwner(w, r, cid)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
@@ -540,15 +518,7 @@ func (s *Server) updateCookie(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
sess := auth.SessionFromContext(r.Context())
|
||||
credentialUnlock := s.Store.LockAccountCredentials(cid)
|
||||
detail, err := s.loadCookiePlatformDetail(r.Context(), cid)
|
||||
if err != nil || detail == nil || detail.UserID != ownedDetail.UserID || detail.UserID != sess.UserID {
|
||||
credentialUnlock()
|
||||
writeErr(w, http.StatusNotFound, "账号不存在")
|
||||
return
|
||||
}
|
||||
if err := s.updateFlatCookieOwnedLocked(r.Context(), detail, req.Value); err != nil {
|
||||
credentialUnlock()
|
||||
if err := s.accountLoginApplication().UpdateCookie(r.Context(), accountCookieUpdateInput{AccountID: cid, Cookies: req.Value, UserID: sess.UserID, LoginMethod: req.LoginMethod}); err != nil {
|
||||
if errors.Is(err, db.ErrForbidden) {
|
||||
writeErr(w, http.StatusForbidden, "无权限操作该账号")
|
||||
return
|
||||
@@ -556,23 +526,6 @@ func (s *Server) updateCookie(w http.ResponseWriter, r *http.Request) {
|
||||
writeErr(w, http.StatusBadRequest, err.Error())
|
||||
return
|
||||
}
|
||||
if s.Store.Tokens != nil {
|
||||
if err := s.Store.Tokens.Clear(r.Context(), cid); err != nil {
|
||||
s.Logger.Warn("更新账号后清理旧连接凭证失败", "cookie_id", cid, "err", err)
|
||||
}
|
||||
}
|
||||
if loginMethod := normalizeLoginMethod(req.LoginMethod); loginMethod != "" {
|
||||
s.markSuccessfulLogin(r.Context(), cid, sess.UserID, loginMethod, "账号登录成功")
|
||||
}
|
||||
credentialUnlock()
|
||||
if d, err := s.loadCookieSummaryDetail(r.Context(), sess.UserID, cid); err == nil {
|
||||
s.refreshAccountProfile(r.Context(), d)
|
||||
}
|
||||
if s.Manager != nil && s.Store.Cookies.GetStatus(r.Context(), cid) {
|
||||
if err := s.Manager.Restart(r.Context(), cid); err != nil {
|
||||
s.Logger.Error("更新后重启账号失败", "cookie_id", cid, "err", err)
|
||||
}
|
||||
}
|
||||
writeJSON(w, http.StatusOK, operationResponse{Success: true})
|
||||
}
|
||||
|
||||
|
||||
@@ -5,15 +5,12 @@ import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
|
||||
"xianyu-go/internal/auth"
|
||||
"xianyu-go/internal/db"
|
||||
"xianyu-go/internal/xianyu/cookierefresh"
|
||||
"xianyu-go/internal/xianyu/protocol"
|
||||
)
|
||||
|
||||
const qrLoginGenerateTimeout = 2 * time.Minute
|
||||
@@ -101,7 +98,7 @@ func (s *Server) checkQRLoginStatusAndPersist(w http.ResponseWriter, r *http.Req
|
||||
writeErr(w, http.StatusUnauthorized, "未授权访问")
|
||||
return
|
||||
}
|
||||
persisted, err := s.persistQRLoginSuccess(r.Context(), sess.UserID, sessionID, result)
|
||||
persisted, err := s.accountLoginApplication().PersistQRLoginSuccess(r.Context(), sess.UserID, sessionID, result, "")
|
||||
if err != nil {
|
||||
if s.Logger != nil {
|
||||
s.Logger.Warn("保存扫码登录结果失败", "session_id", sessionID, "err", err)
|
||||
@@ -171,7 +168,7 @@ func (s *Server) completeQRVerification(w http.ResponseWriter, r *http.Request)
|
||||
result["cookie_snapshot"] = snapshot
|
||||
}
|
||||
}
|
||||
persisted, persistErr := s.persistQRLoginSuccessFor(r.Context(), sess.UserID, sessionID, result, req.TargetAccountID)
|
||||
persisted, persistErr := s.accountLoginApplication().PersistQRLoginSuccess(r.Context(), sess.UserID, sessionID, result, req.TargetAccountID)
|
||||
if persistErr != nil {
|
||||
if s.Logger != nil {
|
||||
s.Logger.Warn("保存扫码验证结果失败", "session_id", sessionID, "err", persistErr)
|
||||
@@ -187,112 +184,14 @@ func (s *Server) completeQRVerification(w http.ResponseWriter, r *http.Request)
|
||||
writeJSON(w, http.StatusOK, resp)
|
||||
}
|
||||
|
||||
// persistQRLoginSuccess 保留历史调用方,委托账号登录应用服务完成扫码结果持久化。
|
||||
func (s *Server) persistQRLoginSuccess(ctx context.Context, userID int64, sessionID string, result map[string]any) (qrLoginPersistence, error) {
|
||||
return s.persistQRLoginSuccessFor(ctx, userID, sessionID, result, "")
|
||||
return s.accountLoginApplication().PersistQRLoginSuccess(ctx, userID, sessionID, result, "")
|
||||
}
|
||||
|
||||
// persistQRLoginSuccessFor 保留带目标账号的历史调用方,委托账号登录应用服务完成幂等持久化。
|
||||
func (s *Server) persistQRLoginSuccessFor(ctx context.Context, userID int64, sessionID string, result map[string]any, targetAccountID string) (qrLoginPersistence, error) {
|
||||
lockValue, _ := s.qrPersistLocks.LoadOrStore(sessionID, &sync.Mutex{})
|
||||
persistMu := lockValue.(*sync.Mutex)
|
||||
persistMu.Lock()
|
||||
defer persistMu.Unlock()
|
||||
|
||||
s.qrMu.Lock()
|
||||
if s.qrPersisted == nil {
|
||||
s.qrPersisted = make(map[string]qrLoginPersistence)
|
||||
}
|
||||
if persisted, ok := s.qrPersisted[sessionID]; ok {
|
||||
s.qrMu.Unlock()
|
||||
if persisted.UserID != userID {
|
||||
return qrLoginPersistence{}, errors.New("扫码会话不属于当前用户")
|
||||
}
|
||||
return persisted, nil
|
||||
}
|
||||
s.qrMu.Unlock()
|
||||
cookies := qrString(result, "cookies")
|
||||
cookieSnapshot, snapshotComplete := qrCookieSnapshot(result)
|
||||
scannedAccountID := strings.TrimSpace(firstNonEmpty(qrString(result, "unb"), protocol.TransCookies(cookies)["unb"]))
|
||||
if cookies == "" || scannedAccountID == "" {
|
||||
return qrLoginPersistence{}, errors.New("扫码结果缺少 cookies 或 unb")
|
||||
}
|
||||
accountID := strings.TrimSpace(targetAccountID)
|
||||
if accountID == "" {
|
||||
accountID = scannedAccountID
|
||||
} else if accountID != scannedAccountID {
|
||||
return qrLoginPersistence{}, errors.New("扫码账号与待重新授权账号不一致,已拒绝覆盖")
|
||||
}
|
||||
|
||||
isNew := false
|
||||
credentialUnlock := s.Store.LockAccountCredentials(accountID)
|
||||
saveErr := func() error {
|
||||
defer credentialUnlock()
|
||||
detail, err := s.loadCookiePlatformDetail(ctx, accountID)
|
||||
switch {
|
||||
case errors.Is(err, db.ErrNotFound):
|
||||
if targetAccountID != "" {
|
||||
return errors.New("待重新授权账号不存在")
|
||||
}
|
||||
isNew = true
|
||||
if err := s.Store.Cookies.CreateOwned(ctx, accountID, cookies, userID); err != nil {
|
||||
return err
|
||||
}
|
||||
if snapshotComplete {
|
||||
metadata := cookierefresh.MetadataWithSnapshot("", cookieSnapshot)
|
||||
if err := s.Store.Cookies.UpdateRenewalCookie(ctx, accountID, cookies, metadata, time.Now().Unix()); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
case err != nil:
|
||||
return err
|
||||
case detail == nil:
|
||||
return db.ErrNotFound
|
||||
case detail.UserID != userID:
|
||||
if targetAccountID != "" {
|
||||
return errors.New("待重新授权账号不属于当前用户")
|
||||
}
|
||||
return db.ErrForbidden
|
||||
default:
|
||||
if snapshotComplete {
|
||||
metadata := cookierefresh.MetadataWithSnapshot(detail.MetadataJSON, cookieSnapshot)
|
||||
if err := s.Store.Cookies.UpdateRenewalCookie(ctx, detail.ID, cookies, metadata, time.Now().Unix()); err != nil {
|
||||
return err
|
||||
}
|
||||
} else if err := s.updateFlatCookieOwnedLocked(ctx, detail, cookies); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
s.markSuccessfulLogin(ctx, accountID, userID, loginMethodQRScan, "扫码登录成功")
|
||||
if s.Store.Tokens != nil {
|
||||
if err := s.Store.Tokens.Clear(ctx, accountID); err != nil {
|
||||
s.Logger.Warn("扫码登录保存后清理旧连接凭证失败", "cookie_id", accountID, "err", err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}()
|
||||
if saveErr != nil {
|
||||
if errors.Is(saveErr, db.ErrForbidden) {
|
||||
return qrLoginPersistence{}, errors.New("该账号ID已存在且不属于当前用户")
|
||||
}
|
||||
if errors.Is(saveErr, db.ErrAlreadyExists) {
|
||||
return qrLoginPersistence{}, errors.New("该账号ID已被并发创建,请重新获取账号状态")
|
||||
}
|
||||
return qrLoginPersistence{}, saveErr
|
||||
}
|
||||
if d, err := s.loadCookieSummaryDetail(ctx, userID, accountID); err == nil {
|
||||
s.refreshAccountProfile(ctx, d)
|
||||
}
|
||||
s.wakeCredentialBlockedAutomation(ctx, accountID)
|
||||
if s.Manager != nil && s.Store.Cookies.GetStatus(ctx, accountID) {
|
||||
if err := s.Manager.Restart(ctx, accountID); err != nil && s.Logger != nil {
|
||||
s.Logger.Warn("扫码登录后重启账号失败", "cookie_id", accountID, "err", err)
|
||||
}
|
||||
}
|
||||
persisted := qrLoginPersistence{AccountID: accountID, IsNew: isNew, UserID: userID, CreatedAt: time.Now().UTC()}
|
||||
s.qrMu.Lock()
|
||||
s.qrPersisted[sessionID] = persisted
|
||||
s.qrMu.Unlock()
|
||||
s.qrPersistLocks.Delete(sessionID)
|
||||
return persisted, nil
|
||||
return s.accountLoginApplication().PersistQRLoginSuccess(ctx, userID, sessionID, result, targetAccountID)
|
||||
}
|
||||
|
||||
func (s *Server) requireQRSessionOwner(w http.ResponseWriter, r *http.Request, sessionID string) bool {
|
||||
|
||||
Reference in new issue
Block a user