crud_user.py 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. from typing import Any, Dict, Optional, Union
  2. from sqlalchemy.orm import Session
  3. from app.core.security import get_password_hash, verify_password
  4. from app.crud.base import CRUDBase
  5. from app.models.user import User
  6. from app.schemas.user import UserCreate, UserUpdate
  7. class CRUDUser(CRUDBase[User, UserCreate, UserUpdate]):
  8. def get_by_email(self, db: Session, *, email: str) -> Optional[User]:
  9. return db.query(User).filter(User.email == email).first()
  10. def create(self, db: Session, *, obj_in: UserCreate) -> User:
  11. db_obj = User(
  12. email=obj_in.email,
  13. hashed_password=get_password_hash(obj_in.password),
  14. full_name=obj_in.full_name,
  15. is_superuser=obj_in.is_superuser,
  16. )
  17. db.add(db_obj)
  18. db.commit()
  19. db.refresh(db_obj)
  20. return db_obj
  21. def update(
  22. self, db: Session, *, db_obj: User, obj_in: Union[UserUpdate, Dict[str, Any]]
  23. ) -> User:
  24. if isinstance(obj_in, dict):
  25. update_data = obj_in
  26. else:
  27. update_data = obj_in.dict(exclude_unset=True)
  28. if update_data.get("password"):
  29. hashed_password = get_password_hash(update_data["password"])
  30. del update_data["password"]
  31. update_data["hashed_password"] = hashed_password
  32. return super().update(db, db_obj=db_obj, obj_in=update_data)
  33. def authenticate(self, db: Session, *, email: str, password: str) -> Optional[User]:
  34. user = self.get_by_email(db, email=email)
  35. if not user:
  36. return None
  37. if not verify_password(password, user.hashed_password):
  38. return None
  39. return user
  40. def google_auth(self, db: Session, *, email: str) -> Optional[User]:
  41. user = self.get_by_email(db, email=email)
  42. if not user:
  43. return None
  44. return user
  45. def is_active(self, user: User) -> bool:
  46. return user.is_active
  47. def is_superuser(self, user: User) -> bool:
  48. return user.is_superuser
  49. user = CRUDUser(User)