routes_auth.py 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187
  1. # -*- coding: utf-8 -*-
  2. """认证路由:短信登录(用户)、账号密码登录(管理员)、当前用户信息。"""
  3. import time
  4. import re
  5. from fastapi import APIRouter, HTTPException, Request
  6. from pydantic import BaseModel
  7. import auth
  8. import cache
  9. from db import db, user_row_to_dict
  10. router = APIRouter(prefix="/api/auth", tags=["auth"])
  11. class SmsSendBody(BaseModel):
  12. phone: str
  13. class SmsLoginBody(BaseModel):
  14. phone: str
  15. code: str
  16. class AdminLoginBody(BaseModel):
  17. username: str
  18. password: str
  19. class EmailSendBody(BaseModel):
  20. email: str
  21. class EmailLoginBody(BaseModel):
  22. email: str
  23. code: str
  24. class EmailPasswordLoginBody(BaseModel):
  25. email: str
  26. password: str
  27. class SetPasswordBody(BaseModel):
  28. oldPassword: str = ""
  29. newPassword: str
  30. class BindEmailBody(BaseModel):
  31. email: str
  32. code: str
  33. @router.post("/sms/send")
  34. def sms_send(body: SmsSendBody):
  35. phone = body.phone.strip()
  36. if not phone.isdigit() or len(phone) != 11:
  37. raise HTTPException(status_code=400, detail="请输入正确的手机号")
  38. return auth.issue_sms_code(phone)
  39. @router.post("/sms/login")
  40. def sms_login(body: SmsLoginBody):
  41. phone = body.phone.strip()
  42. code = body.code.strip()
  43. if not auth.check_sms_code(phone, code):
  44. raise HTTPException(status_code=400, detail="验证码错误或已过期")
  45. with db() as cur:
  46. cur.execute("SELECT * FROM users WHERE phone = %s", (phone,))
  47. row = cur.fetchone()
  48. if not row:
  49. cur.execute(
  50. "INSERT INTO users (phone, username, name, role, status, password_hash, created_at)"
  51. " VALUES (%s, NULL, %s, 'user', 'active', NULL, %s)",
  52. (phone, "用户" + phone[-4:], int(time.time())),
  53. )
  54. cur.execute("SELECT * FROM users WHERE phone = %s", (phone,))
  55. row = cur.fetchone()
  56. if row["status"] != "active":
  57. raise HTTPException(status_code=403, detail="账号已被禁用,请联系客服")
  58. user = user_row_to_dict(row)
  59. return {"token": auth.make_token(row["id"], row["role"]), "user": user}
  60. @router.post("/admin/login")
  61. def admin_login(body: AdminLoginBody):
  62. """后台/工厂协作账号登录(同一入口,按角色分发界面权限)。"""
  63. with db() as cur:
  64. cur.execute(
  65. "SELECT * FROM users WHERE username = %s AND role IN ('admin', 'factory')",
  66. (body.username.strip(),),
  67. )
  68. row = cur.fetchone()
  69. if not row or not auth.verify_password(body.password, row["password_hash"] or ""):
  70. raise HTTPException(status_code=401, detail="用户名或密码错误")
  71. if row["status"] != "active":
  72. raise HTTPException(status_code=403, detail="账号已被禁用")
  73. return {"token": auth.make_token(row["id"], row["role"]), "user": user_row_to_dict(row)}
  74. @router.get("/me")
  75. def me(request: Request):
  76. return auth.user_from_request(request)
  77. @router.post("/email/send")
  78. def email_send(body: EmailSendBody):
  79. return auth.issue_email_code(auth.normalize_email(body.email))
  80. @router.post("/email/login")
  81. def email_login(body: EmailLoginBody):
  82. """邮箱验证码登录;账号不存在则自动注册(无密码,name=邮箱前缀)。"""
  83. email = auth.normalize_email(body.email)
  84. if not auth.check_email_code(email, body.code.strip()):
  85. raise HTTPException(status_code=400, detail="验证码错误或已过期")
  86. with db() as cur:
  87. cur.execute("SELECT * FROM users WHERE email = %s", (email,))
  88. row = cur.fetchone()
  89. if not row:
  90. cur.execute(
  91. "INSERT INTO users (phone, username, name, role, status, password_hash, created_at, email)"
  92. " VALUES (NULL, NULL, %s, 'user', 'active', NULL, %s, %s)",
  93. (email.split("@", 1)[0][:100], int(time.time()), email),
  94. )
  95. cur.execute("SELECT * FROM users WHERE email = %s", (email,))
  96. row = cur.fetchone()
  97. if row["status"] != "active":
  98. raise HTTPException(status_code=403, detail="账号已被禁用,请联系客服")
  99. cache.delete(cache.USER_KEY % row["id"])
  100. user = user_row_to_dict(row)
  101. return {"token": auth.make_token(row["id"], row["role"]), "user": user}
  102. @router.post("/email/password-login")
  103. def email_password_login(body: EmailPasswordLoginBody):
  104. email = auth.normalize_email(body.email)
  105. with db() as cur:
  106. cur.execute("SELECT * FROM users WHERE email = %s AND role = 'user'", (email,))
  107. row = cur.fetchone()
  108. if row and not row["password_hash"]:
  109. raise HTTPException(status_code=400, detail="该账号未设置密码,请使用验证码登录")
  110. if not row or not auth.verify_password(body.password, row["password_hash"] or ""):
  111. raise HTTPException(status_code=401, detail="邮箱或密码错误")
  112. if row["status"] != "active":
  113. raise HTTPException(status_code=403, detail="账号已被禁用,请联系客服")
  114. return {"token": auth.make_token(row["id"], row["role"]), "user": user_row_to_dict(row)}
  115. @router.post("/set-password")
  116. def set_password(request: Request, body: SetPasswordBody):
  117. """设置/修改登录密码。验证码注册的账号首次设置免旧密码。"""
  118. me = auth.user_from_request(request)
  119. new = body.newPassword or ""
  120. if len(new) < 8 or not re.search(r"[A-Za-z]", new) or not re.search(r"\d", new):
  121. raise HTTPException(status_code=400, detail="密码需至少 8 位且包含字母和数字")
  122. with db() as cur:
  123. cur.execute("SELECT password_hash FROM users WHERE id = %s", (me["id"],))
  124. row = cur.fetchone()
  125. if not row:
  126. raise HTTPException(status_code=401, detail="账号不存在")
  127. if row["password_hash"] and not auth.verify_password(body.oldPassword or "", row["password_hash"]):
  128. raise HTTPException(status_code=400, detail="旧密码不正确")
  129. cur.execute(
  130. "UPDATE users SET password_hash = %s WHERE id = %s",
  131. (auth.hash_password(new), me["id"]),
  132. )
  133. cache.delete(cache.USER_KEY % me["id"])
  134. return {"ok": True, "hasPassword": True}
  135. @router.post("/bind-email")
  136. def bind_email(request: Request, body: BindEmailBody):
  137. """已登录用户绑定邮箱(legacy 手机号账号强制路径,也可主动使用)。"""
  138. me = auth.user_from_request(request)
  139. email = auth.normalize_email(body.email)
  140. if not auth.check_email_code(email, body.code.strip()):
  141. raise HTTPException(status_code=400, detail="验证码错误或已过期")
  142. with db() as cur:
  143. cur.execute("SELECT id FROM users WHERE email = %s AND id != %s", (email, me["id"]))
  144. if cur.fetchone():
  145. raise HTTPException(status_code=400, detail="该邮箱已被其他账号绑定")
  146. cur.execute("UPDATE users SET email = %s WHERE id = %s", (email, me["id"]))
  147. cur.execute("SELECT * FROM users WHERE id = %s", (me["id"],))
  148. row = cur.fetchone()
  149. cache.delete(cache.USER_KEY % me["id"])
  150. return {"ok": True, "user": user_row_to_dict(row)}