dependencies.py 926 B

1234567891011121314151617181920212223242526
  1. from fastapi import Depends, HTTPException, status
  2. from fastapi.security import OAuth2PasswordBearer
  3. import auth_utils
  4. async def get_current_user(token: str = Depends(auth_utils.oauth2_scheme)):
  5. payload = auth_utils.decode_token(token)
  6. if not payload:
  7. raise HTTPException(
  8. status_code=status.HTTP_401_UNAUTHORIZED,
  9. detail="Could not validate credentials",
  10. headers={"WWW-Authenticate": "Bearer"},
  11. )
  12. return payload
  13. async def require_admin(current_user: dict = Depends(get_current_user)):
  14. if current_user.get("role") != 'admin':
  15. raise HTTPException(
  16. status_code=status.HTTP_403_FORBIDDEN,
  17. detail="Admin role required"
  18. )
  19. return current_user
  20. async def get_current_user_optional(token: str = Depends(auth_utils.oauth2_scheme_optional)):
  21. if not token:
  22. return None
  23. return auth_utils.decode_token(token)