A multipurpose python flask API server and administration SPA
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.

86 lines
1.9 KiB

  1. """Service to handle user operations."""
  2. import logging
  3. from datetime import datetime
  4. from typing import Optional
  5. from corvus.db import db
  6. from corvus.model import User
  7. from corvus.utility import authentication_utility
  8. LOGGER = logging.getLogger(__name__)
  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_utility.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. 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. if user is not None:
  47. user.last_login_time = datetime.now()
  48. db.session.commit()
  49. def update_password(user: User, password: str) -> None:
  50. """
  51. Change the user password.
  52. :param user:
  53. :param password:
  54. :return:
  55. """
  56. pw_hash, pw_revision = authentication_utility.get_password_hash(
  57. password)
  58. user.password_hash = pw_hash
  59. user.password_revision = pw_revision
  60. db.session.commit()
  61. def find_by_name(name: str) -> Optional[User]:
  62. """
  63. Find a user by name.
  64. :param name:
  65. :return:
  66. """
  67. return User.query.filter_by(name=name).first()