routes_auth.py 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. # -*- coding: utf-8 -*-
  2. """认证路由:短信登录(用户)、账号密码登录(管理员)、当前用户信息。"""
  3. import time
  4. from fastapi import APIRouter, HTTPException, Request
  5. from pydantic import BaseModel
  6. import auth
  7. from db import db, user_row_to_dict
  8. router = APIRouter(prefix="/api/auth", tags=["auth"])
  9. class SmsSendBody(BaseModel):
  10. phone: str
  11. class SmsLoginBody(BaseModel):
  12. phone: str
  13. code: str
  14. class AdminLoginBody(BaseModel):
  15. username: str
  16. password: str
  17. @router.post("/sms/send")
  18. def sms_send(body: SmsSendBody):
  19. phone = body.phone.strip()
  20. if not phone.isdigit() or len(phone) != 11:
  21. raise HTTPException(status_code=400, detail="请输入正确的手机号")
  22. return auth.issue_sms_code(phone)
  23. @router.post("/sms/login")
  24. def sms_login(body: SmsLoginBody):
  25. phone = body.phone.strip()
  26. code = body.code.strip()
  27. if not auth.check_sms_code(phone, code):
  28. raise HTTPException(status_code=400, detail="验证码错误或已过期")
  29. with db() as cur:
  30. cur.execute("SELECT * FROM users WHERE phone = %s", (phone,))
  31. row = cur.fetchone()
  32. if not row:
  33. cur.execute(
  34. "INSERT INTO users (phone, username, name, role, status, password_hash, created_at)"
  35. " VALUES (%s, NULL, %s, 'user', 'active', NULL, %s)",
  36. (phone, "用户" + phone[-4:], int(time.time())),
  37. )
  38. cur.execute("SELECT * FROM users WHERE phone = %s", (phone,))
  39. row = cur.fetchone()
  40. if row["status"] != "active":
  41. raise HTTPException(status_code=403, detail="账号已被禁用,请联系客服")
  42. user = user_row_to_dict(row)
  43. return {"token": auth.make_token(row["id"], row["role"]), "user": user}
  44. @router.post("/admin/login")
  45. def admin_login(body: AdminLoginBody):
  46. """后台/工厂协作账号登录(同一入口,按角色分发界面权限)。"""
  47. with db() as cur:
  48. cur.execute(
  49. "SELECT * FROM users WHERE username = %s AND role IN ('admin', 'factory')",
  50. (body.username.strip(),),
  51. )
  52. row = cur.fetchone()
  53. if not row or not auth.verify_password(body.password, row["password_hash"] or ""):
  54. raise HTTPException(status_code=401, detail="用户名或密码错误")
  55. if row["status"] != "active":
  56. raise HTTPException(status_code=403, detail="账号已被禁用")
  57. return {"token": auth.make_token(row["id"], row["role"]), "user": user_row_to_dict(row)}
  58. @router.get("/me")
  59. def me(request: Request):
  60. return auth.user_from_request(request)