ForcePilot/server/main.py

63 lines
1.9 KiB
Python
Raw Normal View History

2024-10-02 20:11:28 +08:00
import uvicorn
2025-02-28 00:26:57 +08:00
2025-05-02 23:56:59 +08:00
from fastapi import FastAPI, Request, HTTPException, status, Depends
2024-10-02 20:11:28 +08:00
from fastapi.middleware.cors import CORSMiddleware
2025-05-02 23:56:59 +08:00
from fastapi.responses import JSONResponse
from starlette.middleware.base import BaseHTTPMiddleware
2025-04-04 00:16:18 +08:00
from server.routers import router
from server.utils.auth_middleware import is_public_path
2025-02-27 19:35:25 +08:00
from src.utils.logging_config import logger
2024-10-02 20:11:28 +08:00
app = FastAPI()
app.include_router(router, prefix="/api")
2024-10-02 20:11:28 +08:00
# CORS 设置
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
2025-05-02 23:56:59 +08:00
# 鉴权中间件
class AuthMiddleware(BaseHTTPMiddleware):
async def dispatch(self, request: Request, call_next):
# 获取请求路径
path = request.url.path
# 检查是否为公开路径,公开路径无需身份验证
if is_public_path(path):
return await call_next(request)
if not path.startswith("/api"):
2025-05-02 23:56:59 +08:00
# 非API路径可能是前端路由或静态资源
return await call_next(request)
# # 提取Authorization头
# auth_header = request.headers.get("Authorization")
# if not auth_header or not auth_header.startswith("Bearer "):
# return JSONResponse(
# status_code=status.HTTP_401_UNAUTHORIZED,
# content={"detail": f"请先登录。Path: {path}"},
# headers={"WWW-Authenticate": "Bearer"}
# )
2025-05-02 23:56:59 +08:00
# # 获取token
# token = auth_header.split("Bearer ")[1]
2025-05-02 23:56:59 +08:00
# # 添加token到请求状态后续路由可以直接使用
# request.state.token = token
2025-05-02 23:56:59 +08:00
# 继续处理请求
return await call_next(request)
# 添加鉴权中间件
app.add_middleware(AuthMiddleware)
2024-10-02 20:11:28 +08:00
if __name__ == "__main__":
2025-04-28 22:53:13 +08:00
uvicorn.run(app, host="0.0.0.0", port=5050, threads=10, workers=10, reload=True)
2024-10-02 20:11:28 +08:00