feat(auth+desktop): 邮箱验证码登录 + 登录窗改版(微信/邮箱双方式,无边框)
ci / server (push) Failing after 10s
ci / design-system (push) Failing after 10s

后端(协议 → 存储 → 接口,E2E 测试全绿):
- protocol:AuthEmailCodeRequest / AuthEmailRequest DTO
- store:EmailIdentity 表(邮箱唯一索引)+ authmail:* Redis key
- auth/email.go:POST /v1/auth/email/code 发 6 位码(crypto/rand,
  60s 冷却 SetNX,10 分钟 TTL);POST /v1/auth/email 常量时间比对、
  码一次性、邮箱建号(昵称取前缀)→ JWT(与微信登录同响应形态)
- Mailer 接口 + MockMailer(验证码打日志供联调;SMTP 未配置自动降级,
  装配结果入启动日志,上线前须换真实实现)
- TestEmailLogin E2E:发码/冷却 429/错码拒绝/登录/token 可用/码防复用

桌面(Rust 命令 + UI 改版):
- api.rs:login_email_code / login_email(成功保存 token + ws 重连,
  与扫码登录同路径)
- 登录窗改版(原型 LoginPurchase 先行,dark 截图验收):logo + 分段
  切换(微信扫码 / 邮箱登录,与设置页同控件语言)+ 邮箱表单
  (60s 倒计时、错误文案、未注册自动建号提示)
- 二维码真渲染:qrcode 库画 canvas(前景/背景取主题 token),
  替换原 URL 文本占位;过期态半透明化
