项目初次搭建
This commit is contained in:
23
app/application/app.py
Normal file
23
app/application/app.py
Normal file
@ -0,0 +1,23 @@
|
||||
from fastapi import FastAPI
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
|
||||
from app.application.token_middleware import TokenMiddleware
|
||||
from app.application.logger_middleware import LoggerMiddleware
|
||||
|
||||
my_app = FastAPI()
|
||||
|
||||
|
||||
'''
|
||||
添加CROS中间件,允许跨域请求
|
||||
'''
|
||||
my_app.add_middleware(
|
||||
CORSMiddleware,
|
||||
allow_origins=["*"],
|
||||
allow_credentials=True,
|
||||
allow_methods=["*"],
|
||||
allow_headers=["*"],
|
||||
)
|
||||
|
||||
#注意中间的顺序,这个地方是倒序执行的
|
||||
my_app.add_middleware(LoggerMiddleware)
|
||||
my_app.add_middleware(TokenMiddleware)
|
23
app/application/logger_middleware.py
Normal file
23
app/application/logger_middleware.py
Normal file
@ -0,0 +1,23 @@
|
||||
from starlette.middleware.base import BaseHTTPMiddleware
|
||||
from urllib.request import Request
|
||||
|
||||
from app.common.jwt_check import check_token
|
||||
|
||||
from app.common.logger_config import logger_http
|
||||
|
||||
|
||||
class LoggerMiddleware(BaseHTTPMiddleware):
|
||||
def __init__(self, app):
|
||||
super().__init__(app)
|
||||
|
||||
async def dispatch(self, request: Request, call_next):
|
||||
method = request.method
|
||||
path = request.url.path
|
||||
token = request.headers.get("Authorization")
|
||||
user_id = None
|
||||
if token:
|
||||
decoded_payload = check_token(token)
|
||||
user_id = decoded_payload['user_id']
|
||||
logger_http.info(f"Path: {path},UserId: {user_id}, Method: {method}")
|
||||
response = await call_next(request)
|
||||
return response
|
33
app/application/token_middleware.py
Normal file
33
app/application/token_middleware.py
Normal file
@ -0,0 +1,33 @@
|
||||
from fastapi import status
|
||||
from starlette.middleware.base import BaseHTTPMiddleware
|
||||
from urllib.request import Request
|
||||
from jwt import PyJWTError
|
||||
from common import reponse_code as rc
|
||||
from common import jwt_check as jc
|
||||
|
||||
|
||||
|
||||
class TokenMiddleware(BaseHTTPMiddleware):
|
||||
|
||||
def __init__(self, app):
|
||||
super().__init__(app)
|
||||
|
||||
async def dispatch(self, request: Request, call_next):
|
||||
"""
|
||||
验证token中间件
|
||||
:param request: Request请求
|
||||
:param call_next:
|
||||
:return:
|
||||
"""
|
||||
token = request.headers.get('Authorization')
|
||||
path = request.url.path
|
||||
if '/login' in path:
|
||||
response = await call_next(request)
|
||||
return response
|
||||
if not token:
|
||||
return rc.response_code_view(status.HTTP_401_UNAUTHORIZED, "缺少Token,请重新验证")
|
||||
try:
|
||||
jc.check_token(token)
|
||||
return await call_next(request)
|
||||
except PyJWTError as error:
|
||||
return rc.response_code_view(status.HTTP_401_UNAUTHORIZED, "Token错误或失效,请重新验证")
|
Reference in New Issue
Block a user