deps.py 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. from typing import Generator
  2. from fastapi import Depends, HTTPException, status
  3. from fastapi.security import OAuth2PasswordBearer
  4. from jose import jwt
  5. from pydantic import ValidationError
  6. from sqlalchemy.orm import Session
  7. from app import crud, models, schemas
  8. from app.core import security
  9. from app.core.config import settings
  10. from app.db.session import SessionLocal
  11. reusable_oauth2 = OAuth2PasswordBearer(
  12. tokenUrl=f"{settings.API_V1_STR}/login/access-token"
  13. )
  14. def get_db() -> Generator:
  15. try:
  16. db = SessionLocal()
  17. yield db
  18. finally:
  19. db.close()
  20. def get_current_user(
  21. db: Session = Depends(get_db), token: str = Depends(reusable_oauth2)
  22. ) -> models.User:
  23. try:
  24. payload = jwt.decode(
  25. token, settings.SECRET_KEY, algorithms=[security.ALGORITHM]
  26. )
  27. token_data = schemas.TokenPayload(**payload)
  28. except (jwt.JWTError, ValidationError):
  29. raise HTTPException(
  30. status_code=status.HTTP_403_FORBIDDEN,
  31. detail="Could not validate credentials",
  32. )
  33. user = crud.user.get(db, id=token_data.sub)
  34. if not user:
  35. raise HTTPException(status_code=404, detail="User not found")
  36. return user
  37. def get_current_active_user(
  38. current_user: models.User = Depends(get_current_user),
  39. ) -> models.User:
  40. if not crud.user.is_active(current_user):
  41. raise HTTPException(status_code=400, detail="Inactive user")
  42. return current_user
  43. def get_current_active_superuser(
  44. current_user: models.User = Depends(get_current_user),
  45. ) -> models.User:
  46. if not crud.user.is_superuser(current_user):
  47. raise HTTPException(
  48. status_code=400, detail="The user doesn't have enough privileges"
  49. )
  50. return current_user