auth.py 8.1 KB

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