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.

178 lines
4.8 KiB

  1. """Service to handle user operations."""
  2. import logging
  3. import random
  4. import string
  5. from datetime import datetime
  6. from typing import Optional, Dict, Callable, Any
  7. from corvus import errors
  8. from corvus.db import db
  9. from corvus.model import User
  10. from corvus.service.role_service import Role
  11. from corvus.service.transformation_service import (
  12. BaseTransformer,
  13. register_transformer
  14. )
  15. from corvus.utility import authentication_utility
  16. LOGGER = logging.getLogger(__name__)
  17. class UserTransformer(BaseTransformer):
  18. """Serialize User model."""
  19. type = User
  20. def _deserializers(
  21. self) -> Dict[str, Callable[[User, Any], None]]:
  22. """Define the fields and the accompanying deserializer factory."""
  23. return {
  24. 'name': self.deserialize_name,
  25. 'creationTime': self.deserialize_creation_time,
  26. 'lastLoginTime': self.deserialize_last_login_time,
  27. 'version': self.deserialize_version,
  28. 'role': self.deserialize_role,
  29. }
  30. def _serializers(self) -> Dict[str, Callable[[], Any]]:
  31. """Define the fields and the accompanying serializer factory."""
  32. return {
  33. 'name': self.serialize_name,
  34. 'creationTime': self.serialize_creation_time,
  35. 'lastLoginTime': self.serialize_last_login_time,
  36. 'version': self.serialize_version,
  37. 'role': self.serialize_role,
  38. }
  39. def serialize_name(self) -> str:
  40. """User name."""
  41. return self.model.name
  42. @staticmethod
  43. def deserialize_name(model: User, name: str) -> None:
  44. """User name."""
  45. model.name = name
  46. def serialize_creation_time(self) -> datetime:
  47. """User creation time."""
  48. return self.model.creation_time
  49. @staticmethod
  50. def deserialize_creation_time(
  51. model: User, creation_time: datetime) -> None:
  52. """User creation time."""
  53. model.creation_time = creation_time
  54. def serialize_last_login_time(self) -> datetime:
  55. """User last login time."""
  56. return self.model.last_login_time
  57. @staticmethod
  58. def deserialize_last_login_time(
  59. model: User, last_login_time: datetime) -> None:
  60. """User last login time."""
  61. model.last_login_time = last_login_time
  62. def serialize_version(self) -> int:
  63. """User version."""
  64. return self.model.version
  65. @staticmethod
  66. def deserialize_version(model: User, version: int) -> None:
  67. """User version."""
  68. model.version = version
  69. def serialize_role(self) -> str:
  70. """User role."""
  71. return self.model.role.value
  72. @staticmethod
  73. def deserialize_role(model: User, role_value: str) -> None:
  74. """User role."""
  75. model.role = Role(role_value)
  76. register_transformer(User.__name__, UserTransformer)
  77. def find_by_name(name: str) -> Optional[User]:
  78. """
  79. Find a user by name.
  80. :param name:
  81. :return:
  82. """
  83. return User.query.filter_by(name=name).first()
  84. def register(name: str, password: Optional[str], role: Optional[str]) -> User:
  85. """
  86. Register a new user.
  87. :param name: Desired user name. Must be unique and not already registered
  88. :param password: Password to be hashed and stored for the user
  89. :param role: Role to assign the user [ROLE_USER, ROLE_ADMIN]
  90. :return:
  91. """
  92. password = password if password is not None else ''.join(
  93. random.choices(string.ascii_letters + string.digits, k=32))
  94. role = role if role is not None else User.ROLE_USER
  95. if find_by_name(name=name) is not None:
  96. raise errors.ValidationError('User name is already taken.')
  97. pw_hash, pw_revision = authentication_utility.get_password_hash(password)
  98. new_user = User(
  99. name=name,
  100. role=role,
  101. password_hash=pw_hash,
  102. password_revision=pw_revision,
  103. creation_time=datetime.now(),
  104. version=0)
  105. db.session.add(new_user)
  106. db.session.commit()
  107. LOGGER.info('Registered new user: %s with role: %s', name, role)
  108. return new_user
  109. def delete(user: User) -> bool:
  110. """
  111. Delete a user.
  112. :param user:
  113. :return:
  114. """
  115. existing_user = db.session.delete(user)
  116. if existing_user is None:
  117. db.session.commit()
  118. return True
  119. return False
  120. def update_last_login_time(user: User) -> None:
  121. """
  122. Bump the last login time for the user.
  123. :param user:
  124. :return:
  125. """
  126. if user is not None:
  127. user.last_login_time = datetime.now()
  128. db.session.commit()
  129. def update_password(user: User, password: str) -> None:
  130. """
  131. Change the user password.
  132. :param user:
  133. :param password:
  134. :return:
  135. """
  136. pw_hash, pw_revision = authentication_utility.get_password_hash(
  137. password)
  138. user.password_hash = pw_hash
  139. user.password_revision = pw_revision
  140. db.session.commit()