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.

68 lines
1.7 KiB

  1. """
  2. Service to handle user_token operations
  3. """
  4. from datetime import datetime
  5. from typing import Optional
  6. from atheneum import db
  7. from atheneum.model import User, UserToken
  8. from atheneum.service import authentication_service
  9. def create(
  10. user: User,
  11. note: Optional[str] = None,
  12. enabled: bool = True,
  13. expiration_time: Optional[datetime] = None) -> UserToken:
  14. """
  15. Create and save a UserToken
  16. :param user: The User object to bind the token to
  17. :param note: An optional field to store additional information about a
  18. token
  19. :param enabled: A boolean to indicate whether a token can be considered
  20. eligible for authentication
  21. :param expiration_time: An optional argument to determine when the token
  22. becomes invalid as a means of authentication. Defaults to None, which means
  23. no expiration
  24. :return:
  25. """
  26. token = authentication_service.generate_token()
  27. user_token = UserToken(
  28. user_id=user.id,
  29. token=token.__str__(),
  30. note=note,
  31. enabled=enabled,
  32. creation_time=datetime.now(),
  33. expiration_time=expiration_time,
  34. version=0)
  35. db.session.add(user_token)
  36. db.session.commit()
  37. return user_token
  38. def delete(user_token: UserToken) -> bool:
  39. """
  40. Delete a user_token
  41. :param user_token:
  42. :return:
  43. """
  44. existing_user_token = db.session.delete(user_token)
  45. if existing_user_token is None:
  46. db.session.commit()
  47. return True
  48. return False
  49. def find_by_user_and_token(user: User, token: str) -> Optional[UserToken]:
  50. """
  51. Lookup a user_token by user and token string
  52. :param user:
  53. :param token:
  54. :return:
  55. """
  56. return UserToken.query.filter_by(user_id=user.id, token=token).first()