crud_creator.py 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  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.creator import Creator
  6. from app.schemas.creator import CreatorCreate, CreatorUpdate
  7. class CRUDUser(CRUDBase[Creator, CreatorCreate, CreatorUpdate]):
  8. def get_by_email(self, db: Session, *, email: str) -> Optional[Creator]:
  9. return db.query(Creator).filter(Creator.email == email).first()
  10. def get_by_account(self, db: Session, *, account: str) -> Optional[Creator]:
  11. return db.query(Creator).filter(Creator.account == account).first()
  12. def create(self, db: Session, *, obj_in: CreatorCreate) -> Creator:
  13. db_obj = Creator(
  14. email=obj_in.email,
  15. account=obj_in.account,
  16. phone=obj_in.phone,
  17. is_active=obj_in.is_active,
  18. nick_name=obj_in.nick_name,
  19. brief_introduction=obj_in.brief_introduction,
  20. work_experience=obj_in.work_experience,
  21. case_type=obj_in.case_type,
  22. pwd=get_password_hash(obj_in.pwd)
  23. )
  24. db.add(db_obj)
  25. db.commit()
  26. db.refresh(db_obj)
  27. return db_obj
  28. def update(
  29. self, db: Session, *, db_obj: Creator,
  30. obj_in: Union[CreatorUpdate, Dict[str, Any]]
  31. ) -> Creator:
  32. if isinstance(obj_in, dict):
  33. update_data = obj_in
  34. else:
  35. update_data = obj_in.dict(exclude_unset=True)
  36. if update_data["pwd"]:
  37. hashed_password = get_password_hash(update_data["pwd"])
  38. del update_data["pwd"]
  39. update_data["pwd"] = hashed_password
  40. return super().update(db, db_obj=db_obj, obj_in=update_data)
  41. def authenticate(self, db: Session, *, account: str, password: str) -> Optional[Creator]:
  42. creator = self.get_by_account(db, account=account)
  43. if not creator:
  44. return None
  45. if not verify_password(password, creator.pwd):
  46. return None
  47. return creator
  48. def is_active(self, creator: Creator) -> bool:
  49. return creator.is_active
  50. def is_superuser(self, creator: Creator) -> bool:
  51. return creator.is_superuser
  52. creator = CRUDUser(Creator)