Files
pangolin/server/internal/auth/store.go
T
wangjia 68608d6471
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
feat(server/auth): 新用户注册欢迎通知——注册同事务插 reward 类到账(零孤儿)
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
2026-07-13 19:03:18 +08:00

162 lines
5.5 KiB
Go

package auth
import (
"context"
"database/sql"
"errors"
"fmt"
"strings"
"time"
"github.com/google/uuid"
)
// User is the subset of the users row the auth module needs.
type User struct {
ID int64
UUID string
Email string
PwHash string
DpUUID string
Status string // "active" | "banned"
TOTPEnabled bool // two-factor enabled → login requires a second TOTP step
}
// Sentinel store errors. Service maps these to API errors.
var (
// ErrEmailTaken is returned by CreateUserWithTrial on a duplicate email.
ErrEmailTaken = errors.New("auth: email already registered")
// ErrNotFound is returned when a user lookup yields no row.
ErrNotFound = errors.New("auth: user not found")
)
// UserStore is the persistence contract for the auth module. The MySQL
// implementation lives in this file; tests substitute an in-memory fake.
type UserStore interface {
// CreateUserWithTrial atomically inserts a new user and a 7-day PRO trial
// subscription (source='trial') in a single transaction. The email UNIQUE
// constraint guarantees a single trial per address; a duplicate returns
// ErrEmailTaken. trialDays controls the trial length.
CreateUserWithTrial(ctx context.Context, email, pwHash string, trialDays int) (*User, error)
// GetUserByEmail returns the user for login. ErrNotFound when absent.
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
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()
dpUUID := uuid.NewString()
tx, err := s.db.BeginTx(ctx, &sql.TxOptions{Isolation: sql.LevelReadCommitted})
if err != nil {
return nil, fmt.Errorf("auth: begin tx: %w", err)
}
committed := false
defer func() {
if !committed {
_ = tx.Rollback()
}
}()
now := time.Now().UTC()
res, err := tx.ExecContext(ctx,
`INSERT INTO users (uuid, email, pw_hash, dp_uuid, status, created_at)
VALUES (?, ?, ?, ?, 'active', ?)`,
userUUID, email, pwHash, dpUUID, now)
if err != nil {
if isDuplicateKey(err) {
return nil, ErrEmailTaken
}
return nil, fmt.Errorf("auth: insert user: %w", err)
}
userID, err := res.LastInsertId()
if err != nil {
return nil, fmt.Errorf("auth: user last id: %w", err)
}
// Resolve the PRO plan id and insert the trial subscription.
var proID int64
if err := tx.QueryRowContext(ctx, `SELECT id FROM plans WHERE code='pro'`).Scan(&proID); err != nil {
return nil, fmt.Errorf("auth: lookup pro plan: %w", err)
}
expires := now.AddDate(0, 0, trialDays)
if _, err := tx.ExecContext(ctx,
`INSERT INTO subscriptions (user_id, plan_id, expires_at, source, created_at)
VALUES (?, ?, ?, 'trial', ?)`,
userID, proID, expires, now); err != nil {
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)
}
committed = true
return &User{
ID: userID,
UUID: userUUID,
Email: email,
PwHash: pwHash,
DpUUID: dpUUID,
Status: "active",
}, nil
}
// GetUserByEmail implements UserStore.
func (s *SQLStore) GetUserByEmail(ctx context.Context, email string) (*User, error) {
var u User
err := s.db.QueryRowContext(ctx,
`SELECT id, uuid, email, pw_hash, dp_uuid, status, totp_enabled FROM users WHERE email = ?`,
email).Scan(&u.ID, &u.UUID, &u.Email, &u.PwHash, &u.DpUUID, &u.Status, &u.TOTPEnabled)
if err == sql.ErrNoRows {
return nil, ErrNotFound
}
if err != nil {
return nil, fmt.Errorf("auth: get user by email: %w", err)
}
return &u, nil
}
// 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") ||
strings.Contains(msg, "UNIQUE constraint failed")
}