- 登录窗无边框化:transparent + Overlay 标题栏 + 原生贴形阴影;
  抽公共 WindowFrame 组件(设置窗同步重构复用)

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
wangjia
2026-07-11 09:40:16 +08:00
parent 0ca1caa460
commit 19281d9c42
20 changed files with 871 additions and 86 deletions
+152
View File
@@ -0,0 +1,152 @@
// 邮箱验证码登录(桌面端第二登录方式):
// POST /v1/auth/email/code 发送 6 位验证码(60s 冷却,码 10 分钟有效)
// POST /v1/auth/email 校验验证码 → 建号/登录 → JWT
// 邮件发送经 Mailer 接口;SMTP 未配置时装配 MockMailer(验证码打日志,供联调)。
package auth
import (
"context"
"crypto/rand"
"crypto/subtle"
"errors"
"log/slog"
"net/http"
"strings"
"time"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
"github.com/redis/go-redis/v9"
"gorm.io/gorm"
"dudu/server/internal/store"
"dudu/server/pkg/protocol"
)
const (
emailCodeTTL = 10 * time.Minute
emailCodeCooldown = 60 * time.Second
)
// Mailer 验证码邮件发送。
type Mailer interface {
SendCode(ctx context.Context, email, code string) error
}
// MockMailer 开发期 mock:验证码打日志不真发(⚠️ 上线前必须替换 SMTP 实现)。
type MockMailer struct{}
func (MockMailer) SendCode(_ context.Context, email, code string) error {
slog.Info("mock mailer: email login code", "email", email, "code", code)
return nil
}
// randCode 6 位数字验证码(crypto/rand)。
func randCode() string {
b := make([]byte, 6)
_, _ = rand.Read(b)
digits := make([]byte, 6)
for i, v := range b {
digits[i] = '0' + v%10
}
return string(digits)
}
// EmailCode POST /v1/auth/email/code 🔓
func (h *Handlers) EmailCode(c *gin.Context) {
var req protocol.AuthEmailCodeRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, protocol.NewAPIError(protocol.ErrBadRequest))
return
}
email := strings.ToLower(strings.TrimSpace(req.Email))
// 60s 冷却(SET NX),防轰炸
ok, err := h.RDB.SetNX(c, store.KeyAuthEmailCd(email), 1, emailCodeCooldown).Result()
if err != nil {
c.JSON(http.StatusInternalServerError, protocol.NewAPIError(protocol.ErrInternal))
return
}
if !ok {
c.JSON(http.StatusTooManyRequests, protocol.NewAPIError(protocol.ErrRateLimited))
return
}
code := randCode()
if err := h.RDB.Set(c, store.KeyAuthEmail(email), code, emailCodeTTL).Err(); err != nil {
c.JSON(http.StatusInternalServerError, protocol.NewAPIError(protocol.ErrInternal))
return
}
if err := h.Mailer.SendCode(c, email, code); err != nil {
slog.Error("send email code failed", "email", email, "err", err)
c.JSON(http.StatusInternalServerError, protocol.NewAPIError(protocol.ErrInternal))
return
}
c.Status(http.StatusNoContent)
}
// EmailLogin POST /v1/auth/email 🔓
func (h *Handlers) EmailLogin(c *gin.Context) {
var req protocol.AuthEmailRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, protocol.NewAPIError(protocol.ErrBadRequest))
return
}
email := strings.ToLower(strings.TrimSpace(req.Email))
want, err := h.RDB.Get(c, store.KeyAuthEmail(email)).Result()
if err == redis.Nil || subtle.ConstantTimeCompare([]byte(want), []byte(req.Code)) != 1 {
c.JSON(http.StatusBadRequest, protocol.NewAPIError(protocol.ErrBadRequest))
return
}
if err != nil && err != redis.Nil {
c.JSON(http.StatusInternalServerError, protocol.NewAPIError(protocol.ErrInternal))
return
}
// 一次性:校验通过即删,防复用
h.RDB.Del(c, store.KeyAuthEmail(email))
user, err := findOrCreateUserByEmail(h.DB, email)
if err != nil {
c.JSON(http.StatusInternalServerError, protocol.NewAPIError(protocol.ErrInternal))
return
}
token, err := h.JWT.Sign(user.ID)
if err != nil {
c.JSON(http.StatusInternalServerError, protocol.NewAPIError(protocol.ErrInternal))
return
}
c.JSON(http.StatusOK, protocol.AuthTokenResponse{
Token: token,
User: protocol.UserInfo{UserID: user.ID, NicknameMasked: MaskNickname(user.Nickname)},
})
}
// findOrCreateUserByEmail 邮箱身份建号/登录(昵称取邮箱前缀)。
func findOrCreateUserByEmail(db *gorm.DB, email string) (*store.User, error) {
var ident store.EmailIdentity
err := db.Where("email = ?", email).First(&ident).Error
if err == nil {
var u store.User
return &u, db.First(&u, "id = ?", ident.UserID).Error
}
if !errors.Is(err, gorm.ErrRecordNotFound) {
return nil, err
}
nick := email
if i := strings.IndexByte(email, '@'); i > 0 {
nick = email[:i]
}
user := store.User{ID: strings.ReplaceAll(uuid.NewString(), "-", "")[:24], Nickname: nick}
err = db.Transaction(func(tx *gorm.DB) error {
if err := tx.Create(&user).Error; err != nil {
return err
}
return tx.Create(&store.EmailIdentity{UserID: user.ID, Email: email}).Error
})
if err != nil {
return nil, err
}
return &user, nil
}
+2 -1
View File
@@ -14,12 +14,13 @@ import (
"dudu/server/pkg/protocol"
)
// Handlers 认证路由:扫码(5B)、微信 OAuth(5C)、logout。
// Handlers 认证路由:扫码(5B)、微信 OAuth(5C)、邮箱验证码、logout。
type Handlers struct {
DB *gorm.DB
RDB *redis.Client
JWT *JWT
Wechat WechatClient
Mailer Mailer
// QrAuthURL 二维码内容模板(真实环境为微信开放平台授权页,%s 为 state)
QrAuthURL string
}
+4
View File
@@ -40,6 +40,9 @@ type Config struct {
OSSKeyID string
OSSKeySecret string
// SMTP(邮箱验证码登录;未配置降级 mock mailer
SMTPHost string
// AppLatest 启动时解析 APP_LATEST_JSON 一次(17G):平台→版本信息。
// 解析失败或未配置则为 nil/空,handler 据此返回 204,不 fail-fast。
AppLatest map[string]protocol.AppLatestResponse
@@ -70,6 +73,7 @@ func Load() Config {
OSSEndpoint: os.Getenv("OSS_ENDPOINT"),
OSSBucket: os.Getenv("OSS_BUCKET"),
SMTPHost: os.Getenv("SMTP_HOST"),
OSSKeyID: os.Getenv("OSS_KEY_ID"),
OSSKeySecret: os.Getenv("OSS_KEY_SECRET"),
+59 -7
View File
@@ -24,7 +24,7 @@ import (
"dudu/server/pkg/protocol"
)
func newAPI(t *testing.T) (*httptest.Server, *gorm.DB) {
func newAPI(t *testing.T) (*httptest.Server, *gorm.DB, *redis.Client) {
t.Helper()
gin.SetMode(gin.TestMode)
mr := miniredis.RunT(t)
@@ -45,7 +45,7 @@ func newAPI(t *testing.T) (*httptest.Server, *gorm.DB) {
Register(r, &Deps{Cfg: cfg, DB: db, RDB: rdb, JWT: jwt, Quota: quota.New(rdb, db)})
srv := httptest.NewServer(r)
t.Cleanup(srv.Close)
return srv, db
return srv, db, rdb
}
func postJSON(t *testing.T, url, token string, body any) *http.Response {
@@ -93,7 +93,7 @@ func login(t *testing.T, srv *httptest.Server, code string) string {
}
func TestMobileLoginAndMe(t *testing.T) {
srv, _ := newAPI(t)
srv, _, _ := newAPI(t)
token := login(t, srv, "wangjia99")
var me protocol.MeResponse
@@ -120,7 +120,7 @@ func TestMobileLoginAndMe(t *testing.T) {
}
func TestQrLoginFlow(t *testing.T) {
srv, _ := newAPI(t)
srv, _, _ := newAPI(t)
resp := postJSON(t, srv.URL+"/v1/auth/qr", "", nil)
var qr protocol.AuthQrResponse
_ = json.NewDecoder(resp.Body).Decode(&qr)
@@ -154,7 +154,7 @@ func TestQrLoginFlow(t *testing.T) {
}
func TestOrderAndPayNotifyIdempotent(t *testing.T) {
srv, db := newAPI(t)
srv, db, _ := newAPI(t)
token := login(t, srv, "buyer1")
// packs
@@ -235,7 +235,7 @@ func postFeedback(t *testing.T, srv *httptest.Server, token, content string, ima
}
func TestFeedback(t *testing.T) {
srv, db := newAPI(t)
srv, db, _ := newAPI(t)
token := login(t, srv, "fbuser")
t.Cleanup(func() { _ = removeUploads() })
@@ -287,7 +287,7 @@ func TestFeedback(t *testing.T) {
func removeUploads() error { return nil } // LocalStorage 写入 var/uploads,测试容忍残留
func TestMetricsBatchAndAggregate(t *testing.T) {
srv, db := newAPI(t)
srv, db, _ := newAPI(t)
body := protocol.MetricsBatchRequest{
DeviceID: "dev-m1", Platform: "mac", AppVersion: "0.1.0",
Events: []protocol.MetricEvent{
@@ -314,3 +314,55 @@ func TestMetricsBatchAndAggregate(t *testing.T) {
t.Fatalf("want 2 events stored (whitelist), got %d", n)
}
}
// 邮箱验证码登录 E2E:发码(60s 冷却)→ 取码登录 → token 可用 → 码一次性。
func TestEmailLogin(t *testing.T) {
srv, _, rdb := newAPI(t)
// 发码
resp := postJSON(t, srv.URL+"/v1/auth/email/code", "", map[string]string{"email": "Dev@Example.com"})
if resp.StatusCode != http.StatusNoContent {
t.Fatalf("send code: want 204, got %d", resp.StatusCode)
}
// 冷却期内再发 → 429
resp = postJSON(t, srv.URL+"/v1/auth/email/code", "", map[string]string{"email": "dev@example.com"})
if resp.StatusCode != http.StatusTooManyRequests {
t.Fatalf("cooldown: want 429, got %d", resp.StatusCode)
}
code, err := rdb.Get(t.Context(), store.KeyAuthEmail("dev@example.com")).Result()
if err != nil {
t.Fatal(err)
}
// 错码拒绝
resp = postJSON(t, srv.URL+"/v1/auth/email", "", map[string]string{"email": "dev@example.com", "code": "000000"})
if code != "000000" && resp.StatusCode != http.StatusBadRequest {
t.Fatalf("wrong code: want 400, got %d", resp.StatusCode)
}
// 正确码登录
resp = postJSON(t, srv.URL+"/v1/auth/email", "", map[string]string{"email": "DEV@example.com", "code": code})
if resp.StatusCode != http.StatusOK {
t.Fatalf("login: want 200, got %d", resp.StatusCode)
}
var tok protocol.AuthTokenResponse
_ = json.NewDecoder(resp.Body).Decode(&tok)
if tok.Token == "" || tok.User.UserID == "" {
t.Fatalf("empty token/user: %+v", tok)
}
// token 可访问 /v1/me
req, _ := http.NewRequest("GET", srv.URL+"/v1/me", nil)
req.Header.Set("Authorization", "Bearer "+tok.Token)
meResp, err := http.DefaultClient.Do(req)
if err != nil || meResp.StatusCode != http.StatusOK {
t.Fatalf("me with email token: %v %d", err, meResp.StatusCode)
}
// 码一次性:复用被拒
resp = postJSON(t, srv.URL+"/v1/auth/email", "", map[string]string{"email": "dev@example.com", "code": code})
if resp.StatusCode != http.StatusBadRequest {
t.Fatalf("code reuse: want 400, got %d", resp.StatusCode)
}
}
+15 -2
View File
@@ -53,6 +53,15 @@ func pickWechat(cfg config.Config) (auth.WechatClient, string) {
return auth.MockWechat{}, "mock" // TODO(5C-真实): 开放平台实现,凭证就绪后替换
}
// pickMailer SMTP 未配置时使用 mock(验证码打日志,供联调)。返回 kind。
// ⚠️ 上线前必须配置真实 SMTP,否则邮箱登录形同虚设。
func pickMailer(cfg config.Config) (auth.Mailer, string) {
if cfg.SMTPHost == "" {
return auth.MockMailer{}, "mock"
}
return auth.MockMailer{}, "mock" // TODO(邮箱登录-真实): SMTP 实现,凭证就绪后替换
}
// pickPay 商户号未配置(#2B 申请中)时使用 mock。返回 kind="mock"。
// ⚠️⚠️ 上线前必须替换为真实 PayClientMockPay 不验签,/v1/pay/notify 等于公开充值接口。
func pickPay(cfg config.Config) (billing.PayClient, string) {
@@ -78,12 +87,14 @@ func Register(r *gin.Engine, d *Deps) {
wechat, wechatKind := pickWechat(d.Cfg)
pay, payKind := pickPay(d.Cfg)
storage, storageKind := pickStorage(d.Cfg)
mailer, mailerKind := pickMailer(d.Cfg)
// 启动时打印各外部依赖的装配结果(real/mock),便于部署核对(17E)。
slog.Info("dependency assembly",
"asr_provider", providerKind, "wechat", wechatKind, "pay", payKind, "storage", storageKind)
"asr_provider", providerKind, "wechat", wechatKind, "pay", payKind,
"storage", storageKind, "mailer", mailerKind)
authH := &auth.Handlers{DB: d.DB, RDB: d.RDB, JWT: d.JWT, Wechat: wechat}
authH := &auth.Handlers{DB: d.DB, RDB: d.RDB, JWT: d.JWT, Wechat: wechat, Mailer: mailer}
billH := &billing.Handlers{DB: d.DB, Pay: pay, Quota: d.Quota}
userH := &user.Handlers{DB: d.DB, Quota: d.Quota, AppVersions: d.Cfg.AppLatest}
fbH := &feedback.Handlers{DB: d.DB, RDB: d.RDB, Storage: storage}
@@ -103,6 +114,8 @@ func Register(r *gin.Engine, d *Deps) {
v1.GET("/auth/qr/:state", authH.PollQr)
v1.GET("/auth/wechat/callback", authH.QrCallback)
v1.POST("/auth/wechat", authH.MobileLogin)
v1.POST("/auth/email/code", authH.EmailCode)
v1.POST("/auth/email", authH.EmailLogin)
v1.GET("/packs", billH.Packs)
// ⚠️ 部署前必须切换到真实 PayClient(验签)!当前 MockPay 不验签,
// /v1/pay/notify 等于一个无鉴权的公开充值接口(任意人可伪造支付成功回调充值)。
Binary file not shown.

After

Width:  |  Height:  |  Size: 12 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 12 B

+10 -2
View File
@@ -24,6 +24,14 @@ type WechatIdentity struct {
CreatedAt time.Time
}
// EmailIdentity 邮箱验证码登录身份(桌面端第二登录方式)。
type EmailIdentity struct {
ID uint `gorm:"primaryKey"`
UserID string `gorm:"size:32;index;not null"`
Email string `gorm:"size:255;uniqueIndex;not null"`
CreatedAt time.Time
}
type DurationPack struct {
ID string `gorm:"primaryKey;size:32"`
Minutes int `gorm:"not null"`
@@ -141,10 +149,10 @@ type MetricDaily struct {
P95Ms float64 `gorm:"not null;default:0"`
}
// AllModels 迁移清单(11 张表)。
// AllModels 迁移清单(12 张表)。
func AllModels() []any {
return []any{
&User{}, &WechatIdentity{}, &DurationPack{}, &Order{}, &BalanceLedger{},
&User{}, &WechatIdentity{}, &EmailIdentity{}, &DurationPack{}, &Order{}, &BalanceLedger{},
&TrialUsage{}, &ASRSession{}, &Device{}, &Feedback{}, &MetricEvent{}, &MetricDaily{},
}
}
+2
View File
@@ -13,6 +13,8 @@ func KeyQuotaTrial(uid string, day string) string {
return "quota:" + uid + ":trial:" + day
}
func KeyAuthQr(state string) string { return "authqr:" + state }
func KeyAuthEmail(email string) string { return "authmail:" + email }
func KeyAuthEmailCd(email string) string { return "authmail:cd:" + email }
func KeyJwtBlock(jti string) string { return "jwt:block:" + jti }
func KeyRateCnt(did string) string { return "rate:" + did + ":asr:cnt" }
func KeyRateSecs(did string) string { return "rate:" + did + ":asr:secs" }
+10
View File
@@ -17,6 +17,16 @@ type AuthWechatRequest struct {
Code string `json:"code" binding:"required"`
}
// 邮箱验证码登录(桌面端第二登录方式)
type AuthEmailCodeRequest struct {
Email string `json:"email" binding:"required,email"`
}
type AuthEmailRequest struct {
Email string `json:"email" binding:"required,email"`
Code string `json:"code" binding:"required,len=6"`
}
type AuthTokenResponse struct {
Token string `json:"token"`
User UserInfo `json:"user"`