crawler_task_management/public_function/auth.py

28 lines
1.1 KiB
Python
Raw Permalink Normal View History

2025-11-28 18:17:54 +08:00
import os
from pathlib import Path
2025-11-28 11:14:38 +08:00
from fastapi import Request
from fastapi.responses import JSONResponse
2025-11-28 18:17:54 +08:00
from public_function.public_func import read_config
from public_function.redis_task_manager import RedisTaskManager
config_path = os.path.join(Path(__file__).resolve().parent, 'config.yaml')
config = read_config(config_path)
redis_conn = RedisTaskManager(config)
2025-11-29 10:18:38 +08:00
TOKEN = "opB4ztbdw45xFoJbXti20520bsEq3UDKKAtiDWHnGjjhP6v0KNFjqBM7bfzto6GLdUPviYnVdCgdCJYqe42nPoy6mvW59F3TPQZu"
2025-11-28 11:14:38 +08:00
async def verify_tk_token(request: Request, call_next):
"""鉴权中间件"""
2025-11-29 10:18:38 +08:00
path = request.scope["path"]
2025-11-28 11:14:38 +08:00
token = request.headers.get("token")
2025-11-29 10:18:38 +08:00
if path.endswith("token"):
if token != TOKEN:
return JSONResponse(status_code=401, content={"detail": "token 验证失败"})
else:
if not redis_conn.check_field_exists('user_token', token):
return JSONResponse(status_code=401, content={"detail": "token 验证失败"})
2025-11-28 18:17:54 +08:00
# if token != TOKEN:
# return JSONResponse(status_code=401, content={"detail": "token 验证失败"})
2025-11-28 11:14:38 +08:00
return await call_next(request)