auth.py 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187
  1. """
  2. 认证与用户校验中间件(ASGI)
  3. - 验证 Authorization: Bearer <token>
  4. - 校验用户/管理员存在性与用户卡密到期
  5. - 在 scope 中注入 verified_user_id / verified_admin_id 供下游中间件使用
  6. """
  7. from typing import Callable
  8. from app.core.security import verify_token
  9. from app.database import SessionLocal
  10. from app.models.user import User
  11. from app.models.admin import Admin
  12. from app.utils.timezone import beijing_now_naive
  13. from fastapi.responses import JSONResponse
  14. import json
  15. from datetime import datetime
  16. from app.core.logger import logger, get_logger_by_path
  17. EXEMPT_PATHS = [
  18. "/admin/login",
  19. "/api/login",
  20. # 客户端不需要加密/鉴权的用户接口(明文调用时可免鉴权)
  21. "/api/user/login",
  22. "/api/user/register",
  23. "/api/user/unbind",
  24. "/api/user/recharge",
  25. # 公钥获取接口(需要时间戳验证)
  26. "/api/keys/public",
  27. "/api/v1/keys/public",
  28. "/health",
  29. "/docs",
  30. "/redoc",
  31. "/openapi.json",
  32. # 公共接口,可按需加入
  33. "/api/health", # 健康检查接口
  34. "/api/user/heartbeat",
  35. "/api/announcement", # 客户端公告查询接口
  36. "/api/configs", # 客户端配置获取接口
  37. # v1 路由前缀(加密接口,无需 Bearer)
  38. "/api/v1/auth/login",
  39. "/api/v1/auth/register",
  40. "/api/v1/auth/forgot-password",
  41. "/api/v1/auth/recharge",
  42. "/api/v1/auth/unbind",
  43. "/api/v1/auth/change-password",
  44. "/api/v1/announcements",
  45. "/api/v1/heartbeat",
  46. ]
  47. class AuthValidationASGIMiddleware:
  48. def __init__(self, app):
  49. self.app = app
  50. async def __call__(self, scope, receive, send):
  51. # 仅处理 HTTP 请求
  52. if scope.get("type") != "http":
  53. await self.app(scope, receive, send)
  54. return
  55. path = scope.get("path", "")
  56. method = scope.get("method", "").upper()
  57. # 根据路径选择对应的logger
  58. auth_logger = get_logger_by_path(path)
  59. # 跳过不需要验证的路径或 CORS 预检
  60. if method == "OPTIONS" or any(path.startswith(p) for p in EXEMPT_PATHS):
  61. await self.app(scope, receive, send)
  62. return
  63. headers = {k.decode("utf-8"): v.decode("utf-8") for k, v in scope.get("headers", [])}
  64. auth_header = headers.get("authorization", "") or headers.get("Authorization", "")
  65. # 获取header中的用户信息用于组合校验
  66. header_user_id = headers.get("x-user-id") or headers.get("X-User-Id")
  67. header_user_name = headers.get("x-user-name") or headers.get("X-User-Name")
  68. # 临时调试日志:记录客户端传来的鉴别头,帮助定位客户端是否传递了 X-User-Id/X-User-Name 或 Authorization
  69. try:
  70. auth_logger.debug(f"[AuthMiddleware][DEBUG HEADERS] path={path} method={method} X-User-Id={header_user_id} X-User-Name={header_user_name} AuthorizationPresent={bool(auth_header)}")
  71. except Exception:
  72. auth_logger.debug("[AuthMiddleware][DEBUG HEADERS] failed to read headers")
  73. if not auth_header or not auth_header.startswith("Bearer "):
  74. resp = JSONResponse(status_code=401, content={"code": 401, "msg": "认证信息缺失或无效"})
  75. await resp(scope, receive, send)
  76. return
  77. token = auth_header[7:]
  78. payload = verify_token(token)
  79. if not payload:
  80. resp = JSONResponse(status_code=401, content={"code": 401, "msg": "认证信息无效或已过期"})
  81. await resp(scope, receive, send)
  82. return
  83. username = payload.get("sub")
  84. if not username:
  85. resp = JSONResponse(status_code=401, content={"code": 401, "msg": "认证信息无效"})
  86. await resp(scope, receive, send)
  87. return
  88. auth_logger.debug(f"[AuthMiddleware][DEBUG] Starting authentication for username: {username}, path: {path}")
  89. # 查询用户或管理员
  90. db = SessionLocal()
  91. try:
  92. user = db.query(User).filter(User.username == username, User.is_deleted == 0).first()
  93. if user:
  94. auth_logger.debug(f"[AuthMiddleware][DEBUG] Found user: {user.username} (ID: {user.id})")
  95. # 检查状态与过期
  96. if user.status != 1:
  97. resp = JSONResponse(status_code=403, content={"code": 403, "msg": "账号已被禁用"})
  98. await resp(scope, receive, send)
  99. return
  100. if user.expire_time and user.expire_time < beijing_now_naive():
  101. resp = JSONResponse(status_code=403, content={"code": 403, "msg": "卡密已过期"})
  102. await resp(scope, receive, send)
  103. return
  104. # 验证header中的用户信息是否匹配(组合校验)
  105. if header_user_id and header_user_name:
  106. try:
  107. header_user_id_int = int(header_user_id)
  108. if header_user_id_int != user.id or header_user_name != user.username:
  109. resp = JSONResponse(status_code=401, content={"code": 401, "msg": "用户信息校验失败"})
  110. await resp(scope, receive, send)
  111. return
  112. except ValueError:
  113. resp = JSONResponse(status_code=401, content={"code": 401, "msg": "用户信息格式错误"})
  114. await resp(scope, receive, send)
  115. return
  116. else:
  117. resp = JSONResponse(status_code=401, content={"code": 401, "msg": "缺少用户信息"})
  118. await resp(scope, receive, send)
  119. return
  120. scope["verified_user_id"] = user.id
  121. scope["verified_username"] = user.username
  122. scope["verified_is_admin"] = False
  123. auth_logger.debug(f"[AuthMiddleware][DEBUG] Set verified_user_id: {user.id} for user: {user.username}")
  124. await self.app(scope, receive, send)
  125. return
  126. admin = db.query(Admin).filter(Admin.username == username).first()
  127. if admin:
  128. auth_logger.debug(f"[AuthMiddleware][DEBUG] Found admin: {admin.username} (ID: {admin.id})")
  129. # 验证header中的用户信息是否匹配(组合校验)
  130. if header_user_id and header_user_name:
  131. try:
  132. header_user_id_int = int(header_user_id)
  133. if header_user_id_int != admin.id or header_user_name != admin.username:
  134. resp = JSONResponse(status_code=401, content={"code": 401, "msg": "用户信息校验失败"})
  135. await resp(scope, receive, send)
  136. return
  137. except ValueError:
  138. resp = JSONResponse(status_code=401, content={"code": 401, "msg": "用户信息格式错误"})
  139. await resp(scope, receive, send)
  140. return
  141. else:
  142. resp = JSONResponse(status_code=401, content={"code": 401, "msg": "缺少用户信息"})
  143. await resp(scope, receive, send)
  144. return
  145. if admin.status != 1:
  146. resp = JSONResponse(status_code=403, content={"code": 403, "msg": "管理员账号已被禁用"})
  147. await resp(scope, receive, send)
  148. return
  149. scope["verified_admin_id"] = admin.id
  150. scope["verified_username"] = admin.username
  151. scope["verified_is_admin"] = True
  152. auth_logger.debug(f"[AuthMiddleware][DEBUG] Set verified_admin_id: {admin.id} for admin: {admin.username}")
  153. await self.app(scope, receive, send)
  154. return
  155. # 未找到对应用户或管理员
  156. auth_logger.debug(f"[AuthMiddleware][DEBUG] No user or admin found for username: {username}")
  157. resp = JSONResponse(status_code=401, content={"code": 401, "msg": "认证失败:用户不存在"})
  158. await resp(scope, receive, send)
  159. return
  160. except Exception as e:
  161. auth_logger.exception(f"[AuthMiddleware][ERROR] Exception during authentication: {e}")
  162. resp = JSONResponse(status_code=500, content={"code": 500, "msg": "认证服务异常"})
  163. await resp(scope, receive, send)
  164. return
  165. finally:
  166. db.close()