xbackend/main.py
2021-04-28 20:20:19 +08:00

46 lines
1.3 KiB
Python

import time
import uvicorn
from fastapi import FastAPI, Request, Depends
from starlette.middleware.cors import CORSMiddleware
from fastapi.responses import JSONResponse
from api.api_v1.api import api_router
from api.deps import get_current_user
from core.config import settings
app = FastAPI(title=settings.PROJECT_NAME, openapi_url=f"{settings.API_V1_STR}/openapi.json")
allow_anonymous = [f'{settings.API_V1_STR}/{page}' for page in settings.ALLOW_ANONYMOUS]
allow_anonymous.extend(['/docs'])
@app.middleware("http")
async def add_jwt_auth(request: Request, call_next):
fail = {'code': -1, 'msg': '身份验证失败'}
if request.scope.get('path') not in allow_anonymous:
token = request.headers.get("Authorization")
try:
user = get_current_user(token)
except:
return JSONResponse(fail)
#
# request.state.user = user
response = await call_next(request)
return response
if settings.BACKEND_CORS_ORIGINS:
app.add_middleware(
CORSMiddleware,
allow_origins=['*'],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
app.include_router(api_router, prefix=settings.API_V1_STR)
if __name__ == '__main__':
uvicorn.run(app='main:app', host="0.0.0.0", port=8888, reload=True, debug=True)