feat(server/auth): 新用户注册欢迎通知——注册同事务插 reward 类到账(零孤儿)
ci-pangolin / Lint — shellcheck (pull_request) Successful in 13s
ci-pangolin / Redline Scan — 脱敏 (UI 文案) (pull_request) Successful in 24s
ci-pangolin / Cleartext Scan — Android 禁明文 (pull_request) Successful in 20s
ci-pangolin / OpenAPI Sync Check (pull_request) Successful in 34s
ci-pangolin / Portable SQL — 可移植性 (mysql/sqlite) (pull_request) Successful in 22s
ci-pangolin / Flutter — analyze + test (pull_request) Successful in 36s
ci-pangolin / Codegen Drift — token 生成物未漂移 (pull_request) Successful in 3s
ci-pangolin / DS-flow — 原型/跨端同源/代码色单源闸 (pull_request) Successful in 4s
ci-pangolin / Go — build + test (pull_request) Failing after 13s
ci-pangolin / E2E Smoke — L4 进程级端到端 (pull_request) Failing after 11s
ci-pangolin / Go — integration (mysql/redis testcontainers) (pull_request) Failing after 4m37s
ci-pangolin / Golden — 视觉回归 (全量:components/auth/desktop/tablet) (pull_request) Failing after 19s
ci-pangolin / Lint — shellcheck (pull_request) Successful in 13s
ci-pangolin / Redline Scan — 脱敏 (UI 文案) (pull_request) Successful in 24s
ci-pangolin / Cleartext Scan — Android 禁明文 (pull_request) Successful in 20s
ci-pangolin / OpenAPI Sync Check (pull_request) Successful in 34s
ci-pangolin / Portable SQL — 可移植性 (mysql/sqlite) (pull_request) Successful in 22s
ci-pangolin / Flutter — analyze + test (pull_request) Successful in 36s
ci-pangolin / Codegen Drift — token 生成物未漂移 (pull_request) Successful in 3s
ci-pangolin / DS-flow — 原型/跨端同源/代码色单源闸 (pull_request) Successful in 4s
ci-pangolin / Go — build + test (pull_request) Failing after 13s
ci-pangolin / E2E Smoke — L4 进程级端到端 (pull_request) Failing after 11s
ci-pangolin / Go — integration (mysql/redis testcontainers) (pull_request) Failing after 4m37s
ci-pangolin / Golden — 视觉回归 (全量:components/auth/desktop/tablet) (pull_request) Failing after 19s
CreateUserWithTrial 新增本地 Noticer 接口(同 InsertNoticeTx 签名,参照 reward 包做法避免 notices→auth 循环依赖);SQLStore 加 noticer 字段 + SetNoticer, nil-safe。注册事务插完 trial 订阅、commit 前,若已注入 noticer 则同事务插一条 type=reward 的双语欢迎通知(标题/正文按 trialDays 参数化),失败即整事务回滚, 与 reward/pay 到账钩子同语义、零孤儿。main.go 在 noticesStore 构造后装配 authStore.SetNoticer(noticesStore)(authStore 提升到 if-block 外声明以跨块可见)。 顺带修复 isDuplicateKey 只认 MySQL 错误文案的 dialect 缺口——sqlite 下重复邮箱 注册此前会落入错误分支返回不透明的「auth: insert user」,而非 ErrEmailTaken; 现同时匹配 sqlite 的 "UNIQUE constraint failed"。 Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01P9G7E3wmAYL9KeYCVZVsqu
This commit is contained in:
@@ -282,6 +282,7 @@ func mountV1(r chi.Router, sqlDB *sql.DB, rdb *redis.Client, nodeSvc *nodes.Serv
|
||||
// ── Auth ──────────────────────────────────────────────────────────────────
|
||||
var authHandler *auth.Handler
|
||||
var authSvc *auth.Service
|
||||
var authStore *auth.SQLStore
|
||||
if tm != nil {
|
||||
var mailer auth.Mailer
|
||||
if smtpHost := os.Getenv("SMTP_HOST"); smtpHost != "" {
|
||||
@@ -296,7 +297,7 @@ func mountV1(r chi.Router, sqlDB *sql.DB, rdb *redis.Client, nodeSvc *nodes.Serv
|
||||
mailer = auth.NewLogMailer(nil) // dev: code printed to log
|
||||
}
|
||||
rl := auth.NewRateLimiter(rdb, nil)
|
||||
authStore := auth.NewSQLStore(sqlDB)
|
||||
authStore = auth.NewSQLStore(sqlDB)
|
||||
authSvc = auth.NewService(authStore, rdb, rl, tm, mailer, auth.ServiceConfig{}, nil)
|
||||
authSvc.SetDeviceRegistrar(authDeviceRegistrar{svc: devicesSvc})
|
||||
authSvc.SetSessionStore(sessionStore)
|
||||
@@ -355,6 +356,9 @@ func mountV1(r chi.Router, sqlDB *sql.DB, rdb *redis.Client, nodeSvc *nodes.Serv
|
||||
noticesStore := notices.NewStore(sqlDB)
|
||||
noticesHandler := notices.NewHandler(noticesStore)
|
||||
rewardSvc.SetNoticer(noticesStore)
|
||||
if authStore != nil {
|
||||
authStore.SetNoticer(noticesStore)
|
||||
}
|
||||
|
||||
// ── Pay(pay v2 统一支付网关;PAY_BASE_URL 未配则整组不挂载)──────────────
|
||||
var payHandler *pay.Handler
|
||||
|
||||
@@ -42,14 +42,25 @@ type UserStore interface {
|
||||
GetUserByEmail(ctx context.Context, email string) (*User, error)
|
||||
}
|
||||
|
||||
// Noticer 抽象 notices.Store 的事务内插入入口(测试可替身;生产传 notices.NewStore(db))。
|
||||
// auth → notices 单向依赖,不引入 import cycle,故本地声明接口、不直接 import notices
|
||||
// (参照 reward 包 Noticer 的做法)。
|
||||
type Noticer interface {
|
||||
InsertNoticeTx(ctx context.Context, tx *sql.Tx, userID int64, typ, titleZH, titleEN, bodyZH, bodyEN, link string, now time.Time) error
|
||||
}
|
||||
|
||||
// SQLStore is the MySQL-backed UserStore.
|
||||
type SQLStore struct {
|
||||
db *sql.DB
|
||||
db *sql.DB
|
||||
noticer Noticer
|
||||
}
|
||||
|
||||
// NewSQLStore builds a SQLStore.
|
||||
func NewSQLStore(db *sql.DB) *SQLStore { return &SQLStore{db: db} }
|
||||
|
||||
// SetNoticer 注入注册欢迎通知钩子(notices.Store 满足此接口);为 nil 时跳过(装配前兼容)。
|
||||
func (s *SQLStore) SetNoticer(n Noticer) { s.noticer = n }
|
||||
|
||||
// CreateUserWithTrial implements UserStore.
|
||||
func (s *SQLStore) CreateUserWithTrial(ctx context.Context, email, pwHash string, trialDays int) (*User, error) {
|
||||
userUUID := uuid.NewString()
|
||||
@@ -95,6 +106,17 @@ func (s *SQLStore) CreateUserWithTrial(ctx context.Context, email, pwHash string
|
||||
return nil, fmt.Errorf("auth: insert trial subscription: %w", err)
|
||||
}
|
||||
|
||||
// 欢迎站内通知:同事务插入,注册回滚则通知不留(零孤儿),与 reward/pay 到账接缝同语义。
|
||||
if s.noticer != nil {
|
||||
titleZH := "欢迎加入 Pangolin 🎉"
|
||||
titleEN := "Welcome to Pangolin 🎉"
|
||||
bodyZH := fmt.Sprintf("已为你开通 %d 天 PRO 会员,现在就选节点连接,畅享全球网络。", trialDays)
|
||||
bodyEN := fmt.Sprintf("Your %d-day PRO trial is active. Pick a node and connect to enjoy unrestricted access.", trialDays)
|
||||
if err := s.noticer.InsertNoticeTx(ctx, tx, userID, "reward", titleZH, titleEN, bodyZH, bodyEN, "", now); err != nil {
|
||||
return nil, fmt.Errorf("auth: insert welcome notice: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
if err := tx.Commit(); err != nil {
|
||||
return nil, fmt.Errorf("auth: commit: %w", err)
|
||||
}
|
||||
@@ -125,11 +147,15 @@ func (s *SQLStore) GetUserByEmail(ctx context.Context, email string) (*User, err
|
||||
return &u, nil
|
||||
}
|
||||
|
||||
// isDuplicateKey reports whether err is a MySQL duplicate-key (1062) error.
|
||||
// isDuplicateKey reports whether err is a duplicate-key/unique-constraint
|
||||
// violation, dialect-neutral: MySQL ("Duplicate entry" / 1062) and sqlite
|
||||
// (modernc.org/sqlite "UNIQUE constraint failed" / SQLITE_CONSTRAINT_UNIQUE
|
||||
// 2067) both matched by message text.
|
||||
func isDuplicateKey(err error) bool {
|
||||
if err == nil {
|
||||
return false
|
||||
}
|
||||
msg := err.Error()
|
||||
return strings.Contains(msg, "Duplicate entry") || strings.Contains(msg, "1062")
|
||||
return strings.Contains(msg, "Duplicate entry") || strings.Contains(msg, "1062") ||
|
||||
strings.Contains(msg, "UNIQUE constraint failed")
|
||||
}
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
package auth_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"testing"
|
||||
|
||||
"github.com/wangjia/pangolin/server/internal/auth"
|
||||
"github.com/wangjia/pangolin/server/internal/notices"
|
||||
)
|
||||
|
||||
// TestCreateUserWithTrial_InsertsWelcomeNotice: 注册同事务应插入一条欢迎到账通知,
|
||||
// 双语文案按 trialDays 参数化。用真实 notices.Store(而非 fake)验证落库结果;
|
||||
// 放在外部测试包(package auth_test)是因为 notices 反向 import auth(handler.go),
|
||||
// 若同包(package auth)测试文件再 import notices 会成环 —— 参照 store_sqlite_test.go
|
||||
// 里 fakeNoticer 单测的注释。
|
||||
func TestCreateUserWithTrial_InsertsWelcomeNotice(t *testing.T) {
|
||||
db := auth.OpenAuthDBForTest(t)
|
||||
s := auth.NewSQLStore(db)
|
||||
s.SetNoticer(notices.NewStore(db))
|
||||
|
||||
u, err := s.CreateUserWithTrial(context.Background(), "welcome@example.com", "hash", 7)
|
||||
if err != nil {
|
||||
t.Fatalf("CreateUserWithTrial: %v", err)
|
||||
}
|
||||
|
||||
var n int
|
||||
if err := db.QueryRow(`SELECT COUNT(*) FROM notices WHERE type='reward' AND user_id=?`, u.ID).Scan(&n); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if n != 1 {
|
||||
t.Fatalf("welcome notice count = %d, want 1", n)
|
||||
}
|
||||
|
||||
var typ, titleZH, titleEN, bodyZH, bodyEN string
|
||||
row := db.QueryRow(`SELECT type, title_zh, title_en, body_zh, body_en FROM notices WHERE user_id=?`, u.ID)
|
||||
if err := row.Scan(&typ, &titleZH, &titleEN, &bodyZH, &bodyEN); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if typ != "reward" {
|
||||
t.Fatalf("type = %q, want reward", typ)
|
||||
}
|
||||
if titleZH != "欢迎加入 Pangolin 🎉" {
|
||||
t.Fatalf("titleZH = %q", titleZH)
|
||||
}
|
||||
if titleEN != "Welcome to Pangolin 🎉" {
|
||||
t.Fatalf("titleEN = %q", titleEN)
|
||||
}
|
||||
wantBodyZH := fmt.Sprintf("已为你开通 %d 天 PRO 会员,现在就选节点连接,畅享全球网络。", 7)
|
||||
if bodyZH != wantBodyZH {
|
||||
t.Fatalf("bodyZH = %q, want %q", bodyZH, wantBodyZH)
|
||||
}
|
||||
wantBodyEN := fmt.Sprintf("Your %d-day PRO trial is active. Pick a node and connect to enjoy unrestricted access.", 7)
|
||||
if bodyEN != wantBodyEN {
|
||||
t.Fatalf("bodyEN = %q, want %q", bodyEN, wantBodyEN)
|
||||
}
|
||||
}
|
||||
|
||||
// TestCreateUserWithTrial_DupEmail_NoNotice: 邮箱重复 → 用户插入失败(事务回滚),
|
||||
// 不应留下任何通知(零孤儿)。
|
||||
func TestCreateUserWithTrial_DupEmail_NoNotice(t *testing.T) {
|
||||
db := auth.OpenAuthDBForTest(t)
|
||||
s := auth.NewSQLStore(db)
|
||||
s.SetNoticer(notices.NewStore(db))
|
||||
|
||||
if _, err := s.CreateUserWithTrial(context.Background(), "dup@example.com", "hash", 7); err != nil {
|
||||
t.Fatalf("first CreateUserWithTrial: %v", err)
|
||||
}
|
||||
if _, err := s.CreateUserWithTrial(context.Background(), "dup@example.com", "hash2", 7); err != auth.ErrEmailTaken {
|
||||
t.Fatalf("second CreateUserWithTrial err = %v, want ErrEmailTaken", err)
|
||||
}
|
||||
|
||||
var n int
|
||||
if err := db.QueryRow(`SELECT COUNT(*) FROM notices`).Scan(&n); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if n != 1 {
|
||||
t.Fatalf("notices count = %d, want 1 (only the first registration's welcome notice)", n)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"fmt"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/wangjia/pangolin/server/internal/config"
|
||||
"github.com/wangjia/pangolin/server/internal/store"
|
||||
)
|
||||
|
||||
// openAuthDB spins up an in-memory sqlite DB with the full migration set
|
||||
// (plans get seeded by 000007_seed.up.sql), mirroring reward package's
|
||||
// openDB test harness. Exported (capitalized) so the external store_notices_test.go
|
||||
// (package auth_test, needed to avoid the notices->auth import cycle) can reuse it.
|
||||
func OpenAuthDBForTest(t *testing.T) *sql.DB {
|
||||
t.Helper()
|
||||
db, err := store.Open(&config.Config{Driver: "sqlite", DSN: ":memory:"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { _ = db.Close() })
|
||||
if err := store.MigrateUp(db, "sqlite"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := store.ApplyCodesLibMigrations(context.Background(), db, "sqlite"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return db
|
||||
}
|
||||
|
||||
// fakeNoticer 记录调用,用于验证「未设置 noticer 时跳过」与「显式 fake 校验参数」两种路径。
|
||||
// 用 fake(而非真实 notices.Store)是因为 notices 包反向 import auth(handler.go 用
|
||||
// auth.UserIDFromContext),同包内部测试(package auth)若再 import notices 会成环;
|
||||
// 真实 notices.Store 的集成断言放到外部测试包 store_notices_test.go(package auth_test)。
|
||||
type fakeNoticer struct {
|
||||
calls int
|
||||
last struct {
|
||||
userID int64
|
||||
typ, titleZH, titleEN string
|
||||
bodyZH, bodyEN, link string
|
||||
}
|
||||
}
|
||||
|
||||
func (f *fakeNoticer) InsertNoticeTx(_ context.Context, _ *sql.Tx, userID int64, typ, titleZH, titleEN, bodyZH, bodyEN, link string, _ time.Time) error {
|
||||
f.calls++
|
||||
f.last.userID = userID
|
||||
f.last.typ = typ
|
||||
f.last.titleZH = titleZH
|
||||
f.last.titleEN = titleEN
|
||||
f.last.bodyZH = bodyZH
|
||||
f.last.bodyEN = bodyEN
|
||||
f.last.link = link
|
||||
return nil
|
||||
}
|
||||
|
||||
// TestCreateUserWithTrial_NilNoticer_Skips: 未注入 noticer(装配前/未调用 SetNoticer)时,
|
||||
// 注册仍应成功且不 panic —— 保持既有装配可编译、零副作用。
|
||||
func TestCreateUserWithTrial_NilNoticer_Skips(t *testing.T) {
|
||||
db := OpenAuthDBForTest(t)
|
||||
s := NewSQLStore(db) // 不调用 SetNoticer
|
||||
|
||||
if _, err := s.CreateUserWithTrial(context.Background(), "nonoticer@example.com", "hash", 7); err != nil {
|
||||
t.Fatalf("CreateUserWithTrial: %v", err)
|
||||
}
|
||||
var n int
|
||||
if err := db.QueryRow(`SELECT COUNT(*) FROM notices`).Scan(&n); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if n != 0 {
|
||||
t.Fatalf("notices count = %d, want 0 when noticer not set", n)
|
||||
}
|
||||
}
|
||||
|
||||
// TestCreateUserWithTrial_FakeNoticer_CalledOnceWithArgs: 用 fake 断言被调用一次、
|
||||
// 参数与实际 trialDays 一致。
|
||||
func TestCreateUserWithTrial_FakeNoticer_CalledOnceWithArgs(t *testing.T) {
|
||||
db := OpenAuthDBForTest(t)
|
||||
s := NewSQLStore(db)
|
||||
fn := &fakeNoticer{}
|
||||
s.SetNoticer(fn)
|
||||
|
||||
u, err := s.CreateUserWithTrial(context.Background(), "fake@example.com", "hash", 14)
|
||||
if err != nil {
|
||||
t.Fatalf("CreateUserWithTrial: %v", err)
|
||||
}
|
||||
if fn.calls != 1 {
|
||||
t.Fatalf("noticer calls = %d, want 1", fn.calls)
|
||||
}
|
||||
if fn.last.userID != u.ID {
|
||||
t.Fatalf("noticer userID = %d, want %d", fn.last.userID, u.ID)
|
||||
}
|
||||
if fn.last.typ != "reward" {
|
||||
t.Fatalf("noticer typ = %q, want reward", fn.last.typ)
|
||||
}
|
||||
wantBodyZH := fmt.Sprintf("已为你开通 %d 天 PRO 会员,现在就选节点连接,畅享全球网络。", 14)
|
||||
if fn.last.bodyZH != wantBodyZH {
|
||||
t.Fatalf("noticer bodyZH = %q, want %q", fn.last.bodyZH, wantBodyZH)
|
||||
}
|
||||
if fn.last.link != "" {
|
||||
t.Fatalf("noticer link = %q, want empty", fn.last.link)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user