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.

52 lines
1.5 KiB

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