deps.py 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. from collections.abc import Generator
  2. from typing import Annotated
  3. from app.common import security
  4. from app.config import settings
  5. from app.extensions.db import engine
  6. from app.models.models import TokenPayload
  7. from app.models.user import User
  8. from jose import JWTError, jwt
  9. from pydantic import ValidationError, EmailStr, Field, field_validator
  10. from sqlmodel import Session
  11. from fastapi import Depends, HTTPException, status
  12. from fastapi.security import OAuth2PasswordBearer
  13. reusable_oauth2 = OAuth2PasswordBearer(
  14. tokenUrl=f"{settings.API_V1_STR}/login/access-token"
  15. )
  16. def get_db() -> Generator[Session, None, None]:
  17. """
  18. 返回数据库对象
  19. """
  20. with Session(engine) as session:
  21. yield session
  22. SessionDep = Annotated[Session, Depends(get_db)]
  23. TokenDep = Annotated[str, Depends(reusable_oauth2)]
  24. def get_current_user(session: SessionDep, token: TokenDep) -> User:
  25. try:
  26. payload = jwt.decode(
  27. token, settings.SECRET_KEY, algorithms=[security.ALGORITHM]
  28. )
  29. token_data = TokenPayload(**payload)
  30. except (JWTError, ValidationError):
  31. raise HTTPException(
  32. status_code=status.HTTP_403_FORBIDDEN,
  33. detail="Could not validate credentials",
  34. )
  35. user = session.get(User, token_data.sub)
  36. if not user:
  37. raise HTTPException(status_code=404, detail="User not found")
  38. if not user.is_active:
  39. raise HTTPException(status_code=400, detail="Inactive user")
  40. return user
  41. # 在使用 CurrentUser 依赖时,会调用 get_current_user 函数来获取当前用户对象,并将其作为 User 类型的参数传递给依赖项
  42. CurrentUser = Annotated[User, Depends(get_current_user)]
  43. def get_current_active_superuser(current_user: CurrentUser) -> User:
  44. if not current_user.is_superuser:
  45. raise HTTPException(
  46. status_code=400, detail="The user doesn't have enough privileges"
  47. )
  48. return current_user