|
@@ -0,0 +1,1407 @@
|
|
|
|
|
+# 邮箱账号体系改造 Implementation Plan
|
|
|
|
|
+
|
|
|
|
|
+> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
|
|
|
|
|
+
|
|
|
|
|
+**Goal:** 客户账号从手机号改为邮箱(邮箱+验证码 / 邮箱+密码 双通道),legacy 手机号登录后强制绑定邮箱。
|
|
|
|
|
+
|
|
|
|
|
+**Architecture:** 方案 A 增量式:不动 JWT/PBKDF2/短信框架,`users` 加 `email` 列、新建 `email_codes` 表,新增 5 个 `/api/auth/email*` 端点;后端在 `auth.require_user()` 单点拦截未绑邮箱用户(403 `detail.code=bind-email`),前端 api.js 排队重试 + auth.js 强制绑定弹窗。设计文档见 `docs/superpowers/specs/2026-10-27-email-account-design.md`。
|
|
|
|
|
+
|
|
|
|
|
+**Tech Stack:** FastAPI + PyMySQL(MySQL 8) + Redis(60s 用户缓存,可降级)、原生 JS 静态站(React18+antd5 仅后台/订单页)、运行时 DOM i18n。
|
|
|
|
|
+
|
|
|
|
|
+**约定**
|
|
|
|
|
+- 所有 SQL 占位符 `%s`,只在 `server/db.py` 与路由文件中出现。
|
|
|
|
|
+- 测试即 `server/e2e_test.py`(项目无 pytest;脚本对运行中服务做全链路断言,`check()` 失败即 `sys.exit(1)`)。
|
|
|
|
|
+- 演示模式(`PL_DEMO=1` 默认 或 SMTP 未配置)验证码随响应返回,前端 toast 展示并自动填入——与现有短信行为一致。
|
|
|
|
|
+- 提交信息用中文,一任务一提交。
|
|
|
|
|
+
|
|
|
|
|
+**账户面板位置说明(与 spec 的偏差)**:spec 写"orders.html 我的区"。实现上把「账户设置」弹窗挂在 `auth.js` 的登录菜单里(全站可用,orders 页也在菜单处入口),功能清单不变:显示邮箱/密码状态、设置/修改密码、补绑邮箱。
|
|
|
|
|
+
|
|
|
|
|
+---
|
|
|
|
|
+
|
|
|
|
|
+## 文件结构
|
|
|
|
|
+
|
|
|
|
|
+| 文件 | 责任 | 动作 |
|
|
|
|
|
+|---|---|---|
|
|
|
|
|
+| `server/db.py` | 建表/迁移/行转字典 | 改:users.email 列、email_codes 表、user_row_to_dict 新字段 |
|
|
|
|
|
+| `server/auth.py` | 凭证与鉴权 | 改:邮箱校验/验证码收发、`require_user` 强制绑定拦截、`_user_dict` 新字段 |
|
|
|
|
|
+| `server/routes_auth.py` | 认证端点 | 改:+5 个邮箱端点 |
|
|
|
|
|
+| `server/i18n.py` | 服务端错误翻译 | 改:新文案 + dict 型 detail 翻译 |
|
|
|
|
|
+| `server/routes_admin.py` | 后台用户列表 | 改:搜索含 email |
|
|
|
|
|
+| `server/main.py` | 入口 | 改:version 1.8.23 |
|
|
|
|
|
+| `server/e2e_test.py` | 全链路测试 | 改:邮箱流程断言 |
|
|
|
|
|
+| `assets/js/api.js` | 请求层 | 改:403 bind-email 排队重试 |
|
|
|
|
|
+| `assets/js/auth.js` | 登录/账户 UI | 重写:三 tab + 强制绑定框 + 账户设置框 |
|
|
|
|
|
+| `assets/js/admin.js` | 后台用户表 | 改:邮箱列/搜索 |
|
|
|
|
|
+| `assets/js/i18n-en.js` | 英文字典 | 改:批次 11 新文案 |
|
|
|
|
|
+| `deploy/k8s/pouchlab.yaml` + `deploy/Dockerfile` 版本 | 部署 | 改:镜像 tag 1.8.23 |
|
|
|
|
|
+
|
|
|
|
|
+---
|
|
|
|
|
+
|
|
|
|
|
+## Task 1: 本地联调环境 + e2e 基线
|
|
|
|
|
+
|
|
|
|
|
+**Files:** 无代码改动
|
|
|
|
|
+
|
|
|
|
|
+- [ ] **Step 1: 起本地 MySQL(匹配 db.py 默认连接参数 root/pouchlab@127.0.0.1:3306/pouchlab)**
|
|
|
|
|
+
|
|
|
|
|
+```bash
|
|
|
|
|
+docker run -d --name pl-mysql -p 3306:3306 \
|
|
|
|
|
+ -e MYSQL_ROOT_PASSWORD=pouchlab -e MYSQL_DATABASE=pouchlab mysql:8
|
|
|
|
|
+# 等待就绪(约 30-60s)
|
|
|
|
|
+until docker exec pl-mysql mysqladmin ping -uroot -ppouchlab --silent; do sleep 2; done
|
|
|
|
|
+```
|
|
|
|
|
+
|
|
|
|
|
+Redis 可不装:`cache.py` 连接失败自动降级直查库。若本机 3306 已被占用,改用其他宿主端口并在启动 uvicorn 时加 `PL_DB_PORT=<端口>`。
|
|
|
|
|
+
|
|
|
|
|
+- [ ] **Step 2: 启动后端**
|
|
|
|
|
+
|
|
|
|
|
+```bash
|
|
|
|
|
+cd server && .venv/bin/uvicorn main:app --port 8080 &
|
|
|
|
|
+```
|
|
|
|
|
+
|
|
|
|
|
+Expected: 日志含 `Application startup complete`(startup 事件会建表+种子 admin/factory)。若 `.venv` 不存在:`python3 -m venv .venv && .venv/bin/pip install -r requirements.txt`。
|
|
|
|
|
+
|
|
|
|
|
+- [ ] **Step 3: 跑现有 e2e 确认基线绿**
|
|
|
|
|
+
|
|
|
|
|
+Run: `cd server && python3 e2e_test.py`
|
|
|
|
|
+Expected: 末行 `全部通过` 且退出码 0(约 60 项断言)。若历史用例本来就红,先修复或记录,再进入 Task 2。
|
|
|
|
|
+
|
|
|
|
|
+- [ ] **Step 4: 提交环境说明(可选,无代码则跳过)**
|
|
|
|
|
+
|
|
|
|
|
+---
|
|
|
|
|
+
|
|
|
|
|
+## Task 2: 数据库迁移 + 用户负载新字段
|
|
|
|
|
+
|
|
|
|
|
+**Files:**
|
|
|
|
|
+- Modify: `server/db.py`(SCHEMA_STATEMENTS:74-166、init_db:179-214、user_row_to_dict:270-282)
|
|
|
|
|
+- Modify: `server/auth.py`(`_user_dict`:约 117-127)
|
|
|
|
|
+- Test: 通过启动即验证(建表/迁移在 `init_db()` 内)
|
|
|
|
|
+
|
|
|
|
|
+- [ ] **Step 1: db.py users 建表语句加 email 列(新库直接带列)**
|
|
|
|
|
+
|
|
|
|
|
+在 `SCHEMA_STATEMENTS` 的 users CREATE 里,`phone VARCHAR(20) UNIQUE,` 之后插入一行:
|
|
|
|
|
+
|
|
|
|
|
+```sql
|
|
|
|
|
+ email VARCHAR(120) UNIQUE,
|
|
|
|
|
+```
|
|
|
|
|
+
|
|
|
|
|
+- [ ] **Step 2: SCHEMA_STATEMENTS 追加 email_codes 表(放在 sms_codes 语句之后,字段同构)**
|
|
|
|
|
+
|
|
|
|
|
+```python
|
|
|
|
|
+ """CREATE TABLE IF NOT EXISTS email_codes (
|
|
|
|
|
+ id INT AUTO_INCREMENT PRIMARY KEY,
|
|
|
|
|
+ email VARCHAR(120) NOT NULL,
|
|
|
|
|
+ code VARCHAR(10) NOT NULL,
|
|
|
|
|
+ sent_at BIGINT NOT NULL,
|
|
|
|
|
+ expires_at BIGINT NOT NULL,
|
|
|
|
|
+ used TINYINT NOT NULL DEFAULT 0,
|
|
|
|
|
+ KEY idx_email_code_email (email, sent_at)
|
|
|
|
|
+ ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4""",
|
|
|
|
|
+```
|
|
|
|
|
+
|
|
|
|
|
+- [ ] **Step 3: init_db() 加存量库迁移(幂等,照抄 ai_quota 的写法,插在 ai_quota 迁移块之后)**
|
|
|
|
|
+
|
|
|
|
|
+```python
|
|
|
|
|
+ # 迁移:users 增加 email(邮箱账号体系;旧手机号账号为 NULL,登录后强制补绑)
|
|
|
|
|
+ cur.execute(
|
|
|
|
|
+ "SELECT COUNT(*) AS c FROM information_schema.COLUMNS"
|
|
|
|
|
+ " WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'users' AND COLUMN_NAME = 'email'"
|
|
|
|
|
+ )
|
|
|
|
|
+ if cur.fetchone()["c"] == 0:
|
|
|
|
|
+ cur.execute("ALTER TABLE users ADD COLUMN email VARCHAR(120) NULL UNIQUE")
|
|
|
|
|
+```
|
|
|
|
|
+
|
|
|
|
|
+- [ ] **Step 4: user_row_to_dict 增加三字段**
|
|
|
|
|
+
|
|
|
|
|
+```python
|
|
|
|
|
+ "email": r.get("email"),
|
|
|
|
|
+ "hasPassword": bool(r.get("password_hash")),
|
|
|
|
|
+ "needsBindEmail": r["role"] == "user" and not r.get("email"),
|
|
|
|
|
+```
|
|
|
|
|
+
|
|
|
|
|
+注意:现有 SELECT 均为 `SELECT * FROM users`,password_hash 会在行里,仅用于推导不外传(字典里不要输出 password_hash 本身)。
|
|
|
|
|
+
|
|
|
|
|
+- [ ] **Step 5: auth.py `_user_dict` 同步增加三字段**
|
|
|
|
|
+
|
|
|
|
|
+```python
|
|
|
|
|
+def _user_dict(row) -> dict:
|
|
|
|
|
+ return {
|
|
|
|
|
+ "id": row["id"],
|
|
|
|
|
+ "phone": row["phone"],
|
|
|
|
|
+ "email": row.get("email"),
|
|
|
|
|
+ "username": row["username"],
|
|
|
|
|
+ "name": row["name"],
|
|
|
|
|
+ "role": row["role"],
|
|
|
|
|
+ "status": row["status"],
|
|
|
|
|
+ "createdAt": row["created_at"],
|
|
|
|
|
+ "hasPassword": bool(row.get("password_hash")),
|
|
|
|
|
+ "needsBindEmail": row["role"] == "user" and not row.get("email"),
|
|
|
|
|
+ }
|
|
|
|
|
+```
|
|
|
|
|
+
|
|
|
|
|
+- [ ] **Step 6: 重启 uvicorn 验证迁移生效**
|
|
|
|
|
+
|
|
|
|
|
+Run(kill 旧进程后): `cd server && .venv/bin/uvicorn main:app --port 8080 &`,再:
|
|
|
|
|
+
|
|
|
|
|
+```bash
|
|
|
|
|
+docker exec pl-mysql mysql -uroot -ppouchlab pouchlab -e "SHOW COLUMNS FROM users LIKE 'email'; SHOW TABLES LIKE 'email_codes';"
|
|
|
|
|
+```
|
|
|
|
|
+
|
|
|
|
|
+Expected: 两行都返回结果(列 VARCHAR(120)、表存在)。
|
|
|
|
|
+
|
|
|
|
|
+- [ ] **Step 7: e2e 基线仍绿**
|
|
|
|
|
+
|
|
|
|
|
+Run: `cd server && python3 e2e_test.py` Expected: 通过(本步不应改变现有行为——`needsBindEmail` 此时还没有任何消费方)。
|
|
|
|
|
+
|
|
|
|
|
+- [ ] **Step 8: Commit**
|
|
|
|
|
+
|
|
|
|
|
+```bash
|
|
|
|
|
+git add server/db.py server/auth.py
|
|
|
|
|
+git commit -m "db: 用户表增加 email 列与 email_codes 验证码表(幂等迁移)"
|
|
|
|
|
+```
|
|
|
|
|
+
|
|
|
|
|
+---
|
|
|
|
|
+
|
|
|
|
|
+## Task 3: auth.py 邮箱验证码 + 强制绑定拦截
|
|
|
|
|
+
|
|
|
|
|
+**Files:**
|
|
|
|
|
+- Modify: `server/auth.py`(新增邮箱函数;`require_user` 改造)
|
|
|
|
|
+- Test: `server/e2e_test.py`(Task 6 统一补断言;本任务先做函数级快速验证)
|
|
|
|
|
+
|
|
|
|
|
+- [ ] **Step 1: auth.py 顶部加 `import re` 与邮箱工具(放"短信验证码"段之后,新增"邮箱验证码"段)**
|
|
|
|
|
+
|
|
|
|
|
+```python
|
|
|
|
|
+# ---------- 邮箱 ----------
|
|
|
|
|
+
|
|
|
|
|
+EMAIL_RE = re.compile(r"^[^\s@]+@[^\s@]+\.[^\s@]+$")
|
|
|
|
|
+EMAIL_DEMO = DEMO_MODE # SMTP 未配置时同样降级为演示模式(见 issue_email_code)
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+def normalize_email(email: str) -> str:
|
|
|
|
|
+ e = str(email or "").strip().lower()
|
|
|
|
|
+ if len(e) > 120 or not EMAIL_RE.match(e):
|
|
|
|
|
+ raise HTTPException(status_code=400, detail="请输入正确的邮箱地址")
|
|
|
|
|
+ return e
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+def issue_email_code(email: str) -> dict:
|
|
|
|
|
+ """发邮箱验证码。演示/未配置 SMTP 时验证码随响应返回。"""
|
|
|
|
|
+ import email_service
|
|
|
|
|
+
|
|
|
|
|
+ now = int(time.time())
|
|
|
|
|
+ with db() as cur:
|
|
|
|
|
+ cur.execute(
|
|
|
|
|
+ "SELECT sent_at FROM email_codes WHERE email = %s ORDER BY id DESC LIMIT 1", (email,)
|
|
|
|
|
+ )
|
|
|
|
|
+ recent = cur.fetchone()
|
|
|
|
|
+ if recent and now - recent["sent_at"] < SMS_RESEND_INTERVAL:
|
|
|
|
|
+ raise HTTPException(status_code=429, detail="发送太频繁,请稍后再试")
|
|
|
|
|
+ code = "%06d" % secrets.randbelow(1000000)
|
|
|
|
|
+ cur.execute(
|
|
|
|
|
+ "INSERT INTO email_codes (email, code, sent_at, expires_at, used) VALUES (%s,%s,%s,%s,0)",
|
|
|
|
|
+ (email, code, now, now + SMS_TTL),
|
|
|
|
|
+ )
|
|
|
|
|
+ cur.execute("DELETE FROM email_codes WHERE expires_at < %s", (now - SMS_TTL,))
|
|
|
|
|
+ demo = DEMO_MODE or not email_service.smtp_configured()
|
|
|
|
|
+ result = {"ok": True, "demo": demo}
|
|
|
|
|
+ if demo:
|
|
|
|
|
+ result["code"] = code
|
|
|
|
|
+ return result
|
|
|
|
|
+ status, err = email_service.send_email(
|
|
|
|
|
+ email, "【袋研社 POUCHLAB】登录验证码",
|
|
|
|
|
+ "你的登录验证码:%s(10 分钟内有效)。如非本人操作请忽略。" % code,
|
|
|
|
|
+ )
|
|
|
|
|
+ if status != "sent":
|
|
|
|
|
+ raise HTTPException(status_code=500, detail="邮件发送失败,请稍后再试")
|
|
|
|
|
+ return result
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+def check_email_code(email: str, code: str) -> bool:
|
|
|
|
|
+ now = int(time.time())
|
|
|
|
|
+ with db() as cur:
|
|
|
|
|
+ cur.execute(
|
|
|
|
|
+ "SELECT id FROM email_codes WHERE email = %s AND code = %s AND used = 0 AND expires_at > %s"
|
|
|
|
|
+ " ORDER BY id DESC LIMIT 1",
|
|
|
|
|
+ (email, code, now),
|
|
|
|
|
+ )
|
|
|
|
|
+ row = cur.fetchone()
|
|
|
|
|
+ if not row:
|
|
|
|
|
+ return False
|
|
|
|
|
+ cur.execute("UPDATE email_codes SET used = 1 WHERE id = %s", (row["id"],))
|
|
|
|
|
+ return True
|
|
|
|
|
+```
|
|
|
|
|
+
|
|
|
|
|
+(`SMS_TTL`/`SMS_RESEND_INTERVAL` 常量与短信共用,不再新定义。)
|
|
|
|
|
+
|
|
|
|
|
+- [ ] **Step 2: require_user 加强制绑定拦截(bind-email/set-password/me 走的是 `user_from_request`,不受影响)**
|
|
|
|
|
+
|
|
|
|
|
+把:
|
|
|
|
|
+
|
|
|
|
|
+```python
|
|
|
|
|
+def require_user(request: Request) -> dict:
|
|
|
|
|
+ return user_from_request(request)
|
|
|
|
|
+```
|
|
|
|
|
+
|
|
|
|
|
+改为:
|
|
|
|
|
+
|
|
|
|
|
+```python
|
|
|
|
|
+def require_user(request: Request) -> dict:
|
|
|
|
|
+ user = user_from_request(request)
|
|
|
|
|
+ if user["role"] == "user" and not user.get("email"):
|
|
|
|
|
+ raise HTTPException(
|
|
|
|
|
+ status_code=403,
|
|
|
|
|
+ detail={"code": "bind-email", "message": "请先绑定邮箱后继续使用"},
|
|
|
|
|
+ )
|
|
|
|
|
+ return user
|
|
|
|
|
+```
|
|
|
|
|
+
|
|
|
|
|
+- [ ] **Step 3: 快速函数级验证**
|
|
|
|
|
+
|
|
|
|
|
+Run: `cd server && kill %1; .venv/bin/uvicorn main:app --port 8080 & sleep 2; python3 - <<'PY'
|
|
|
|
|
+import json, urllib.request
|
|
|
|
|
+def post(path, body, token=None):
|
|
|
|
|
+ req = urllib.request.Request('http://127.0.0.1:8080/api'+path, method='POST')
|
|
|
|
|
+ req.add_header('Content-Type','application/json')
|
|
|
|
|
+ if token: req.add_header('Authorization','Bearer '+token)
|
|
|
|
|
+ return json.loads(urllib.request.urlopen(req, json.dumps(body).encode()).read())
|
|
|
|
|
+r = post('/auth/sms/send', {'phone':'13900000111'})
|
|
|
|
|
+login = post('/auth/sms/login', {'phone':'13900000111','code':r['code']})
|
|
|
|
|
+u = login['user']
|
|
|
|
|
+assert u.get('needsBindEmail') is True, u
|
|
|
|
|
+assert u.get('hasPassword') is False, u
|
|
|
|
|
+import urllib.error
|
|
|
|
|
+try:
|
|
|
|
|
+ post('/orders/mine/x', {}, login['token']) # 不存在但会先过鉴权
|
|
|
|
|
+ raise AssertionError('should 403')
|
|
|
|
|
+except urllib.error.HTTPError as e:
|
|
|
|
|
+ d = json.loads(e.read())
|
|
|
|
|
+ assert e.code == 403 and d['detail']['code'] == 'bind-email', d
|
|
|
|
|
+print('require_user 拦截 OK')
|
|
|
|
|
+PY`
|
|
|
|
|
+
|
|
|
|
|
+Expected: `require_user 拦截 OK`。
|
|
|
|
|
+说明:Redis 用户缓存 TTL 60s 且旧结构缺 `email` 键,`user.get("email")` 为 None 时行为与真缺邮箱一致(保守拦截),无脏数据风险。
|
|
|
|
|
+
|
|
|
|
|
+- [ ] **Step 4: Commit**
|
|
|
|
|
+
|
|
|
|
|
+```bash
|
|
|
|
|
+git add server/auth.py
|
|
|
|
|
+git commit -m "auth: 邮箱验证码通道与未绑邮箱强制拦截"
|
|
|
|
|
+```
|
|
|
|
|
+
|
|
|
|
|
+---
|
|
|
|
|
+
|
|
|
|
|
+## Task 4: routes_auth.py 五个新端点 + 服务端 i18n
|
|
|
|
|
+
|
|
|
|
|
+**Files:**
|
|
|
|
|
+- Modify: `server/routes_auth.py`
|
|
|
|
|
+- Modify: `server/i18n.py`
|
|
|
|
|
+
|
|
|
|
|
+- [ ] **Step 1: routes_auth.py 加 Pydantic body 模型(现有类之后)**
|
|
|
|
|
+
|
|
|
|
|
+```python
|
|
|
|
|
+class EmailSendBody(BaseModel):
|
|
|
|
|
+ email: str
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+class EmailLoginBody(BaseModel):
|
|
|
|
|
+ email: str
|
|
|
|
|
+ code: str
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+class EmailPasswordLoginBody(BaseModel):
|
|
|
|
|
+ email: str
|
|
|
|
|
+ password: str
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+class SetPasswordBody(BaseModel):
|
|
|
|
|
+ oldPassword: str = ""
|
|
|
|
|
+ newPassword: str
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+class BindEmailBody(BaseModel):
|
|
|
|
|
+ email: str
|
|
|
|
|
+ code: str
|
|
|
|
|
+```
|
|
|
|
|
+
|
|
|
|
|
+- [ ] **Step 2: 追加端点(文件末尾)。路由顺序无所谓,前缀都是 /api/auth**
|
|
|
|
|
+
|
|
|
|
|
+```python
|
|
|
|
|
+@router.post("/email/send")
|
|
|
|
|
+def email_send(body: EmailSendBody):
|
|
|
|
|
+ return auth.issue_email_code(auth.normalize_email(body.email))
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+@router.post("/email/login")
|
|
|
|
|
+def email_login(body: EmailLoginBody):
|
|
|
|
|
+ """邮箱验证码登录;账号不存在则自动注册(无密码,name=邮箱前缀)。"""
|
|
|
|
|
+ email = auth.normalize_email(body.email)
|
|
|
|
|
+ if not auth.check_email_code(email, body.code.strip()):
|
|
|
|
|
+ raise HTTPException(status_code=400, detail="验证码错误或已过期")
|
|
|
|
|
+ with db() as cur:
|
|
|
|
|
+ cur.execute("SELECT * FROM users WHERE email = %s", (email,))
|
|
|
|
|
+ row = cur.fetchone()
|
|
|
|
|
+ if not row:
|
|
|
|
|
+ cur.execute(
|
|
|
|
|
+ "INSERT INTO users (phone, username, name, role, status, password_hash, created_at, email)"
|
|
|
|
|
+ " VALUES (NULL, NULL, %s, 'user', 'active', NULL, %s, %s)",
|
|
|
|
|
+ (email.split("@", 1)[0][:100], int(time.time()), email),
|
|
|
|
|
+ )
|
|
|
|
|
+ cur.execute("SELECT * FROM users WHERE email = %s", (email,))
|
|
|
|
|
+ row = cur.fetchone()
|
|
|
|
|
+ if row["status"] != "active":
|
|
|
|
|
+ raise HTTPException(status_code=403, detail="账号已被禁用,请联系客服")
|
|
|
|
|
+ cache.delete(cache.USER_KEY % row["id"])
|
|
|
|
|
+ user = user_row_to_dict(row)
|
|
|
|
|
+ return {"token": auth.make_token(row["id"], row["role"]), "user": user}
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+@router.post("/email/password-login")
|
|
|
|
|
+def email_password_login(body: EmailPasswordLoginBody):
|
|
|
|
|
+ email = auth.normalize_email(body.email)
|
|
|
|
|
+ with db() as cur:
|
|
|
|
|
+ cur.execute("SELECT * FROM users WHERE email = %s AND role = 'user'", (email,))
|
|
|
|
|
+ row = cur.fetchone()
|
|
|
|
|
+ if row and not row["password_hash"]:
|
|
|
|
|
+ raise HTTPException(status_code=400, detail="该账号未设置密码,请使用验证码登录")
|
|
|
|
|
+ if not row or not auth.verify_password(body.password, row["password_hash"] or ""):
|
|
|
|
|
+ raise HTTPException(status_code=401, detail="邮箱或密码错误")
|
|
|
|
|
+ if row["status"] != "active":
|
|
|
|
|
+ raise HTTPException(status_code=403, detail="账号已被禁用,请联系客服")
|
|
|
|
|
+ return {"token": auth.make_token(row["id"], row["role"]), "user": user_row_to_dict(row)}
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+@router.post("/set-password")
|
|
|
|
|
+def set_password(request: Request, body: SetPasswordBody):
|
|
|
|
|
+ """设置/修改登录密码。验证码注册的账号首次设置免旧密码。"""
|
|
|
|
|
+ me = auth.user_from_request(request)
|
|
|
|
|
+ new = body.newPassword or ""
|
|
|
|
|
+ if len(new) < 8 or not re.search(r"[A-Za-z]", new) or not re.search(r"\d", new):
|
|
|
|
|
+ raise HTTPException(status_code=400, detail="密码需至少 8 位且包含字母和数字")
|
|
|
|
|
+ with db() as cur:
|
|
|
|
|
+ cur.execute("SELECT password_hash FROM users WHERE id = %s", (me["id"],))
|
|
|
|
|
+ row = cur.fetchone()
|
|
|
|
|
+ if not row:
|
|
|
|
|
+ raise HTTPException(status_code=401, detail="账号不存在")
|
|
|
|
|
+ if row["password_hash"] and not auth.verify_password(body.oldPassword or "", row["password_hash"]):
|
|
|
|
|
+ raise HTTPException(status_code=400, detail="旧密码不正确")
|
|
|
|
|
+ cur.execute(
|
|
|
|
|
+ "UPDATE users SET password_hash = %s WHERE id = %s",
|
|
|
|
|
+ (auth.hash_password(new), me["id"]),
|
|
|
|
|
+ )
|
|
|
|
|
+ cache.delete(cache.USER_KEY % me["id"])
|
|
|
|
|
+ return {"ok": True, "hasPassword": True}
|
|
|
|
|
+
|
|
|
|
|
+
|
|
|
|
|
+@router.post("/bind-email")
|
|
|
|
|
+def bind_email(request: Request, body: BindEmailBody):
|
|
|
|
|
+ """已登录用户绑定邮箱(legacy 手机号账号强制路径,也可主动使用)。"""
|
|
|
|
|
+ me = auth.user_from_request(request)
|
|
|
|
|
+ email = auth.normalize_email(body.email)
|
|
|
|
|
+ if not auth.check_email_code(email, body.code.strip()):
|
|
|
|
|
+ raise HTTPException(status_code=400, detail="验证码错误或已过期")
|
|
|
|
|
+ with db() as cur:
|
|
|
|
|
+ cur.execute("SELECT id FROM users WHERE email = %s AND id != %s", (email, me["id"]))
|
|
|
|
|
+ if cur.fetchone():
|
|
|
|
|
+ raise HTTPException(status_code=400, detail="该邮箱已被其他账号绑定")
|
|
|
|
|
+ cur.execute("UPDATE users SET email = %s WHERE id = %s", (email, me["id"]))
|
|
|
|
|
+ cur.execute("SELECT * FROM users WHERE id = %s", (me["id"],))
|
|
|
|
|
+ row = cur.fetchone()
|
|
|
|
|
+ cache.delete(cache.USER_KEY % me["id"])
|
|
|
|
|
+ return {"ok": True, "user": user_row_to_dict(row)}
|
|
|
|
|
+```
|
|
|
|
|
+
|
|
|
|
|
+文件头需要补 `import re` 与 `import cache`(现有 import 块:`import time` 下加 `import re`;`from db import db, user_row_to_dict` 上方加 `import cache`)。
|
|
|
|
|
+
|
|
|
|
|
+- [ ] **Step 3: i18n.py ERRORS_EN 增加新文案(保持字典字母序惯例,就近插入)**
|
|
|
|
|
+
|
|
|
|
|
+```python
|
|
|
|
|
+ "请输入正确的邮箱地址": "Enter a valid email address",
|
|
|
|
|
+ "邮件发送失败,请稍后再试": "Failed to send email — try again later",
|
|
|
|
|
+ "该邮箱已被其他账号绑定": "This email is already linked to another account",
|
|
|
|
|
+ "该账号未设置密码,请使用验证码登录": "No password set for this account — sign in with the code",
|
|
|
|
|
+ "邮箱或密码错误": "Wrong email or password",
|
|
|
|
|
+ "密码需至少 8 位且包含字母和数字": "Password must be at least 8 characters with letters and digits",
|
|
|
|
|
+ "旧密码不正确": "Current password is incorrect",
|
|
|
|
|
+ "请先绑定邮箱后继续使用": "Please bind your email to continue",
|
|
|
|
|
+```
|
|
|
|
|
+
|
|
|
|
|
+- [ ] **Step 4: i18n.py `translate_json_body` 支持 dict 型 detail(bind-email 403 的 detail 是对象)**
|
|
|
|
|
+
|
|
|
|
|
+把 `if isinstance(data, dict):` 块内循环之前加:
|
|
|
|
|
+
|
|
|
|
|
+```python
|
|
|
|
|
+ d = data.get("detail")
|
|
|
|
|
+ if isinstance(d, dict) and isinstance(d.get("message"), str):
|
|
|
|
|
+ t = translate_detail(d["message"])
|
|
|
|
|
+ if t != d["message"]:
|
|
|
|
|
+ d["message"] = t
|
|
|
|
|
+ changed = True
|
|
|
|
|
+```
|
|
|
|
|
+
|
|
|
|
|
+- [ ] **Step 5: 冒烟(重启后 curl)**
|
|
|
|
|
+
|
|
|
|
|
+```bash
|
|
|
|
|
+cd server && kill %1 2>/dev/null; .venv/bin/uvicorn main:app --port 8080 & sleep 2
|
|
|
|
|
+curl -s -X POST localhost:8080/api/auth/email/send -H 'content-type: application/json' -d '{"email":"Smoke.Test1@Example.com "}'
|
|
|
|
|
+```
|
|
|
|
|
+
|
|
|
|
|
+Expected: `{"ok":true,"demo":true,"code":"<6位>"}`(注意返回前已 trim+lower)。再跑 `python3 e2e_test.py` 应仍全绿(旧用例不受影响)。
|
|
|
|
|
+
|
|
|
|
|
+- [ ] **Step 6: Commit**
|
|
|
|
|
+
|
|
|
|
|
+```bash
|
|
|
|
|
+git add server/routes_auth.py server/i18n.py
|
|
|
|
|
+git commit -m "api: 邮箱登录/密码登录/设置密码/绑定邮箱端点与服务端翻译"
|
|
|
|
|
+```
|
|
|
|
|
+
|
|
|
|
|
+---
|
|
|
|
|
+
|
|
|
|
|
+## Task 5: 后台用户列表支持邮箱
|
|
|
|
|
+
|
|
|
|
|
+**Files:**
|
|
|
|
|
+- Modify: `server/routes_admin.py:206-211`
|
|
|
|
|
+- Modify: `assets/js/admin.js:694-696,743`
|
|
|
|
|
+
|
|
|
|
|
+- [ ] **Step 1: routes_admin.py 用户搜索条件加 email**
|
|
|
|
|
+
|
|
|
|
|
+把:
|
|
|
|
|
+
|
|
|
|
|
+```python
|
|
|
|
|
+ where = "WHERE role = 'user' AND (phone LIKE %s OR name LIKE %s)" if query.strip() else "WHERE role = 'user'"
|
|
|
|
|
+ args = ("%" + query.strip() + "%", "%" + query.strip() + "%") if query.strip() else ()
|
|
|
|
|
+```
|
|
|
|
|
+
|
|
|
|
|
+改为:
|
|
|
|
|
+
|
|
|
|
|
+```python
|
|
|
|
|
+ where = (
|
|
|
|
|
+ "WHERE role = 'user' AND (phone LIKE %s OR name LIKE %s OR email LIKE %s)"
|
|
|
|
|
+ if query.strip() else "WHERE role = 'user'"
|
|
|
|
|
+ )
|
|
|
|
|
+ args = ("%" + query.strip() + "%",) * 3 if query.strip() else ()
|
|
|
|
|
+```
|
|
|
|
|
+
|
|
|
|
|
+- [ ] **Step 2: admin.js 用户表加邮箱列、改列名与搜索占位**
|
|
|
|
|
+
|
|
|
|
|
+列定义(`userCols` 内,ID 列后)改为:
|
|
|
|
|
+
|
|
|
|
|
+```js
|
|
|
|
|
+ { title: '邮箱', dataIndex: 'email', width: 180, render: function (v) { return v || '—'; } },
|
|
|
|
|
+ { title: '手机号(旧)', dataIndex: 'phone', width: 120, render: function (v) { return v || '—'; } },
|
|
|
|
|
+```
|
|
|
|
|
+
|
|
|
|
|
+搜索框 placeholder:`'搜索手机号 / 昵称'` → `'搜索手机号 / 邮箱 / 昵称'`(admin.js:743)。
|
|
|
|
|
+
|
|
|
|
|
+- [ ] **Step 3: 浏览器验证**
|
|
|
|
|
+
|
|
|
|
|
+`http://127.0.0.1:8080/admin.html` 登录 admin/admin123 → 用户管理:新注册邮箱用户(Task 4 冒烟或 Task 6 e2e 造的)邮箱列有值;搜索其邮箱前缀能命中。
|
|
|
|
|
+
|
|
|
|
|
+- [ ] **Step 4: Commit**
|
|
|
|
|
+
|
|
|
|
|
+```bash
|
|
|
|
|
+git add server/routes_admin.py assets/js/admin.js
|
|
|
|
|
+git commit -m "admin: 用户列表展示与搜索支持邮箱"
|
|
|
|
|
+```
|
|
|
|
|
+
|
|
|
|
|
+---
|
|
|
|
|
+
|
|
|
|
|
+## Task 6: e2e 邮箱全流程断言(先红后绿)
|
|
|
|
|
+
|
|
|
|
|
+**Files:**
|
|
|
|
|
+- Modify: `server/e2e_test.py`("短信流程" 段之后、"纸盒订单" 之前插入;文件顶部已有 random/json/urllib)
|
|
|
|
|
+
|
|
|
|
|
+- [ ] **Step 1: 写失败测试——插入以下段落**
|
|
|
|
|
+
|
|
|
|
|
+```python
|
|
|
|
|
+# --- 邮箱流程 ---
|
|
|
|
|
+EMAIL = "e2e-%08d@pouchlab.test" % random.randint(0, 99999999)
|
|
|
|
|
+
|
|
|
|
|
+st, r = call("POST", "/api/auth/email/send", body={"email": " not-an-email "})
|
|
|
|
|
+check("非法邮箱拒绝", st == 400)
|
|
|
|
|
+
|
|
|
|
|
+st, r = call("POST", "/api/auth/email/send", body={"email": EMAIL})
|
|
|
|
|
+check("发送邮箱验证码(demo 返回 code)", st == 200 and r.get("demo") and r.get("code"))
|
|
|
|
|
+ecode = r["code"]
|
|
|
|
|
+
|
|
|
|
|
+st, r = call("POST", "/api/auth/email/send", body={"email": EMAIL})
|
|
|
|
|
+check("邮箱验证码 60 秒限流", st == 429)
|
|
|
|
|
+
|
|
|
|
|
+st, r = call("POST", "/api/auth/email/login", body={"email": EMAIL, "code": "000000"})
|
|
|
|
|
+check("邮箱错误验证码拒绝", st == 400)
|
|
|
|
|
+
|
|
|
|
|
+st, r = call("POST", "/api/auth/email/login", body={"email": EMAIL, "code": ecode})
|
|
|
|
|
+check("邮箱验证码登录(自动注册)", st == 200 and r.get("token")
|
|
|
|
|
+ and r["user"]["email"] == EMAIL and r["user"]["needsBindEmail"] is False)
|
|
|
|
|
+etok = r["token"]
|
|
|
|
|
+
|
|
|
|
|
+st, r = call("GET", "/api/orders/mine", token=etok)
|
|
|
|
|
+check("邮箱用户可直接下单查询", st == 200)
|
|
|
|
|
+
|
|
|
|
|
+st, r = call("POST", "/api/auth/email/password-login", body={"email": EMAIL, "password": "password123"})
|
|
|
|
|
+check("未设密码账号密码登录被拒", st == 400)
|
|
|
|
|
+
|
|
|
|
|
+st, r = call("POST", "/api/auth/set-password", token=etok, body={"newPassword": "short1"})
|
|
|
|
|
+check("弱密码拒绝", st == 400)
|
|
|
|
|
+
|
|
|
|
|
+st, r = call("POST", "/api/auth/set-password", token=etok, body={"newPassword": "password123"})
|
|
|
|
|
+check("首次设置密码(免旧密码)", st == 200)
|
|
|
|
|
+
|
|
|
|
|
+st, r = call("POST", "/api/auth/email/password-login", body={"email": EMAIL, "password": "password123"})
|
|
|
|
|
+check("密码登录成功", st == 200 and r.get("token"))
|
|
|
|
|
+
|
|
|
|
|
+st, r = call("POST", "/api/auth/set-password", token=etok, body={"newPassword": "password456"})
|
|
|
|
|
+check("再次设置需旧密码(缺旧密码被拒)", st == 400)
|
|
|
|
|
+
|
|
|
|
|
+st, r = call("POST", "/api/auth/set-password", token=etok,
|
|
|
|
|
+ body={"oldPassword": "password123", "newPassword": "password456"})
|
|
|
|
|
+check("旧密码正确可改密", st == 200)
|
|
|
|
|
+
|
|
|
|
|
+# --- legacy 手机号登录 → 强制绑定邮箱 ---
|
|
|
|
|
+PHONE2 = "139%08d" % random.randint(0, 99999999)
|
|
|
|
|
+st, r = call("POST", "/api/auth/sms/send", body={"phone": PHONE2})
|
|
|
|
|
+check("legacy 短信验证码(demo)", st == 200 and r.get("code"))
|
|
|
|
|
+pcode = r["code"]
|
|
|
|
|
+
|
|
|
|
|
+st, r = call("POST", "/api/auth/sms/login", body={"phone": PHONE2, "code": pcode})
|
|
|
|
|
+check("legacy 手机号登录返回 needsBindEmail", st == 200 and r["user"]["needsBindEmail"] is True)
|
|
|
|
|
+ptok = r["token"]
|
|
|
|
|
+
|
|
|
|
|
+st, r = call("GET", "/api/orders/mine", token=ptok)
|
|
|
|
|
+check("未绑邮箱业务接口 403 bind-email",
|
|
|
|
|
+ st == 403 and isinstance(r.get("detail"), dict) and r["detail"].get("code") == "bind-email")
|
|
|
|
|
+
|
|
|
|
|
+st, r = call("POST", "/api/auth/email/send", body={"email": EMAIL})
|
|
|
|
|
+check("绑定用邮箱验证码(换邮箱地址)", st == 200 and r.get("code"))
|
|
|
|
|
+bcode = r["code"]
|
|
|
|
|
+
|
|
|
|
|
+st, r = call("POST", "/api/auth/bind-email", token=ptok, body={"email": EMAIL, "code": bcode})
|
|
|
|
|
+check("绑定已被占用邮箱被拒", st == 400)
|
|
|
|
|
+
|
|
|
|
|
+EMAIL2 = "e2e-%08d@pouchlab.test" % random.randint(0, 99999999)
|
|
|
|
|
+st, r = call("POST", "/api/auth/email/send", body={"email": EMAIL2})
|
|
|
|
|
+bcode2 = r["code"]
|
|
|
|
|
+st, r = call("POST", "/api/auth/bind-email", token=ptok, body={"email": EMAIL2, "code": bcode2})
|
|
|
|
|
+check("绑定新邮箱成功", st == 200 and r["user"]["email"] == EMAIL2
|
|
|
|
|
+ and r["user"]["needsBindEmail"] is False)
|
|
|
|
|
+
|
|
|
|
|
+st, r = call("GET", "/api/orders/mine", token=ptok)
|
|
|
|
|
+check("绑定后业务接口放行", st == 200)
|
|
|
|
|
+```
|
|
|
|
|
+
|
|
|
|
|
+逐条对照实现要点:`call()` 已存在(返回 (status, json));403 的 detail 是 dict,`check` 断言其 `code`;验证码 60s 限流用同一邮箱顺序触发,占用邮箱用第一个已注册 EMAIL。
|
|
|
|
|
+
|
|
|
|
|
+- [ ] **Step 2: 重启 uvicorn 跑 e2e,确认新段全过**
|
|
|
|
|
+
|
|
|
|
|
+Run: `cd server && python3 e2e_test.py`
|
|
|
|
|
+Expected: 通过。若 Task 2-4 已做完,本段应直接绿;若红,按断言逐条排查实现,不降低断言。
|
|
|
|
|
+
|
|
|
|
|
+- [ ] **Step 3: EN 头验证 dict detail 翻译**
|
|
|
|
|
+
|
|
|
|
|
+```bash
|
|
|
|
|
+curl -s -X POST localhost:8080/api/auth/email/send -H 'content-type: application/json' -H 'Accept-Language: en' -d '{"email":"bad-email"}'
|
|
|
|
|
+```
|
|
|
|
|
+
|
|
|
|
|
+Expected: `{"detail":"Enter a valid email address"}`。
|
|
|
|
|
+
|
|
|
|
|
+- [ ] **Step 4: Commit**
|
|
|
|
|
+
|
|
|
|
|
+```bash
|
|
|
|
|
+git add server/e2e_test.py
|
|
|
|
|
+git commit -m "test: 邮箱登录/密码/强制绑定全流程 e2e 断言"
|
|
|
|
|
+```
|
|
|
|
|
+
|
|
|
|
|
+---
|
|
|
|
|
+
|
|
|
|
|
+## Task 7: api.js bind-email 拦截与重放
|
|
|
|
|
+
|
|
|
|
|
+**Files:**
|
|
|
|
|
+- Modify: `assets/js/api.js:24-63`
|
|
|
|
|
+
|
|
|
|
|
+- [ ] **Step 1: IIFE 顶部(TOKEN_KEY 旁)加等待队列**
|
|
|
|
|
+
|
|
|
|
|
+```js
|
|
|
|
|
+ const bindWaiters = [];
|
|
|
|
|
+```
|
|
|
|
|
+
|
|
|
|
|
+- [ ] **Step 2: `request()` 的 `!res.ok` 分支前拦截 403 bind-email,挂起并广播**
|
|
|
|
|
+
|
|
|
|
|
+把:
|
|
|
|
|
+
|
|
|
|
|
+```js
|
|
|
|
|
+ if (!res.ok) {
|
|
|
|
|
+ const err = new Error(data.detail || tr('请求失败(' + res.status + ')'));
|
|
|
|
|
+ err.status = res.status;
|
|
|
|
|
+ throw err;
|
|
|
|
|
+ }
|
|
|
|
|
+```
|
|
|
|
|
+
|
|
|
|
|
+改为:
|
|
|
|
|
+
|
|
|
|
|
+```js
|
|
|
|
|
+ if (res.status === 403 && data.detail && data.detail.code === 'bind-email') {
|
|
|
|
|
+ return new Promise(function (resolve, reject) {
|
|
|
|
|
+ bindWaiters.push(function () { request(method, path, body, opts).then(resolve, reject); });
|
|
|
|
|
+ document.dispatchEvent(new CustomEvent('pl:bind-email-required',
|
|
|
|
|
+ { detail: { message: data.detail.message } }));
|
|
|
|
|
+ });
|
|
|
|
|
+ }
|
|
|
|
|
+ if (!res.ok) {
|
|
|
|
|
+ const msg = data.detail && data.detail.message ? data.detail.message : data.detail;
|
|
|
|
|
+ const err = new Error(msg || tr('请求失败(' + res.status + ')'));
|
|
|
|
|
+ err.status = res.status;
|
|
|
|
|
+ throw err;
|
|
|
|
|
+ }
|
|
|
|
|
+```
|
|
|
|
|
+
|
|
|
|
|
+- [ ] **Step 3: 暴露 flush 接口**
|
|
|
|
|
+
|
|
|
|
|
+`window.PL.api = {` 对象里追加:
|
|
|
|
|
+
|
|
|
|
|
+```js
|
|
|
|
|
+ flushBind: function () {
|
|
|
|
|
+ const list = bindWaiters.splice(0);
|
|
|
|
|
+ list.forEach(function (run) { try { run(); } catch (e) {} });
|
|
|
|
|
+ }
|
|
|
|
|
+```
|
|
|
|
|
+
|
|
|
|
|
+- [ ] **Step 4: Commit**
|
|
|
|
|
+
|
|
|
|
|
+```bash
|
|
|
|
|
+git add assets/js/api.js
|
|
|
|
|
+git commit -m "api: 403 bind-email 挂起原请求并在绑定成功后自动重放"
|
|
|
|
|
+```
|
|
|
|
|
+
|
|
|
|
|
+---
|
|
|
|
|
+
|
|
|
|
|
+## Task 8: auth.js 重写(邮箱优先三通道 + 强制绑定 + 账户设置)
|
|
|
|
|
+
|
|
|
|
|
+**Files:**
|
|
|
|
|
+- Rewrite: `assets/js/auth.js`(整文件替换,公开接口 `PL.auth` 不变)
|
|
|
|
|
+
|
|
|
|
|
+- [ ] **Step 1: 整文件替换为以下内容**
|
|
|
|
|
+
|
|
|
|
|
+要点:邮箱登录为默认 tab;密码 tab 常显(未设密码由后端报错引导);"手机号(旧)"走原短信通道;登录响应 `needsBindEmail=true` 立即弹不可关闭绑定框;`pl:bind-email-required` 事件(api.js 触发)同样弹框;绑定成功后 `PL.api.flushBind()` 重放被 403 挂起的请求;菜单加"账户设置"(邮箱状态、设/改密)。
|
|
|
|
|
+
|
|
|
|
|
+```js
|
|
|
|
|
+(function () {
|
|
|
|
|
+ const KEY = 'pouchlab.user.v1';
|
|
|
|
|
+ let user = null;
|
|
|
|
|
+ let pending = null;
|
|
|
|
|
+ let mode = 'email'; // email | password | phone
|
|
|
|
|
+ let countdown = 0;
|
|
|
|
|
+ let countdownTimer = null;
|
|
|
|
|
+ const listeners = [];
|
|
|
|
|
+
|
|
|
|
|
+ try {
|
|
|
|
|
+ user = JSON.parse(localStorage.getItem(KEY) || 'null');
|
|
|
|
|
+ if (user && !user.phone && !user.email) user = null;
|
|
|
|
|
+ } catch (e) {
|
|
|
|
|
+ user = null;
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ function emit() {
|
|
|
|
|
+ listeners.forEach(function (fn) {
|
|
|
|
|
+ try { fn(user); } catch (e) {}
|
|
|
|
|
+ });
|
|
|
|
|
+ document.dispatchEvent(new CustomEvent('pl:auth', { detail: { user: user } }));
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ function notify(msg, kind) {
|
|
|
|
|
+ if (window.PL && PL.ui && PL.ui.message) {
|
|
|
|
|
+ if (kind === 'warn') PL.ui.message.warning(msg);
|
|
|
|
|
+ else PL.ui.message.success(msg);
|
|
|
|
|
+ return;
|
|
|
|
|
+ }
|
|
|
|
|
+ window.alert(msg);
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ function maskPhone(phone) {
|
|
|
|
|
+ const p = String(phone || '');
|
|
|
|
|
+ if (p.length !== 11) return p;
|
|
|
|
|
+ return p.slice(0, 3) + '****' + p.slice(7);
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ function validEmail(v) { return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(v); }
|
|
|
|
|
+
|
|
|
|
|
+ const STYLE = '<style>' +
|
|
|
|
|
+ '.pl-auth-tabs{display:flex;gap:6px;margin:0 0 14px}' +
|
|
|
|
|
+ '.pl-auth-tabs button{flex:1;padding:8px 4px;font-size:13px;border:1px solid #d8cfc0;border-radius:8px;background:#fff;color:#7d7466;cursor:pointer}' +
|
|
|
|
|
+ '.pl-auth-tabs button.on{border-color:#b08d57;color:#5a4a2f;background:#f7efdf;font-weight:600}' +
|
|
|
|
|
+ '.pl-auth-menu button{display:block;width:100%;margin-top:6px}' +
|
|
|
|
|
+ '</style>';
|
|
|
|
|
+
|
|
|
|
|
+ function ensureModal() {
|
|
|
|
|
+ if (document.getElementById('plAuthModal')) return;
|
|
|
|
|
+ const wrap = document.createElement('div');
|
|
|
|
|
+ wrap.id = 'plAuthModal';
|
|
|
|
|
+ wrap.className = 'pl-auth-mask';
|
|
|
|
|
+ wrap.hidden = true;
|
|
|
|
|
+ wrap.innerHTML = STYLE +
|
|
|
|
|
+ '<div class="pl-auth-card" role="dialog" aria-modal="true" aria-labelledby="plAuthTitle">' +
|
|
|
|
|
+ '<button class="pl-auth-close" type="button" aria-label="关闭">✕</button>' +
|
|
|
|
|
+ '<div class="pl-auth-brand">袋研社 <em>POUCHLAB</em></div>' +
|
|
|
|
|
+ '<h2 id="plAuthTitle">登录 / 注册</h2>' +
|
|
|
|
|
+ '<p class="pl-auth-sub">登录后可保存设计、同步订单进度与下载记录。</p>' +
|
|
|
|
|
+ '<div class="pl-auth-tabs">' +
|
|
|
|
|
+ '<button type="button" data-mode="email" class="on">邮箱登录</button>' +
|
|
|
|
|
+ '<button type="button" data-mode="password">密码登录</button>' +
|
|
|
|
|
+ '<button type="button" data-mode="phone">手机号(旧)</button>' +
|
|
|
|
|
+ '</div>' +
|
|
|
|
|
+ // —— 邮箱验证码 ——
|
|
|
|
|
+ '<div id="plSecEmail">' +
|
|
|
|
|
+ '<label class="pl-auth-label" for="plAuthEmail">邮箱</label>' +
|
|
|
|
|
+ '<input id="plAuthEmail" class="pl-auth-input" type="email" maxlength="120" autocomplete="email" placeholder="name@example.com">' +
|
|
|
|
|
+ '<label class="pl-auth-label" for="plAuthCode">验证码</label>' +
|
|
|
|
|
+ '<div class="pl-auth-code-row">' +
|
|
|
|
|
+ '<input id="plAuthCode" class="pl-auth-input" type="text" inputmode="numeric" maxlength="6" autocomplete="one-time-code" placeholder="6 位验证码">' +
|
|
|
|
|
+ '<button id="plAuthSend" class="pl-auth-send" type="button">获取验证码</button>' +
|
|
|
|
|
+ '</div>' +
|
|
|
|
|
+ '</div>' +
|
|
|
|
|
+ // —— 邮箱密码 ——
|
|
|
|
|
+ '<div id="plSecPwd" hidden>' +
|
|
|
|
|
+ '<label class="pl-auth-label" for="plPwdEmail">邮箱</label>' +
|
|
|
|
|
+ '<input id="plPwdEmail" class="pl-auth-input" type="email" maxlength="120" autocomplete="email" placeholder="name@example.com">' +
|
|
|
|
|
+ '<label class="pl-auth-label" for="plPwdPass">密码</label>' +
|
|
|
|
|
+ '<input id="plPwdPass" class="pl-auth-input" type="password" maxlength="64" autocomplete="current-password" placeholder="登录密码">' +
|
|
|
|
|
+ '</div>' +
|
|
|
|
|
+ // —— legacy 手机号 ——
|
|
|
|
|
+ '<div id="plSecPhone" hidden>' +
|
|
|
|
|
+ '<label class="pl-auth-label" for="plAuthPhone">手机号</label>' +
|
|
|
|
|
+ '<input id="plAuthPhone" class="pl-auth-input" type="tel" inputmode="numeric" maxlength="11" autocomplete="tel" placeholder="请输入 11 位手机号">' +
|
|
|
|
|
+ '<label class="pl-auth-label" for="plPhoneCode">验证码</label>' +
|
|
|
|
|
+ '<div class="pl-auth-code-row">' +
|
|
|
|
|
+ '<input id="plPhoneCode" class="pl-auth-input" type="text" inputmode="numeric" maxlength="6" autocomplete="one-time-code" placeholder="6 位验证码">' +
|
|
|
|
|
+ '<button id="plPhoneSend" class="pl-auth-send" type="button">获取验证码</button>' +
|
|
|
|
|
+ '</div>' +
|
|
|
|
|
+ '</div>' +
|
|
|
|
|
+ '<p class="pl-auth-hint" id="plAuthHint">输入邮箱获取验证码登录;演示环境验证码会直接弹出显示。</p>' +
|
|
|
|
|
+ '<p class="pl-auth-error" id="plAuthError" hidden></p>' +
|
|
|
|
|
+ '<button id="plAuthSubmit" class="pl-auth-submit" type="button">登录</button>' +
|
|
|
|
|
+ '<p class="pl-auth-terms">登录即表示同意《服务条款》与《隐私政策》</p>' +
|
|
|
|
|
+ '</div>';
|
|
|
|
|
+ document.body.appendChild(wrap);
|
|
|
|
|
+
|
|
|
|
|
+ wrap.querySelector('.pl-auth-close').addEventListener('click', close);
|
|
|
|
|
+ wrap.addEventListener('click', function (e) {
|
|
|
|
|
+ if (e.target === wrap) close();
|
|
|
|
|
+ });
|
|
|
|
|
+ wrap.querySelectorAll('.pl-auth-tabs button').forEach(function (b) {
|
|
|
|
|
+ b.addEventListener('click', function () { setMode(b.dataset.mode); });
|
|
|
|
|
+ });
|
|
|
|
|
+ wrap.querySelector('#plAuthSend').addEventListener('click', function () { sendCode('email'); });
|
|
|
|
|
+ wrap.querySelector('#plPhoneSend').addEventListener('click', function () { sendCode('phone'); });
|
|
|
|
|
+ wrap.querySelector('#plAuthSubmit').addEventListener('click', submit);
|
|
|
|
|
+ wrap.querySelector('#plAuthPhone').addEventListener('input', function () {
|
|
|
|
|
+ this.value = this.value.replace(/\D/g, '').slice(0, 11); hideError();
|
|
|
|
|
+ });
|
|
|
|
|
+ [['#plAuthCode', '#plAuthEmail'], ['#plPhoneCode', '#plAuthPhone'], ['#plPwdPass', '#plPwdEmail']]
|
|
|
|
|
+ .forEach(function (pair) {
|
|
|
|
|
+ wrap.querySelector(pair[0]).addEventListener('keydown', function (e) {
|
|
|
|
|
+ if (e.key === 'Enter') { e.preventDefault(); submit(); }
|
|
|
|
|
+ });
|
|
|
|
|
+ wrap.querySelector(pair[1]).addEventListener('input', hideError);
|
|
|
|
|
+ });
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ function setMode(m) {
|
|
|
|
|
+ mode = m;
|
|
|
|
|
+ const modal = document.getElementById('plAuthModal');
|
|
|
|
|
+ modal.querySelectorAll('.pl-auth-tabs button').forEach(function (b) {
|
|
|
|
|
+ b.classList.toggle('on', b.dataset.mode === m);
|
|
|
|
|
+ });
|
|
|
|
|
+ document.getElementById('plSecEmail').hidden = m !== 'email';
|
|
|
|
|
+ document.getElementById('plSecPwd').hidden = m !== 'password';
|
|
|
|
|
+ document.getElementById('plSecPhone').hidden = m !== 'phone';
|
|
|
|
|
+ document.getElementById('plAuthHint').textContent =
|
|
|
|
|
+ m === 'phone' ? '老手机号验证码登录;登录后需绑定邮箱。' :
|
|
|
|
|
+ m === 'password' ? '未设置密码的账号请用邮箱验证码登录。' :
|
|
|
|
|
+ '输入邮箱获取验证码登录;演示环境验证码会直接弹出显示。';
|
|
|
|
|
+ hideError();
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ function showError(msg) {
|
|
|
|
|
+ const el = document.getElementById('plAuthError');
|
|
|
|
|
+ if (!el) return;
|
|
|
|
|
+ el.textContent = msg; el.hidden = false;
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ function hideError() {
|
|
|
|
|
+ const el = document.getElementById('plAuthError');
|
|
|
|
|
+ if (el) el.hidden = true;
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ function open() {
|
|
|
|
|
+ ensureModal();
|
|
|
|
|
+ const modal = document.getElementById('plAuthModal');
|
|
|
|
|
+ const email = document.getElementById('plAuthEmail');
|
|
|
|
|
+ email.value = user && user.email ? user.email : '';
|
|
|
|
|
+ document.getElementById('plAuthCode').value = '';
|
|
|
|
|
+ setMode(user && user.phone && !user.email ? 'phone' : 'email');
|
|
|
|
|
+ modal.hidden = false;
|
|
|
|
|
+ document.body.classList.add('pl-auth-open');
|
|
|
|
|
+ setTimeout(function () { (user && user.email ? document.getElementById('plAuthCode') : email).focus(); }, 30);
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ function close() {
|
|
|
|
|
+ const modal = document.getElementById('plAuthModal');
|
|
|
|
|
+ if (modal) modal.hidden = true;
|
|
|
|
|
+ document.body.classList.remove('pl-auth-open');
|
|
|
|
|
+ pending = null;
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ function fillDemoCode(r, inputSel, msgPrefix) {
|
|
|
|
|
+ if (r && r.demo && r.code) {
|
|
|
|
|
+ notify(msgPrefix + r.code + '(已自动填入)');
|
|
|
|
|
+ const input = document.querySelector(inputSel);
|
|
|
|
|
+ if (input) { input.value = r.code; input.focus(); }
|
|
|
|
|
+ } else {
|
|
|
|
|
+ notify('验证码已发送,请查收邮件/短信');
|
|
|
|
|
+ }
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ function sendCode(m) {
|
|
|
|
|
+ const btn = m === 'phone' ? document.getElementById('plPhoneSend') : document.getElementById('plAuthSend');
|
|
|
|
|
+ if (btn.disabled) return;
|
|
|
|
|
+ if (!window.PL || !PL.api) { notify('离线演示验证码:123456'); return; }
|
|
|
|
|
+ let req, sel;
|
|
|
|
|
+ if (m === 'phone') {
|
|
|
|
|
+ const phone = document.getElementById('plAuthPhone').value.trim();
|
|
|
|
|
+ if (!/^1\d{10}$/.test(phone)) { showError('请输入 11 位手机号'); return; }
|
|
|
|
|
+ req = PL.api.post('/auth/sms/send', { phone: phone }, { timeout: 10000 });
|
|
|
|
|
+ sel = '#plPhoneCode';
|
|
|
|
|
+ } else {
|
|
|
|
|
+ const email = document.getElementById('plAuthEmail').value.trim();
|
|
|
|
|
+ if (!validEmail(email)) { showError('请输入正确的邮箱地址'); return; }
|
|
|
|
|
+ req = PL.api.post('/auth/email/send', { email: email }, { timeout: 15000 });
|
|
|
|
|
+ sel = '#plAuthCode';
|
|
|
|
|
+ }
|
|
|
|
|
+ hideError();
|
|
|
|
|
+ btn.disabled = true; btn.textContent = '发送中…';
|
|
|
|
|
+ req.then(function (r) {
|
|
|
|
|
+ fillDemoCode(r, sel, '演示验证码:');
|
|
|
|
|
+ startCountdown(btn);
|
|
|
|
|
+ }, function (err) {
|
|
|
|
|
+ btn.disabled = false; btn.textContent = '获取验证码';
|
|
|
|
|
+ if (err.network) {
|
|
|
|
|
+ notify('服务器暂不可达,离线演示验证码:123456', 'warn');
|
|
|
|
|
+ startCountdown(btn);
|
|
|
|
|
+ } else {
|
|
|
|
|
+ showError(err.message || '发送失败,请稍后再试');
|
|
|
|
|
+ }
|
|
|
|
|
+ });
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ function startCountdown(btn) {
|
|
|
|
|
+ countdown = 60;
|
|
|
|
|
+ btn.disabled = true;
|
|
|
|
|
+ btn.textContent = countdown + 's 后重发';
|
|
|
|
|
+ clearInterval(countdownTimer);
|
|
|
|
|
+ countdownTimer = setInterval(function () {
|
|
|
|
|
+ countdown -= 1;
|
|
|
|
|
+ if (countdown <= 0) {
|
|
|
|
|
+ clearInterval(countdownTimer);
|
|
|
|
|
+ btn.disabled = false; btn.textContent = '获取验证码';
|
|
|
|
|
+ return;
|
|
|
|
|
+ }
|
|
|
|
|
+ btn.textContent = countdown + 's 后重发';
|
|
|
|
|
+ }, 1000);
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ function persist(u) {
|
|
|
|
|
+ user = u;
|
|
|
|
|
+ try { localStorage.setItem(KEY, JSON.stringify(user)); } catch (e) {}
|
|
|
|
|
+ emit();
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ function applyLogin(u) {
|
|
|
|
|
+ persist({
|
|
|
|
|
+ id: u.id, phone: u.phone || '', email: u.email || '', name: u.name || '',
|
|
|
|
|
+ role: u.role || 'user', hasPassword: !!u.hasPassword,
|
|
|
|
|
+ needsBindEmail: !!u.needsBindEmail, at: Date.now()
|
|
|
|
|
+ });
|
|
|
|
|
+ if (u.needsBindEmail) {
|
|
|
|
|
+ close();
|
|
|
|
|
+ openBind();
|
|
|
|
|
+ return;
|
|
|
|
|
+ }
|
|
|
|
|
+ const cb = pending; pending = null;
|
|
|
|
|
+ close();
|
|
|
|
|
+ notify('登录成功');
|
|
|
|
|
+ if (cb) setTimeout(cb, 60);
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ function submit() {
|
|
|
|
|
+ if (!window.PL || !PL.api) return;
|
|
|
|
|
+ let req;
|
|
|
|
|
+ if (mode === 'password') {
|
|
|
|
|
+ const email = document.getElementById('plPwdEmail').value.trim();
|
|
|
|
|
+ const pass = document.getElementById('plPwdPass').value;
|
|
|
|
|
+ if (!validEmail(email)) { showError('请输入正确的邮箱地址'); return; }
|
|
|
|
|
+ if (!pass) { showError('请输入密码'); return; }
|
|
|
|
|
+ req = PL.api.post('/auth/email/password-login', { email: email, password: pass }, { timeout: 10000 });
|
|
|
|
|
+ } else if (mode === 'phone') {
|
|
|
|
|
+ const phone = document.getElementById('plAuthPhone').value.trim();
|
|
|
|
|
+ const code = document.getElementById('plPhoneCode').value.trim();
|
|
|
|
|
+ if (!/^1\d{10}$/.test(phone)) { showError('请输入 11 位手机号'); return; }
|
|
|
|
|
+ if (!/^\d{6}$/.test(code)) { showError('请输入 6 位验证码'); return; }
|
|
|
|
|
+ req = PL.api.post('/auth/sms/login', { phone: phone, code: code }, { timeout: 10000 })
|
|
|
|
|
+ .catch(function (err) {
|
|
|
|
|
+ if (err.network) { // 保留旧的离线演示登录
|
|
|
|
|
+ applyLogin({ id: 0, phone: phone, name: '用户' + phone.slice(-4), role: 'user', needsBindEmail: false });
|
|
|
|
|
+ notify('离线演示模式登录(数据不会上传)', 'warn');
|
|
|
|
|
+ return new Promise(function () {});
|
|
|
|
|
+ }
|
|
|
|
|
+ throw err;
|
|
|
|
|
+ });
|
|
|
|
|
+ } else {
|
|
|
|
|
+ const email = document.getElementById('plAuthEmail').value.trim();
|
|
|
|
|
+ const code = document.getElementById('plAuthCode').value.trim();
|
|
|
|
|
+ if (!validEmail(email)) { showError('请输入正确的邮箱地址'); return; }
|
|
|
|
|
+ if (!/^\d{6}$/.test(code)) { showError('请输入 6 位验证码'); return; }
|
|
|
|
|
+ req = PL.api.post('/auth/email/login', { email: email, code: code }, { timeout: 10000 });
|
|
|
|
|
+ }
|
|
|
|
|
+ const btn = document.getElementById('plAuthSubmit');
|
|
|
|
|
+ btn.disabled = true; btn.textContent = '登录中…';
|
|
|
|
|
+ req.then(function (r) {
|
|
|
|
|
+ btn.disabled = false; btn.textContent = '登录';
|
|
|
|
|
+ if (!r || !r.token) return;
|
|
|
|
|
+ PL.api.setToken(r.token);
|
|
|
|
|
+ applyLogin(r.user);
|
|
|
|
|
+ }, function (err) {
|
|
|
|
|
+ btn.disabled = false; btn.textContent = '登录';
|
|
|
|
|
+ showError(err.message || '登录失败,请重试');
|
|
|
|
|
+ });
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ // ---------- 强制绑定邮箱 ----------
|
|
|
|
|
+
|
|
|
|
|
+ function ensureBindModal() {
|
|
|
|
|
+ if (document.getElementById('plBindModal')) return;
|
|
|
|
|
+ const wrap = document.createElement('div');
|
|
|
|
|
+ wrap.id = 'plBindModal';
|
|
|
|
|
+ wrap.className = 'pl-auth-mask';
|
|
|
|
|
+ wrap.hidden = true;
|
|
|
|
|
+ wrap.innerHTML =
|
|
|
|
|
+ '<div class="pl-auth-card" role="dialog" aria-modal="true">' +
|
|
|
|
|
+ '<div class="pl-auth-brand">袋研社 <em>POUCHLAB</em></div>' +
|
|
|
|
|
+ '<h2>绑定邮箱</h2>' +
|
|
|
|
|
+ '<p class="pl-auth-sub">为保障订单通知与账号安全,请先绑定邮箱。绑定后方可继续使用。</p>' +
|
|
|
|
|
+ '<label class="pl-auth-label" for="plBindEmail">邮箱</label>' +
|
|
|
|
|
+ '<input id="plBindEmail" class="pl-auth-input" type="email" maxlength="120" autocomplete="email" placeholder="name@example.com">' +
|
|
|
|
|
+ '<label class="pl-auth-label" for="plBindCode">验证码</label>' +
|
|
|
|
|
+ '<div class="pl-auth-code-row">' +
|
|
|
|
|
+ '<input id="plBindCode" class="pl-auth-input" type="text" inputmode="numeric" maxlength="6" autocomplete="one-time-code" placeholder="6 位验证码">' +
|
|
|
|
|
+ '<button id="plBindSend" class="pl-auth-send" type="button">获取验证码</button>' +
|
|
|
|
|
+ '</div>' +
|
|
|
|
|
+ '<p class="pl-auth-error" id="plBindError" hidden></p>' +
|
|
|
|
|
+ '<button id="plBindSubmit" class="pl-auth-submit" type="button">确认绑定</button>' +
|
|
|
|
|
+ '</div>';
|
|
|
|
|
+ document.body.appendChild(wrap);
|
|
|
|
|
+ wrap.querySelector('#plBindSend').addEventListener('click', bindSendCode);
|
|
|
|
|
+ wrap.querySelector('#plBindSubmit').addEventListener('click', submitBind);
|
|
|
|
|
+ wrap.querySelector('#plBindCode').addEventListener('keydown', function (e) {
|
|
|
|
|
+ if (e.key === 'Enter') { e.preventDefault(); submitBind(); }
|
|
|
|
|
+ });
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ function openBind() {
|
|
|
|
|
+ ensureBindModal();
|
|
|
|
|
+ const m = document.getElementById('plBindModal');
|
|
|
|
|
+ document.getElementById('plBindEmail').value = '';
|
|
|
|
|
+ document.getElementById('plBindCode').value = '';
|
|
|
|
|
+ const err = document.getElementById('plBindError'); err.hidden = true;
|
|
|
|
|
+ m.hidden = false;
|
|
|
|
|
+ document.body.classList.add('pl-auth-open');
|
|
|
|
|
+ setTimeout(function () { document.getElementById('plBindEmail').focus(); }, 30);
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ function closeBind() {
|
|
|
|
|
+ const m = document.getElementById('plBindModal');
|
|
|
|
|
+ if (m) m.hidden = true;
|
|
|
|
|
+ if (!document.getElementById('plAuthModal') || document.getElementById('plAuthModal').hidden) {
|
|
|
|
|
+ document.body.classList.remove('pl-auth-open');
|
|
|
|
|
+ }
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ function bindError(msg) {
|
|
|
|
|
+ const el = document.getElementById('plBindError');
|
|
|
|
|
+ el.textContent = msg; el.hidden = false;
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ function bindSendCode() {
|
|
|
|
|
+ const email = document.getElementById('plBindEmail').value.trim();
|
|
|
|
|
+ if (!validEmail(email)) { bindError('请输入正确的邮箱地址'); return; }
|
|
|
|
|
+ const btn = document.getElementById('plBindSend');
|
|
|
|
|
+ btn.disabled = true; btn.textContent = '发送中…';
|
|
|
|
|
+ PL.api.post('/auth/email/send', { email: email }, { timeout: 15000 }).then(function (r) {
|
|
|
|
|
+ fillDemoCode(r, '#plBindCode', '演示验证码:');
|
|
|
|
|
+ startCountdown(btn);
|
|
|
|
|
+ }, function (err) {
|
|
|
|
|
+ btn.disabled = false; btn.textContent = '获取验证码';
|
|
|
|
|
+ bindError(err.message || '发送失败,请稍后再试');
|
|
|
|
|
+ });
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ function submitBind() {
|
|
|
|
|
+ const email = document.getElementById('plBindEmail').value.trim();
|
|
|
|
|
+ const code = document.getElementById('plBindCode').value.trim();
|
|
|
|
|
+ if (!validEmail(email)) { bindError('请输入正确的邮箱地址'); return; }
|
|
|
|
|
+ if (!/^\d{6}$/.test(code)) { bindError('请输入 6 位验证码'); return; }
|
|
|
|
|
+ const btn = document.getElementById('plBindSubmit');
|
|
|
|
|
+ btn.disabled = true; btn.textContent = '绑定中…';
|
|
|
|
|
+ PL.api.post('/auth/bind-email', { email: email, code: code }, { timeout: 10000 }).then(function (r) {
|
|
|
|
|
+ btn.disabled = false; btn.textContent = '确认绑定';
|
|
|
|
|
+ user.email = r.user.email; user.needsBindEmail = false; user.name = r.user.name || user.name;
|
|
|
|
|
+ persist(user);
|
|
|
|
|
+ closeBind();
|
|
|
|
|
+ notify('邮箱已绑定');
|
|
|
|
|
+ if (PL.api.flushBind) PL.api.flushBind();
|
|
|
|
|
+ }, function (err) {
|
|
|
|
|
+ btn.disabled = false; btn.textContent = '确认绑定';
|
|
|
|
|
+ bindError(err.message || '绑定失败,请重试');
|
|
|
|
|
+ });
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ document.addEventListener('pl:bind-email-required', function () {
|
|
|
|
|
+ if (user) openBind();
|
|
|
|
|
+ });
|
|
|
|
|
+
|
|
|
|
|
+ // ---------- 账户设置 ----------
|
|
|
|
|
+
|
|
|
|
|
+ function ensureAccountModal() {
|
|
|
|
|
+ if (document.getElementById('plAccModal')) return;
|
|
|
|
|
+ const wrap = document.createElement('div');
|
|
|
|
|
+ wrap.id = 'plAccModal';
|
|
|
|
|
+ wrap.className = 'pl-auth-mask';
|
|
|
|
|
+ wrap.hidden = true;
|
|
|
|
|
+ wrap.innerHTML = STYLE +
|
|
|
|
|
+ '<div class="pl-auth-card" role="dialog" aria-modal="true">' +
|
|
|
|
|
+ '<button class="pl-auth-close" type="button" aria-label="关闭">✕</button>' +
|
|
|
|
|
+ '<div class="pl-auth-brand">袋研社 <em>POUCHLAB</em></div>' +
|
|
|
|
|
+ '<h2>账户设置</h2>' +
|
|
|
|
|
+ '<p class="pl-auth-sub" id="plAccInfo"></p>' +
|
|
|
|
|
+ '<div id="plAccPwdSec">' +
|
|
|
|
|
+ '<label class="pl-auth-label" for="plAccOld" id="plAccOldLabel">旧密码</label>' +
|
|
|
|
|
+ '<input id="plAccOld" class="pl-auth-input" type="password" maxlength="64" autocomplete="current-password">' +
|
|
|
|
|
+ '<label class="pl-auth-label" for="plAccNew">新密码</label>' +
|
|
|
|
|
+ '<input id="plAccNew" class="pl-auth-input" type="password" maxlength="64" autocomplete="new-password" placeholder="至少 8 位,含字母和数字">' +
|
|
|
|
|
+ '<label class="pl-auth-label" for="plAccNew2">确认新密码</label>' +
|
|
|
|
|
+ '<input id="plAccNew2" class="pl-auth-input" type="password" maxlength="64" autocomplete="new-password">' +
|
|
|
|
|
+ '</div>' +
|
|
|
|
|
+ '<p class="pl-auth-error" id="plAccError" hidden></p>' +
|
|
|
|
|
+ '<button id="plAccSubmit" class="pl-auth-submit" type="button">保存密码</button>' +
|
|
|
|
|
+ '<button id="plAccBind" class="pl-auth-submit" type="button" hidden>去绑定邮箱</button>' +
|
|
|
|
|
+ '</div>';
|
|
|
|
|
+ document.body.appendChild(wrap);
|
|
|
|
|
+ wrap.querySelector('.pl-auth-close').addEventListener('click', function () { wrap.hidden = true; });
|
|
|
|
|
+ wrap.querySelector('#plAccSubmit').addEventListener('click', submitAccount);
|
|
|
|
|
+ wrap.querySelector('#plAccBind').addEventListener('click', function () {
|
|
|
|
|
+ wrap.hidden = true;
|
|
|
|
|
+ openBind();
|
|
|
|
|
+ });
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ function openAccount() {
|
|
|
|
|
+ ensureAccountModal();
|
|
|
|
|
+ if (!user) return;
|
|
|
|
|
+ const info = document.getElementById('plAccInfo');
|
|
|
|
|
+ info.textContent = user.email
|
|
|
|
|
+ ? '邮箱:' + user.email + ' · ' + (user.hasPassword ? '已设置密码' : '未设置密码')
|
|
|
|
|
+ : '尚未绑定邮箱(' + (user.phone ? '手机号 ' + maskPhone(user.phone) : '演示账号') + ')';
|
|
|
|
|
+ document.getElementById('plAccBind').hidden = !!user.email;
|
|
|
|
|
+ document.getElementById('plAccPwdSec').hidden = !!user.needBindBlock || !user.email && user.id === 0;
|
|
|
|
|
+ document.getElementById('plAccSubmit').hidden = document.getElementById('plAccPwdSec').hidden;
|
|
|
|
|
+ document.getElementById('plAccOldLabel').textContent = user.hasPassword ? '旧密码' : '旧密码(首次设置无需填写)';
|
|
|
|
|
+ document.getElementById('plAccOld').hidden = !user.hasPassword;
|
|
|
|
|
+ document.getElementById('plAccError').hidden = true;
|
|
|
|
|
+ document.getElementById('plAccModal').hidden = false;
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ function accError(msg) {
|
|
|
|
|
+ const el = document.getElementById('plAccError');
|
|
|
|
|
+ el.textContent = msg; el.hidden = false;
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ function submitAccount() {
|
|
|
|
|
+ const np = document.getElementById('plAccNew').value;
|
|
|
|
|
+ const np2 = document.getElementById('plAccNew2').value;
|
|
|
|
|
+ if (np !== np2) { accError('两次输入的密码不一致'); return; }
|
|
|
|
|
+ if (np.length < 8 || !/[A-Za-z]/.test(np) || !/\d/.test(np)) {
|
|
|
|
|
+ accError('密码需至少 8 位且包含字母和数字'); return;
|
|
|
|
|
+ }
|
|
|
|
|
+ const btn = document.getElementById('plAccSubmit');
|
|
|
|
|
+ btn.disabled = true;
|
|
|
|
|
+ PL.api.post('/auth/set-password',
|
|
|
|
|
+ { oldPassword: user.hasPassword ? document.getElementById('plAccOld').value : '', newPassword: np },
|
|
|
|
|
+ { timeout: 10000 }).then(function () {
|
|
|
|
|
+ btn.disabled = false;
|
|
|
|
|
+ user.hasPassword = true;
|
|
|
|
|
+ persist(user);
|
|
|
|
|
+ document.getElementById('plAccModal').hidden = true;
|
|
|
|
|
+ notify('密码已保存');
|
|
|
|
|
+ }, function (err) {
|
|
|
|
|
+ btn.disabled = false;
|
|
|
|
|
+ accError(err.message || '保存失败,请重试');
|
|
|
|
|
+ });
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ // ---------- 入口渲染 ----------
|
|
|
|
|
+
|
|
|
|
|
+ function displayName() {
|
|
|
|
|
+ if (!user) return '登录';
|
|
|
|
|
+ return user.name || user.email || maskPhone(user.phone) || '登录';
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ function logout() {
|
|
|
|
|
+ user = null;
|
|
|
|
|
+ pending = null;
|
|
|
|
|
+ try { localStorage.removeItem(KEY); } catch (e) {}
|
|
|
|
|
+ if (window.PL && PL.api) PL.api.setToken('');
|
|
|
|
|
+ emit();
|
|
|
|
|
+ notify('已退出登录');
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ function requireAuth(cb) {
|
|
|
|
|
+ if (user) {
|
|
|
|
|
+ if (user.needsBindEmail) openBind();
|
|
|
|
|
+ if (cb) cb();
|
|
|
|
|
+ return true;
|
|
|
|
|
+ }
|
|
|
|
|
+ pending = cb || null;
|
|
|
|
|
+ open();
|
|
|
|
|
+ return false;
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ function renderEntry(entry) {
|
|
|
|
|
+ const btn = entry.querySelector('.pl-auth-btn');
|
|
|
|
|
+ const menu = entry.querySelector('.pl-auth-menu');
|
|
|
|
|
+ if (!btn) return;
|
|
|
|
|
+ btn.textContent = displayName();
|
|
|
|
|
+ btn.classList.toggle('on', !!user);
|
|
|
|
|
+ if (menu) {
|
|
|
|
|
+ const name = menu.querySelector('.pl-auth-name');
|
|
|
|
|
+ if (name) name.textContent = user ? '已登录 · ' + (user.email || user.name) : '';
|
|
|
|
|
+ }
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ function buildEntry(entry) {
|
|
|
|
|
+ entry.innerHTML =
|
|
|
|
|
+ '<button class="pl-auth-btn" type="button"></button>' +
|
|
|
|
|
+ '<div class="pl-auth-menu" hidden>' +
|
|
|
|
|
+ '<span class="pl-auth-name"></span>' +
|
|
|
|
|
+ '<button type="button" class="pl-auth-account">账户设置</button>' +
|
|
|
|
|
+ '<button type="button" class="pl-auth-logout">退出登录</button>' +
|
|
|
|
|
+ '</div>';
|
|
|
|
|
+ const btn = entry.querySelector('.pl-auth-btn');
|
|
|
|
|
+ const menu = entry.querySelector('.pl-auth-menu');
|
|
|
|
|
+ btn.addEventListener('click', function (e) {
|
|
|
|
|
+ e.stopPropagation();
|
|
|
|
|
+ if (!user) { open(); return; }
|
|
|
|
|
+ menu.hidden = !menu.hidden;
|
|
|
|
|
+ });
|
|
|
|
|
+ entry.querySelector('.pl-auth-account').addEventListener('click', function (e) {
|
|
|
|
|
+ e.stopPropagation();
|
|
|
|
|
+ menu.hidden = true;
|
|
|
|
|
+ openAccount();
|
|
|
|
|
+ });
|
|
|
|
|
+ entry.querySelector('.pl-auth-logout').addEventListener('click', function (e) {
|
|
|
|
|
+ e.stopPropagation();
|
|
|
|
|
+ menu.hidden = true;
|
|
|
|
|
+ logout();
|
|
|
|
|
+ });
|
|
|
|
|
+ document.addEventListener('click', function () { menu.hidden = true; });
|
|
|
|
|
+ renderEntry(entry);
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ function mount() {
|
|
|
|
|
+ const trigger = document.getElementById('loginTrigger');
|
|
|
|
|
+ if (trigger) {
|
|
|
|
|
+ if (trigger.tagName === 'A') {
|
|
|
|
|
+ trigger.addEventListener('click', function (e) { e.preventDefault(); });
|
|
|
|
|
+ }
|
|
|
|
|
+ trigger.addEventListener('click', function () {
|
|
|
|
|
+ if (user) { logout(); } else { open(); }
|
|
|
|
|
+ });
|
|
|
|
|
+ const sync = function () {
|
|
|
|
|
+ trigger.textContent = displayName();
|
|
|
|
|
+ trigger.classList.toggle('on', !!user);
|
|
|
|
|
+ trigger.title = user ? '点击退出登录' : '登录';
|
|
|
|
|
+ };
|
|
|
|
|
+ listeners.push(sync);
|
|
|
|
|
+ sync();
|
|
|
|
|
+ }
|
|
|
|
|
+ const actions = document.querySelector('.studio-actions');
|
|
|
|
|
+ if (actions && !actions.querySelector('.pl-auth-entry')) {
|
|
|
|
|
+ const entry = document.createElement('span');
|
|
|
|
|
+ entry.className = 'pl-auth-entry';
|
|
|
|
|
+ actions.insertBefore(entry, actions.firstChild);
|
|
|
|
|
+ buildEntry(entry);
|
|
|
|
|
+ listeners.push(function () { renderEntry(entry); });
|
|
|
|
|
+ }
|
|
|
|
|
+ emit();
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ document.addEventListener('keydown', function (e) {
|
|
|
|
|
+ if (e.key === 'Escape') {
|
|
|
|
|
+ const modal = document.getElementById('plAuthModal');
|
|
|
|
|
+ if (modal && !modal.hidden) close();
|
|
|
|
|
+ // 强制绑定框不响应 Esc
|
|
|
|
|
+ }
|
|
|
|
|
+ });
|
|
|
|
|
+
|
|
|
|
|
+ window.PL = window.PL || {};
|
|
|
|
|
+ window.PL.auth = {
|
|
|
|
|
+ user: function () { return user; },
|
|
|
|
|
+ open: open,
|
|
|
|
|
+ logout: logout,
|
|
|
|
|
+ require: requireAuth,
|
|
|
|
|
+ openBind: openBind,
|
|
|
|
|
+ openAccount: openAccount,
|
|
|
|
|
+ onChange: function (fn) {
|
|
|
|
|
+ listeners.push(fn);
|
|
|
|
|
+ return function () { const i = listeners.indexOf(fn); if (i >= 0) listeners.splice(i, 1); };
|
|
|
|
|
+ }
|
|
|
|
|
+ };
|
|
|
|
|
+
|
|
|
|
|
+ if (document.readyState === 'loading') {
|
|
|
|
|
+ document.addEventListener('DOMContentLoaded', mount);
|
|
|
|
|
+ } else {
|
|
|
|
|
+ mount();
|
|
|
|
|
+ }
|
|
|
|
|
+})();
|
|
|
|
|
+```
|
|
|
|
|
+
|
|
|
|
|
+- [ ] **Step 2: 已知调用面回归检查**
|
|
|
|
|
+
|
|
|
|
|
+Run: `grep -rn "PL.auth\." assets/js/*.js *.html | grep -v auth.js`
|
|
|
|
|
+Expected: 只出现 `PL.auth.user()/open()/logout()/require()/onChange()`(均未删除);若出现其他成员,按需在新文件补齐后再继续。
|
|
|
|
|
+
|
|
|
|
|
+- [ ] **Step 3: 浏览器冒烟(本地 8080)**
|
|
|
|
|
+
|
|
|
|
|
+`orca tab create --url http://127.0.0.1:8080/index.html`(或人工):
|
|
|
|
|
+1. 登录弹窗默认邮箱 tab → 发码 → 演示 toast 出码并自动填入 → 登录进站(无绑定框)。
|
|
|
|
|
+2. 退出 → 手机号(旧) tab 登录新手机号 → 立即弹绑定框、无法 Esc 关闭 → 绑邮箱 → 进站。
|
|
|
|
|
+3. 菜单 → 账户设置 → 显示邮箱、设密码成功 → 密码 tab 用新密码登录成功。
|
|
|
|
|
+
|
|
|
|
|
+- [ ] **Step 4: Commit**
|
|
|
|
|
+
|
|
|
|
|
+```bash
|
|
|
|
|
+git add assets/js/auth.js
|
|
|
|
|
+git commit -m "auth-ui: 邮箱优先三通道登录、强制绑定邮箱与账户设置"
|
|
|
|
|
+```
|
|
|
|
|
+
|
|
|
|
|
+---
|
|
|
|
|
+
|
|
|
|
|
+## Task 9: 前端英文文案(i18n-en 批次 11)
|
|
|
|
|
+
|
|
|
|
|
+**Files:**
|
|
|
|
|
+- Modify: `assets/js/i18n-en.js`(在 `/* __MORE_ENTRIES__ */` 前追加)
|
|
|
|
|
+
|
|
|
|
|
+- [ ] **Step 1: 追加批次**
|
|
|
|
|
+
|
|
|
|
|
+```js
|
|
|
|
|
+/* 批次 11:邮箱账号体系 */
|
|
|
|
|
+(function (D) {
|
|
|
|
|
+ Object.assign(D.dict, {
|
|
|
|
|
+ "邮箱登录": "Email sign-in", "密码登录": "Password", "手机号(旧)": "Phone (legacy)",
|
|
|
|
|
+ "邮箱": "Email", "密码": "Password", "请输入正确的邮箱地址": "Enter a valid email address",
|
|
|
|
|
+ "请输入密码": "Enter your password", "登录密码": "Password",
|
|
|
|
|
+ "name@example.com": "name@example.com", "至少 8 位,含字母和数字": "8+ chars, letters and digits",
|
|
|
|
|
+ "登录后可保存设计、同步订单进度与下载记录。": "Sign in to save designs, sync order progress and downloads.",
|
|
|
|
|
+ "输入邮箱获取验证码登录;演示环境验证码会直接弹出显示。": "Enter your email to get a code. In demo mode the code is shown in a popup.",
|
|
|
|
|
+ "未设置密码的账号请用邮箱验证码登录。": "Accounts without a password — use the email code tab.",
|
|
|
|
|
+ "老手机号验证码登录;登录后需绑定邮箱。": "Legacy phone sign-in; an email must be bound afterwards.",
|
|
|
|
|
+ "绑定邮箱": "Bind Email",
|
|
|
|
|
+ "为保障订单通知与账号安全,请先绑定邮箱。绑定后方可继续使用。": "For order notifications and account security, bind your email first. You can continue after binding.",
|
|
|
|
|
+ "确认绑定": "Bind", "绑定中…": "Binding…", "邮箱已绑定": "Email bound", "绑定失败,请重试": "Binding failed — try again",
|
|
|
|
|
+ "验证码已发送,请查收邮件/短信": "Code sent — check your email/SMS",
|
|
|
|
|
+ "账户设置": "Account", "旧密码": "Current password", "新密码": "New password", "确认新密码": "Confirm password",
|
|
|
|
|
+ "旧密码(首次设置无需填写)": "Current password (leave empty for first setup)",
|
|
|
|
|
+ "保存密码": "Save password", "密码已保存": "Password saved", "保存失败,请重试": "Save failed — try again",
|
|
|
|
|
+ "两次输入的密码不一致": "Passwords do not match",
|
|
|
|
|
+ "密码需至少 8 位且包含字母和数字": "Password must be at least 8 characters with letters and digits",
|
|
|
|
|
+ "去绑定邮箱": "Bind your email", "尚未绑定邮箱": "No email bound yet",
|
|
|
|
|
+ "邮箱:": "Email: ", "已设置密码": "password set", "未设置密码": "no password",
|
|
|
|
|
+ "手机号 ": "Phone ", "演示账号": "demo account",
|
|
|
|
|
+ "搜索手机号 / 邮箱 / 昵称": "Search phone / email / nickname",
|
|
|
|
|
+ "该邮箱已被其他账号绑定": "This email is already linked to another account"
|
|
|
|
|
+ });
|
|
|
|
|
+})(window.PLI18N_EN);
|
|
|
|
|
+```
|
|
|
|
|
+
|
|
|
|
|
+- [ ] **Step 2: 语法校验**
|
|
|
|
|
+
|
|
|
|
|
+Run: `node --check assets/js/i18n-en.js`
|
|
|
|
|
+Expected: 无输出(通过)。
|
|
|
|
|
+
|
|
|
|
|
+- [ ] **Step 3: 浏览器 EN 抽检**
|
|
|
|
|
+
|
|
|
|
|
+`?lang=en` 打开登录弹窗:tab、hint、绑定框全英文;触发一次绑定成功流程无中文 toast 漏翻(服务端 403 消息走 Task 4 的 ERRORS_EN)。
|
|
|
|
|
+
|
|
|
|
|
+- [ ] **Step 4: Commit**
|
|
|
|
|
+
|
|
|
|
|
+```bash
|
|
|
|
|
+git add assets/js/i18n-en.js
|
|
|
|
|
+git commit -m "i18n: 邮箱账号体系英文文案(批次 11)"
|
|
|
|
|
+```
|
|
|
|
|
+
|
|
|
|
|
+---
|
|
|
|
|
+
|
|
|
|
|
+## Task 10: 全链路回归 + 版本与部署
|
|
|
|
|
+
|
|
|
|
|
+**Files:**
|
|
|
|
|
+- Modify: `server/main.py`(FastAPI version 与 /api/version,:28 与 :90)
|
|
|
|
|
+- Modify: `deploy/k8s/pouchlab.yaml:36`
|
|
|
|
|
+
|
|
|
|
|
+- [ ] **Step 1: 全量 e2e**
|
|
|
|
|
+
|
|
|
|
|
+Run: `cd server && python3 e2e_test.py`
|
|
|
|
|
+Expected: 全绿。
|
|
|
|
|
+
|
|
|
|
|
+- [ ] **Step 2: 版本号 1.8.23**
|
|
|
|
|
+
|
|
|
|
|
+`main.py` 两处 `"1.8.18"` → `"1.8.23"`;`deploy/k8s/pouchlab.yaml` 镜像 tag `pouchlab:1.8.22` → `pouchlab:1.8.23`。
|
|
|
|
|
+
|
|
|
|
|
+- [ ] **Step 3: 构建推送**
|
|
|
|
|
+
|
|
|
|
|
+```bash
|
|
|
|
|
+DOCKER_BUILDKIT=1 docker build --platform linux/amd64 -f deploy/Dockerfile -t k8s.device.wenhq.top:8583/docker_r/pouchlab:1.8.23 .
|
|
|
|
|
+docker push k8s.device.wenhq.top:8583/docker_r/pouchlab:1.8.23
|
|
|
|
|
+```
|
|
|
|
|
+
|
|
|
|
|
+- [ ] **Step 4: 发布**
|
|
|
|
|
+
|
|
|
|
|
+```bash
|
|
|
|
|
+scp deploy/k8s/pouchlab.yaml root@200.200.19.253:/tmp/
|
|
|
|
|
+ssh root@200.200.19.253 'kubectl apply -f /tmp/pouchlab.yaml -n pouchlab && kubectl rollout status deployment/pouchlab -n pouchlab --timeout=180s'
|
|
|
|
|
+```
|
|
|
|
|
+
|
|
|
|
|
+- [ ] **Step 5: 生产验证(迁移自动执行)**
|
|
|
|
|
+
|
|
|
|
|
+```bash
|
|
|
|
|
+curl -s localhost:30080/api/version # {"version":"1.8.23",...}
|
|
|
|
|
+curl -s -X POST localhost:30080/api/auth/email/send -H 'content-type: application/json' -d '{"email":"probe@example.com"}' # demo 模式返回 code
|
|
|
|
|
+ssh root@200.200.19.253 'kubectl exec deploy/pouchlab-mysql -- mysql -uroot -p"$MYSQL_ROOT_PASSWORD" pouchlab -e "SHOW COLUMNS FROM users LIKE '"'"'email'"'"'; SELECT id, phone, email FROM users"'
|
|
|
|
|
+```
|
|
|
|
|
+
|
|
|
|
|
+Expected: 版本 1.8.23;邮箱验证码返回;email 列已加、4 个存量手机号账号 email=NULL。
|
|
|
|
|
+注意:不要在生产真注册业务账号;probe@example.com 只发到 send(不 login 则不建号)。
|
|
|
|
|
+
|
|
|
|
|
+- [ ] **Step 6: 浏览器三端走查(生产)**
|
|
|
|
|
+
|
|
|
|
|
+登录弹窗邮箱注册→进站;旧手机号 13755556666 走不通短信?demo 模式 send 返回 code,可完成强制绑定闭环(若不想污染演示账号,跳过此步,本地 e2e 已覆盖);admin 用户列表出现邮箱列。
|
|
|
|
|
+
|
|
|
|
|
+- [ ] **Step 7: Commit**
|
|
|
|
|
+
|
|
|
|
|
+```bash
|
|
|
|
|
+git add server/main.py deploy/k8s/pouchlab.yaml
|
|
|
|
|
+git commit -m "release: 1.8.23 邮箱账号体系上线"
|
|
|
|
|
+```
|
|
|
|
|
+
|
|
|
|
|
+---
|
|
|
|
|
+
|
|
|
|
|
+## Self-review 记录
|
|
|
|
|
+
|
|
|
|
|
+- Spec 覆盖:数据库迁移✓ Task2;5 端点✓ Task4;强制拦截+重放✓ Task3/7;登录 UI 三通道✓ Task8;账户面板✓ Task8(位置偏差已在头部声明);后台邮箱列/搜索✓ Task5;错误处理与 i18n✓ Task3/4/9;测试✓ Task6/10;部署✓ Task10。
|
|
|
|
|
+- 命名一致性:`normalize_email/issue_email_code/check_email_code`(Task3)→ Task4 引用一致;`needsBindEmail/hasPassword`(Task2 定义)→ Task4/6/8 使用一致;`flushBind`(Task7)= Task8 调用;端点路径 `email/send、email/login、email/password-login、set-password、bind-email` 全文一致。
|
|
|
|
|
+- 无占位符。
|