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.

230 lines
6.5 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, Tuple
  7. from iso8601 import iso8601
  8. from atheneum import errors
  9. from atheneum.db import db
  10. from atheneum.model import User
  11. from atheneum.service import role_service
  12. from atheneum.service.transformation_service import (
  13. BaseTransformer,
  14. register_transformer
  15. )
  16. from atheneum.service.validation_service import (
  17. BaseValidator,
  18. register_validator
  19. )
  20. from atheneum.utility import authentication_utility
  21. LOGGER = logging.getLogger(__name__)
  22. @register_transformer
  23. class UserTransformer(BaseTransformer):
  24. """Serialize User model."""
  25. type = User
  26. def _deserializers(
  27. self) -> Dict[str, Callable[[User, Any], None]]:
  28. """Define the fields and the accompanying deserializer factory."""
  29. return {
  30. 'name': self.deserialize_name,
  31. 'creationTime': self.deserialize_creation_time,
  32. 'lastLoginTime': self.deserialize_last_login_time,
  33. 'version': self.deserialize_version,
  34. 'role': self.deserialize_role,
  35. }
  36. def _serializers(self) -> Dict[str, Callable[[], Any]]:
  37. """Define the fields and the accompanying serializer factory."""
  38. return {
  39. 'name': self.serialize_name,
  40. 'creationTime': self.serialize_creation_time,
  41. 'lastLoginTime': self.serialize_last_login_time,
  42. 'version': self.serialize_version,
  43. 'role': self.serialize_role,
  44. }
  45. def serialize_name(self) -> str:
  46. """User name."""
  47. return self.model.name
  48. @staticmethod
  49. def deserialize_name(model: User, name: str) -> None:
  50. """User name."""
  51. model.name = name
  52. def serialize_creation_time(self) -> datetime:
  53. """User creation time."""
  54. return self.model.creation_time
  55. @staticmethod
  56. def deserialize_creation_time(
  57. model: User, creation_time: datetime) -> None:
  58. """User creation time."""
  59. model.creation_time = iso8601.parse_date(creation_time)
  60. def serialize_last_login_time(self) -> datetime:
  61. """User last login time."""
  62. return self.model.last_login_time
  63. @staticmethod
  64. def deserialize_last_login_time(
  65. model: User, last_login_time: datetime) -> None:
  66. """User last login time."""
  67. model.last_login_time = iso8601.parse_date(last_login_time)
  68. def serialize_version(self) -> int:
  69. """User version."""
  70. return self.model.version
  71. @staticmethod
  72. def deserialize_version(model: User, version: int) -> None:
  73. """User version."""
  74. model.version = version
  75. def serialize_role(self) -> str:
  76. """User role."""
  77. return self.model.role.value
  78. @staticmethod
  79. def deserialize_role(model: User, role_value: str) -> None:
  80. """User role."""
  81. model.role = role_service.Role(role_value)
  82. @register_validator
  83. class UserValidator(BaseValidator):
  84. """Validate User model."""
  85. type = User
  86. def _validators(
  87. self) -> Dict[str, Callable[[Any], Tuple[bool, str]]]:
  88. return {
  89. 'id': self.no_validation,
  90. 'name': self.validate_name,
  91. 'role': self.validate_role,
  92. 'password_hash': self.no_validation,
  93. 'password_revision': self.no_validation,
  94. 'creation_time': self.no_validation,
  95. 'last_login_time': self.no_validation,
  96. 'version': self.validate_version
  97. }
  98. def validate_name(self, new_name: Any) -> Tuple[bool, str]:
  99. """
  100. Name changes are only allowed to be performed by an Admin.
  101. :param new_name:
  102. :return:
  103. """
  104. validation_result = (self.request_user.role == role_service.Role.ADMIN
  105. or new_name is None)
  106. if validation_result:
  107. return validation_result, ''
  108. return (validation_result,
  109. 'Names can only be changed by an administrator')
  110. def validate_role(self, new_role: Any) -> Tuple[bool, str]:
  111. """
  112. Roles can only be increased to the level of the request_user.
  113. :param new_role:
  114. :return:
  115. """
  116. acceptable_roles = role_service.ROLES.find_children_roles(
  117. self.request_user.role)
  118. role = new_role if new_role is not None else self.model.role
  119. if role in acceptable_roles:
  120. return True, ''
  121. return False, 'Role escalation is not permitted'
  122. def find_by_name(name: str) -> Optional[User]:
  123. """
  124. Find a user by name.
  125. :param name:
  126. :return:
  127. """
  128. return User.query.filter_by(name=name).first()
  129. def register(name: str, password: Optional[str], role: Optional[str]) -> User:
  130. """
  131. Register a new user.
  132. :param name: Desired user name. Must be unique and not already registered
  133. :param password: Password to be hashed and stored for the user
  134. :param role: Role to assign the user [ROLE_USER, ROLE_ADMIN]
  135. :return:
  136. """
  137. password = password if password is not None else ''.join(
  138. random.choices(string.ascii_letters + string.digits, k=32))
  139. role = role if role is not None else User.ROLE_USER
  140. if find_by_name(name=name) is not None:
  141. raise errors.ValidationError('User name is already taken.')
  142. pw_hash, pw_revision = authentication_utility.get_password_hash(password)
  143. new_user = User(
  144. name=name,
  145. role=role,
  146. password_hash=pw_hash,
  147. password_revision=pw_revision,
  148. creation_time=datetime.now(),
  149. version=0)
  150. db.session.add(new_user)
  151. db.session.commit()
  152. LOGGER.info('Registered new user: %s with role: %s', name, role)
  153. return new_user
  154. def delete(user: User) -> bool:
  155. """
  156. Delete a user.
  157. :param user:
  158. :return:
  159. """
  160. existing_user = db.session.delete(user)
  161. if existing_user is None:
  162. db.session.commit()
  163. return True
  164. return False
  165. def update_last_login_time(user: User) -> None:
  166. """
  167. Bump the last login time for the user.
  168. :param user:
  169. :return:
  170. """
  171. if user is not None:
  172. user.last_login_time = datetime.now()
  173. db.session.commit()
  174. def update_password(user: User, password: str) -> None:
  175. """
  176. Change the user password.
  177. :param user:
  178. :param password:
  179. :return:
  180. """
  181. pw_hash, pw_revision = authentication_utility.get_password_hash(
  182. password)
  183. user.password_hash = pw_hash
  184. user.password_revision = pw_revision
  185. db.session.commit()