a5e25b444f
实现 server/internal/auth 控制面鉴权底座,对应 doc/02 §4.1、doc/06 §3:
- POST /v1/auth/code:IP+邮箱双维度 Redis 滑窗限频(同邮箱 1/min、同 IP 10/h)
+ 一次性邮箱域黑名单(embed 词表)→ 6 位数字码写 auth:code:{email} TTL 10min
→ 异步发信(SMTP / 开发态 log mailer)。
- POST /v1/auth/register:验码(一次性,删 key;超次数烧码)→ 单事务建号
(uuid + dp_uuid 应用层生成、argon2id)+ 7 天 PRO 试用(source='trial')→ 签发 JWT。
- POST /v1/auth/login:argon2id 校验(失败恒定时、未知用户走 dummy hash);
失败计数限流 rl:login:{email} + 锁定;banned 拒绝。
- POST /v1/auth/refresh:RS256,access 15min + refresh 30d 落 Redis 白名单
jwt:refresh:{jti},旋转时删旧写新;JWT 头带 kid,验证端接受新旧公钥支持轮换。
- RequireAuth 中间件:解析 Bearer access,注入 user id(复用 codes.CtxKeyUserID
避免循环依赖)+ uuid + claims 到 context。
- 错误体统一走 internal/apierr 的 {code, message_zh, message_en},文案双语脱敏。
- 文件拆分:handler/service/password/token/ratelimit/emailcheck/store/mailer/
middleware/errors/keyloader;config 增加可选 JWT PEM 路径/kid 加载。
测试:password/token/ratelimit/emailcheck/service/handler/middleware 单测
(miniredis,含注册全流程、重复邮箱 409、验证码错误/过期/复用/烧码、限频 429
带 Retry-After、登录失败锁定、banned 拒绝、refresh 旋转后旧 token 失效),
go test -race 通过;集成测试 integration_test.go(testcontainers MySQL8+Redis,
register→login→refresh→受保护接口全链路,构建 tag integration)与 codes 模块同构。
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
134 lines
3.9 KiB
Go
134 lines
3.9 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"
|
|
}
|
|
|
|
// 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)
|
|
}
|
|
|
|
// SQLStore is the MySQL-backed UserStore.
|
|
type SQLStore struct {
|
|
db *sql.DB
|
|
}
|
|
|
|
// NewSQLStore builds a SQLStore.
|
|
func NewSQLStore(db *sql.DB) *SQLStore { return &SQLStore{db: db} }
|
|
|
|
// 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()
|
|
}
|
|
}()
|
|
|
|
res, err := tx.ExecContext(ctx,
|
|
`INSERT INTO users (uuid, email, pw_hash, dp_uuid, status, created_at)
|
|
VALUES (?, ?, ?, ?, 'active', UTC_TIMESTAMP(6))`,
|
|
userUUID, email, pwHash, dpUUID)
|
|
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 := time.Now().UTC().AddDate(0, 0, trialDays)
|
|
if _, err := tx.ExecContext(ctx,
|
|
`INSERT INTO subscriptions (user_id, plan_id, expires_at, source, created_at)
|
|
VALUES (?, ?, ?, 'trial', UTC_TIMESTAMP(6))`,
|
|
userID, proID, expires); err != nil {
|
|
return nil, fmt.Errorf("auth: insert trial subscription: %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 FROM users WHERE email = ?`,
|
|
email).Scan(&u.ID, &u.UUID, &u.Email, &u.PwHash, &u.DpUUID, &u.Status)
|
|
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 MySQL duplicate-key (1062) error.
|
|
func isDuplicateKey(err error) bool {
|
|
if err == nil {
|
|
return false
|
|
}
|
|
msg := err.Error()
|
|
return strings.Contains(msg, "Duplicate entry") || strings.Contains(msg, "1062")
|
|
}
|