An ebook/comic library service and web client
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.

84 lines
1.9 KiB

  1. """
  2. Service to handle user operations
  3. """
  4. from datetime import datetime
  5. from typing import Optional
  6. from atheneum import APP, db
  7. from atheneum.model import User
  8. from atheneum.service import authentication_service
  9. def register(name: str, password: str, role: str) -> User:
  10. """
  11. Register a new user
  12. :param name: Desired user name. Must be unique and not already registered
  13. :param password: Password to be hashed and stored for the user
  14. :param role: Role to assign the user [ROLE_USER, ROLE_ADMIN]
  15. :return:
  16. """
  17. pw_hash, pw_revision = authentication_service.get_password_hash(password)
  18. new_user = User(
  19. name=name,
  20. role=role,
  21. password_hash=pw_hash,
  22. password_revision=pw_revision,
  23. creation_time=datetime.now(),
  24. version=0)
  25. db.session.add(new_user)
  26. db.session.commit()
  27. APP.logger.info('Registered new user: %s with role: %s', name, role)
  28. return new_user
  29. def delete(user: User) -> bool:
  30. """
  31. Delete a user
  32. :param user:
  33. :return:
  34. """
  35. existing_user = db.session.delete(user)
  36. if existing_user is None:
  37. db.session.commit()
  38. return True
  39. return False
  40. def update_last_login_time(user: User) -> None:
  41. """
  42. Bump the last login time for the user
  43. :param user:
  44. :return:
  45. """
  46. user.last_login_time = datetime.now()
  47. db.session.commit()
  48. def update_password(user: User, password: str) -> None:
  49. """
  50. Change the user password
  51. :param user:
  52. :param password:
  53. :return:
  54. """
  55. pw_hash, pw_revision = authentication_service.get_password_hash(
  56. password)
  57. user.password_hash = pw_hash
  58. user.password_revision = pw_revision
  59. db.session.commit()
  60. def find_by_name(name: str) -> Optional[User]:
  61. """
  62. Find a user by name
  63. :param name:
  64. :return:
  65. """
  66. return User.query.filter_by(name=name).first()