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.

126 lines
3.4 KiB

  1. """Service to handle user_token operations."""
  2. import uuid
  3. from datetime import datetime
  4. from typing import Optional, Dict, Callable, Any
  5. from atheneum.db import db
  6. from atheneum.model import User, UserToken
  7. from atheneum.service.serialization_service import (
  8. BaseSerializer,
  9. register_serializer
  10. )
  11. class UserTokenSerializer(BaseSerializer):
  12. """Serialize User model."""
  13. def _serializers(self) -> Dict[str, Callable[[], Any]]:
  14. """Define the fields and the accompanying serializer factory."""
  15. return {
  16. 'token': self.serialize_token,
  17. 'note': self.serialize_note,
  18. 'enabled': self.serialize_enabled,
  19. 'expirationTime': self.serialize_expiration_time,
  20. 'creationTime': self.serialize_creation_time,
  21. 'lastUsageTime': self.serialize_last_usage_time,
  22. 'version': self.serialize_version
  23. }
  24. def serialize_token(self) -> str:
  25. """User token."""
  26. return self.model.token
  27. def serialize_note(self) -> str:
  28. """User token note."""
  29. return self.model.note
  30. def serialize_enabled(self) -> bool:
  31. """User token enabled."""
  32. return self.model.enabled
  33. def serialize_expiration_time(self) -> datetime:
  34. """User token expiration time."""
  35. return self.model.expiration_time
  36. def serialize_creation_time(self) -> datetime:
  37. """User token creation time."""
  38. return self.model.creation_time
  39. def serialize_last_usage_time(self) -> datetime:
  40. """User token last usage time."""
  41. return self.model.last_usage_time
  42. def serialize_version(self) -> int:
  43. """User token version."""
  44. return self.model.version
  45. register_serializer(UserToken.__name__, UserTokenSerializer)
  46. def generate_token() -> uuid.UUID:
  47. """
  48. Generate a unique token.
  49. :return:
  50. """
  51. return uuid.uuid4()
  52. def create(
  53. user: User,
  54. note: Optional[str] = None,
  55. enabled: bool = True,
  56. expiration_time: Optional[datetime] = None) -> UserToken:
  57. """
  58. Create and save a UserToken.
  59. :param user: The User object to bind the token to
  60. :param note: An optional field to store additional information about a
  61. token
  62. :param enabled: A boolean to indicate whether a token can be considered
  63. eligible for authentication
  64. :param expiration_time: An optional argument to determine when the token
  65. becomes invalid as a means of authentication. Defaults to None, which means
  66. no expiration
  67. :return:
  68. """
  69. token = generate_token()
  70. user_token = UserToken(
  71. user_id=user.id,
  72. token=token.__str__(),
  73. note=note,
  74. enabled=enabled,
  75. creation_time=datetime.now(),
  76. expiration_time=expiration_time,
  77. version=0)
  78. db.session.add(user_token)
  79. db.session.commit()
  80. return user_token
  81. def delete(user_token: UserToken) -> bool:
  82. """
  83. Delete a user_token.
  84. :param user_token:
  85. :return:
  86. """
  87. existing_user_token = db.session.delete(user_token)
  88. if existing_user_token is None:
  89. db.session.commit()
  90. return True
  91. return False
  92. def find_by_user_and_token(user: User, token: str) -> Optional[UserToken]:
  93. """
  94. Lookup a user_token by user and token string.
  95. :param user:
  96. :param token:
  97. :return:
  98. """
  99. return UserToken.query.filter_by(user_id=user.id, token=token).first()