Преглед изворни кода

api: 邮箱登录/密码登录/设置密码/绑定邮箱端点与服务端翻译

wenhongquan пре 1 месец
родитељ
комит
1f5b08fc62
2 измењених фајлова са 124 додато и 0 уклоњено
  1. 14 0
      server/i18n.py
  2. 110 0
      server/routes_auth.py

+ 14 - 0
server/i18n.py

@@ -40,12 +40,14 @@ ERRORS_EN = {
     "反馈不存在": "Feedback not found",
     "发送太频繁,请稍后再试": "Sending too frequently — please try again later",
     "密码至少 6 位": "Password must be at least 6 characters",
+    "密码需至少 8 位且包含字母和数字": "Password must be at least 8 characters with letters and digits",
     "工厂账号不存在": "Factory account not found",
     "工厂账号专用接口": "Factory-account-only endpoint",
     "已支付订单请联系客服处理": "Paid order — please contact support",
     "当前状态不可取消": "Cannot cancel in the current status",
     "支付状态不合法": "Invalid payment status",
     "无权查看该订单": "You are not allowed to view this order",
+    "旧密码不正确": "Current password is incorrect",
     "模型名过长": "Model name too long",
     "状态不合法": "Invalid status",
     "生产图纸生成失败": "Production drawing generation failed",
@@ -68,7 +70,10 @@ ERRORS_EN = {
     "该订单尚未进入生产流程": "This order has not entered production yet",
     "该订单没有刀版数据": "This order has no dieline data",
     "该订单没有设计数据": "This order has no design data",
+    "该账号未设置密码,请使用验证码登录": "No password set for this account — sign in with the code",
+    "该邮箱已被其他账号绑定": "This email is already linked to another account",
     "请先登录": "Please sign in first",
+    "请先绑定邮箱后继续使用": "Please bind your email to continue",
     "请填写反馈内容": "Please fill in the feedback",
     "请填写回复内容": "Please fill in the reply",
     "请填写快递公司和运单号": "Please enter the carrier and tracking number",
@@ -77,12 +82,15 @@ ERRORS_EN = {
     "请填写邮件主题与内容": "Please enter the email subject and body",
     "请描述你的排版需求": "Describe your layout needs",
     "请输入正确的手机号": "Enter a valid phone number",
+    "请输入正确的邮箱地址": "Enter a valid email address",
     "请输入消息": "Please enter a message",
     "账号不存在": "Account not found",
     "账号已被禁用": "Account disabled",
     "账号已被禁用,请联系客服": "Account disabled — please contact support",
     "需要工作人员权限": "Staff permission required",
     "需要管理员权限": "Admin permission required",
+    "邮件发送失败,请稍后再试": "Failed to send email — try again later",
+    "邮箱或密码错误": "Wrong email or password",
     "预览图不存在": "Preview image not found",
     "额度需在 0-100000 之间": "Quota must be between 0 and 100000",
     "验证码错误或已过期": "Incorrect or expired verification code",
@@ -116,6 +124,12 @@ def translate_json_body(body: bytes, lang: str) -> bytes:
         return body
     changed = False
     if isinstance(data, dict):
+        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
         for key in ("detail", "message", "msg", "error"):
             v = data.get(key)
             if isinstance(v, str):

+ 110 - 0
server/routes_auth.py

@@ -1,11 +1,13 @@
 # -*- coding: utf-8 -*-
 """认证路由:短信登录(用户)、账号密码登录(管理员)、当前用户信息。"""
 import time
+import re
 
 from fastapi import APIRouter, HTTPException, Request
 from pydantic import BaseModel
 
 import auth
+import cache
 from db import db, user_row_to_dict
 
 router = APIRouter(prefix="/api/auth", tags=["auth"])
@@ -25,6 +27,30 @@ class AdminLoginBody(BaseModel):
     password: str
 
 
+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
+
+
 @router.post("/sms/send")
 def sms_send(body: SmsSendBody):
     phone = body.phone.strip()
@@ -75,3 +101,87 @@ def admin_login(body: AdminLoginBody):
 @router.get("/me")
 def me(request: Request):
     return auth.user_from_request(request)
+
+
+@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)}