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