|
|
@@ -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)}
|