重构后端服务架构并优化前端错误处理
This commit is contained in:
0
fastapi-backend/app/middleware/__init__.py
Normal file
0
fastapi-backend/app/middleware/__init__.py
Normal file
39
fastapi-backend/app/middleware/auth.py
Normal file
39
fastapi-backend/app/middleware/auth.py
Normal file
@@ -0,0 +1,39 @@
|
||||
from fastapi import HTTPException, status, Depends
|
||||
from fastapi.security import OAuth2PasswordBearer
|
||||
from sqlalchemy.orm import Session
|
||||
from app.db.database import get_db
|
||||
from app.models.user import User
|
||||
from app.core.security import decode_access_token
|
||||
|
||||
oauth2_scheme = OAuth2PasswordBearer(tokenUrl="api/auth/login")
|
||||
|
||||
def get_current_user(token: str = Depends(oauth2_scheme), db: Session = Depends(get_db)):
|
||||
credentials_exception = HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Could not validate credentials",
|
||||
headers={"WWW-Authenticate": "Bearer"},
|
||||
)
|
||||
|
||||
payload = decode_access_token(token)
|
||||
if payload is None:
|
||||
raise credentials_exception
|
||||
|
||||
uuid: str = payload.get("sub")
|
||||
if uuid is None:
|
||||
raise credentials_exception
|
||||
|
||||
user = db.query(User).filter(User.uuid == uuid).first()
|
||||
if user is None:
|
||||
raise credentials_exception
|
||||
|
||||
return user
|
||||
|
||||
def require_role(required_role: str):
|
||||
def role_checker(current_user: User = Depends(get_current_user)):
|
||||
if current_user.user_type != required_role:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Insufficient permissions",
|
||||
)
|
||||
return current_user
|
||||
return role_checker
|
||||
25
fastapi-backend/app/middleware/error_handler.py
Normal file
25
fastapi-backend/app/middleware/error_handler.py
Normal file
@@ -0,0 +1,25 @@
|
||||
from fastapi import HTTPException, Request
|
||||
from fastapi.responses import JSONResponse
|
||||
from app.utils.response import ErrorResponse
|
||||
|
||||
async def error_handler(request: Request, exc: Exception):
|
||||
# Handle HTTP exceptions
|
||||
if isinstance(exc, HTTPException):
|
||||
return JSONResponse(
|
||||
status_code=exc.status_code,
|
||||
content=ErrorResponse(
|
||||
code=exc.status_code,
|
||||
message=exc.detail,
|
||||
data=None
|
||||
).dict()
|
||||
)
|
||||
|
||||
# Handle general exceptions
|
||||
return JSONResponse(
|
||||
status_code=500,
|
||||
content=ErrorResponse(
|
||||
code=500,
|
||||
message="Internal Server Error",
|
||||
data=str(exc)
|
||||
).dict()
|
||||
)
|
||||
Reference in New Issue
Block a user