2026-04-17 10:49:14 +08:00
|
|
|
from fastapi import Depends, HTTPException, status
|
|
|
|
|
from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
|
|
|
|
|
from jose import JWTError
|
|
|
|
|
|
|
|
|
|
from app.utils.security import decode_access_token
|
|
|
|
|
|
|
|
|
|
security = HTTPBearer(auto_error=False)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
async def get_current_user_id(
|
|
|
|
|
credentials: HTTPAuthorizationCredentials | None = Depends(security),
|
|
|
|
|
) -> int:
|
|
|
|
|
if credentials is None:
|
|
|
|
|
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Missing token")
|
|
|
|
|
|
|
|
|
|
try:
|
|
|
|
|
payload = decode_access_token(credentials.credentials)
|
|
|
|
|
except JWTError as exc:
|
|
|
|
|
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid token") from exc
|
|
|
|
|
|
|
|
|
|
if payload.get("token_type") not in (None, "access"):
|
|
|
|
|
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid token type")
|
|
|
|
|
|
|
|
|
|
user_id = payload.get("user_id")
|
|
|
|
|
if not user_id:
|
|
|
|
|
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid token payload")
|
|
|
|
|
return int(user_id)
|
|
|
|
|
|
|
|
|
|
|
2026-05-17 10:23:02 +08:00
|
|
|
async def get_optional_current_user_id(
|
|
|
|
|
credentials: HTTPAuthorizationCredentials | None = Depends(security),
|
|
|
|
|
) -> int | None:
|
|
|
|
|
if credentials is None:
|
|
|
|
|
return None
|
|
|
|
|
|
|
|
|
|
try:
|
|
|
|
|
payload = decode_access_token(credentials.credentials)
|
|
|
|
|
except JWTError:
|
|
|
|
|
return None
|
|
|
|
|
|
|
|
|
|
if payload.get("token_type") not in (None, "access"):
|
|
|
|
|
return None
|
|
|
|
|
|
|
|
|
|
user_id = payload.get("user_id")
|
|
|
|
|
return int(user_id) if user_id else None
|
|
|
|
|
|
|
|
|
|
|
2026-04-17 10:49:14 +08:00
|
|
|
async def get_current_admin(
|
|
|
|
|
credentials: HTTPAuthorizationCredentials | None = Depends(security),
|
|
|
|
|
) -> dict:
|
|
|
|
|
if credentials is None:
|
|
|
|
|
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Missing token")
|
|
|
|
|
|
|
|
|
|
try:
|
|
|
|
|
payload = decode_access_token(credentials.credentials)
|
|
|
|
|
except JWTError as exc:
|
|
|
|
|
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid token") from exc
|
|
|
|
|
|
|
|
|
|
admin_id = payload.get("admin_id")
|
|
|
|
|
if not admin_id:
|
|
|
|
|
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid admin token")
|
|
|
|
|
|
|
|
|
|
return payload
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
async def require_super_admin(admin_payload: dict = Depends(get_current_admin)) -> dict:
|
|
|
|
|
if int(admin_payload.get("role", 0)) != 2:
|
|
|
|
|
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Super admin required")
|
|
|
|
|
return admin_payload
|