|
|
@@ -1,11 +1,12 @@
|
|
|
"""FastAPI 依赖:当前用户与菜单权限校验"""
|
|
|
from typing import Annotated, Callable
|
|
|
|
|
|
-from fastapi import Depends, HTTPException
|
|
|
+from fastapi import Depends
|
|
|
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
|
|
|
from sqlalchemy.orm import Session
|
|
|
|
|
|
from app.core.database import get_db
|
|
|
+from app.core.response import AppHTTPError
|
|
|
from app.core.security import TokenError, safe_decode_token
|
|
|
from app.crud import menu as menu_crud
|
|
|
from app.crud import user as user_crud
|
|
|
@@ -19,17 +20,17 @@ def get_current_user(
|
|
|
creds: Annotated[HTTPAuthorizationCredentials | None, Depends(bearer_scheme)],
|
|
|
) -> SysUser:
|
|
|
if creds is None or not creds.credentials:
|
|
|
- raise HTTPException(status_code=401, detail="未登录或令牌无效")
|
|
|
+ raise AppHTTPError(401, "未登录或令牌无效")
|
|
|
try:
|
|
|
payload = safe_decode_token(creds.credentials)
|
|
|
except TokenError:
|
|
|
- raise HTTPException(status_code=401, detail="未登录或令牌无效") from None
|
|
|
+ raise AppHTTPError(401, "未登录或令牌无效") from None
|
|
|
user_id = payload.get("sub")
|
|
|
if not user_id:
|
|
|
- raise HTTPException(status_code=401, detail="未登录或令牌无效")
|
|
|
+ raise AppHTTPError(401, "未登录或令牌无效")
|
|
|
user = user_crud.get_user_by_id(db, user_id)
|
|
|
if not user or user.status != "0":
|
|
|
- raise HTTPException(status_code=401, detail="未登录或令牌无效")
|
|
|
+ raise AppHTTPError(401, "未登录或令牌无效")
|
|
|
return user
|
|
|
|
|
|
|
|
|
@@ -42,7 +43,7 @@ def require_menu(*codes: str) -> Callable:
|
|
|
db: Annotated[Session, Depends(get_db)],
|
|
|
) -> SysUser:
|
|
|
if not menu_crud.role_has_any_menu_code(db, user.role_id, needed):
|
|
|
- raise HTTPException(status_code=403, detail="无权限")
|
|
|
+ raise AppHTTPError(403, "无权限")
|
|
|
return user
|
|
|
|
|
|
return _dep
|