feat: add JWT authentication and AGENTS.md

This commit is contained in:
祀梦
2026-05-17 11:21:41 +08:00
parent 40eb2dadb0
commit 3c03866021
19 changed files with 554 additions and 1632 deletions

View File

@@ -10,6 +10,7 @@ from app.config import CORS_ORIGINS, WEBUI_PATH, HOST, PORT
from app.database import init_db
from app.routers import api_router
from app.utils.logger import logger
from app.utils.auth import decode_access_token
@asynccontextmanager
@@ -89,6 +90,28 @@ async def log_requests(request: Request, call_next):
return response
# 认证中间件(保护所有 /api/* 路由,除了 /api/auth/* 和 /health
@app.middleware("http")
async def auth_middleware(request: Request, call_next):
path = request.url.path
# 不拦截健康检查、静态文件、auth 路由
if path == "/health" or not path.startswith("/api/") or path.startswith("/api/auth/"):
return await call_next(request)
auth_header = request.headers.get("Authorization", "")
token = auth_header.replace("Bearer ", "")
if not token:
return JSONResponse(status_code=401, content={"detail": "未登录"})
try:
decode_access_token(token)
except Exception:
return JSONResponse(status_code=401, content={"detail": "登录已过期,请重新登录"})
return await call_next(request)
# 全局异常处理器
@app.exception_handler(Exception)
async def global_exception_handler(request: Request, exc: Exception):