回滚bug修复
This commit is contained in:
@@ -16,6 +16,7 @@ from fastapi.responses import JSONResponse
|
||||
from typing import Optional, Dict, Any
|
||||
import re
|
||||
|
||||
from config import settings
|
||||
from utils.jwt_handler import jwt_handler
|
||||
from utils.redis_client import RedisClient
|
||||
from utils.response import unauthorized_response
|
||||
@@ -32,12 +33,6 @@ PUBLIC_PATHS = [
|
||||
r'^/debug/.*$', # 调试入口
|
||||
]
|
||||
|
||||
# 不需要Token验证但需要记录访问的路由
|
||||
OPEN_PATHS = [
|
||||
r'^/api/auth/change-password$',
|
||||
]
|
||||
|
||||
|
||||
def is_public_path(path: str) -> bool:
|
||||
"""检查是否为公开路径"""
|
||||
for pattern in PUBLIC_PATHS:
|
||||
@@ -50,34 +45,42 @@ class AuthMiddleware(BaseHTTPMiddleware):
|
||||
"""JWT认证中间件"""
|
||||
|
||||
async def dispatch(self, request: Request, call_next):
|
||||
path = request.url.path
|
||||
|
||||
# OPTIONS 预检请求跳过认证
|
||||
if request.method == "OPTIONS":
|
||||
logger.debug(f"[Auth] OPTIONS {path} - 跳过认证")
|
||||
return await call_next(request)
|
||||
|
||||
path = request.url.path
|
||||
|
||||
# 公开路径跳过认证
|
||||
if is_public_path(path):
|
||||
logger.debug(f"[Auth] {request.method} {path} - 公开路径,跳过认证")
|
||||
return await call_next(request)
|
||||
|
||||
logger.info(f"[Auth] {request.method} {path} - 开始认证")
|
||||
|
||||
try:
|
||||
# 获取Authorization头
|
||||
auth_header = request.headers.get("Authorization")
|
||||
|
||||
if not auth_header:
|
||||
logger.warning(f"[Auth] {path} - 缺少Authorization header")
|
||||
return self._cors_response(request, 401, "缺少认证令牌")
|
||||
|
||||
# 解析Bearer Token
|
||||
try:
|
||||
scheme, token = auth_header.split()
|
||||
if scheme.lower() != "bearer":
|
||||
logger.warning(f"[Auth] {path} - Authorization header格式错误")
|
||||
return self._cors_response(request, 401, "认证格式错误")
|
||||
except ValueError:
|
||||
logger.warning(f"[Auth] {path} - Authorization header格式错误")
|
||||
return self._cors_response(request, 401, "认证格式错误")
|
||||
|
||||
# 验证Token
|
||||
payload = jwt_handler.verify_token(token)
|
||||
if not payload:
|
||||
logger.warning(f"[Auth] {path} - JWT验证失败")
|
||||
return self._cors_response(request, 401, "令牌无效或已过期")
|
||||
|
||||
# 验证Redis中的Token
|
||||
@@ -85,6 +88,7 @@ class AuthMiddleware(BaseHTTPMiddleware):
|
||||
stored_token = await RedisClient.get_user_token(user_id)
|
||||
|
||||
if not stored_token or stored_token != token:
|
||||
logger.warning(f"[Auth] {path} - Redis Token不匹配, user_id={user_id}, stored={'有' if stored_token else '无'}")
|
||||
return self._cors_response(request, 401, "令牌已失效,请重新登录")
|
||||
|
||||
# 将用户信息存储到request.state
|
||||
@@ -95,9 +99,10 @@ class AuthMiddleware(BaseHTTPMiddleware):
|
||||
request.state.role = payload.get("role")
|
||||
|
||||
# 刷新Token过期时间
|
||||
from config import settings
|
||||
await RedisClient.expire(f"user_token:{user_id}", settings.JWT_EXPIRE_MINUTES * 60)
|
||||
|
||||
logger.debug(f"[Auth] {path} - 认证成功, user_id={user_id}, username={payload.get('username')}")
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"认证中间件异常: {e}", exc_info=True)
|
||||
return self._cors_response(request, 401, "认证服务异常,请稍后重试")
|
||||
@@ -107,7 +112,7 @@ class AuthMiddleware(BaseHTTPMiddleware):
|
||||
def _cors_response(self, request: Request, status_code: int, message: str) -> JSONResponse:
|
||||
"""创建带CORS头的响应"""
|
||||
origin = request.headers.get("origin", "")
|
||||
allowed_origins = ["https://class.sea-studio.top", "https://classbackendapi.sea-studio.top"]
|
||||
allowed_origins = settings.CORS_ORIGINS or []
|
||||
|
||||
headers = {}
|
||||
if origin in allowed_origins:
|
||||
|
||||
Reference in New Issue
Block a user