You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

user.py 2.2 KiB

1 vuosi sitten
1 vuosi sitten
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. # Creating a new user in the database
  2. from sqlalchemy.orm import Session
  3. from schemas.user import UserCreate
  4. from db.models.user import User
  5. from core.hashing import Hasher
  6. def create_new_user(user: UserCreate, db: Session):
  7. user_object = User(
  8. Email=user.Email,
  9. Name=user.Name,
  10. MiddleName=user.MiddleName,
  11. LastName=user.LastName,
  12. GovernmentId=user.GovernmentId,
  13. Address=user.Address,
  14. ContactNumber=user.ContactNumber,
  15. Role=user.Role,
  16. HashedPassword=Hasher.get_password_hash(user.Password),
  17. )
  18. db.add(user_object)
  19. db.commit()
  20. db.refresh(user_object)
  21. return user_object
  22. def get_user_by_id(user_id: int, db: Session):
  23. user = db.query(User).filter(User.Id == user_id).first()
  24. return user
  25. def get_user_by_email(email: str, db: Session):
  26. user = db.query(User).filter(User.Email == email).first()
  27. return user
  28. def get_user_by_phone(phone: str, db: Session):
  29. user = db.query(User).filter(User.ContactNumber == phone).first()
  30. return user
  31. def verify_driver_exists(driver_id: int, db: Session):
  32. driver = db.query(User).filter(User.Id == driver_id).first()
  33. if not driver:
  34. return False
  35. if driver.Role != "Driver":
  36. return False
  37. return True
  38. def get_car_driver(vehicle_id: int, db: Session):
  39. driver = db.query(User).filter(User.AssignedVehicle == vehicle_id).first()
  40. if not driver:
  41. return False
  42. return driver
  43. def list_users(db: Session, role: str = "Any"):
  44. users = db.query(User).filter((User.Role == role) | (role == "Any")).all()
  45. return users
  46. def replace_user_data(user_id: int, user_data: UserCreate, db: Session):
  47. user = db.query(User).filter(User.Id == user_id).first()
  48. if not user:
  49. return "userNotFound"
  50. user.Email = user_data.Email
  51. user.Name = user_data.Name
  52. user.MiddleName = user_data.MiddleName
  53. user.LastName = user_data.LastName
  54. user.GovernmentId = user_data.GovernmentId
  55. user.Address = user_data.Address
  56. user.ContactNumber = user_data.ContactNumber
  57. user.Role = user_data.Role
  58. user.HashedPassword = Hasher.get_password_hash(user_data.Password)
  59. db.commit()
  60. db.refresh(user)
  61. return user