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.

74 lines
1.7 KiB

  1. import uuid
  2. from datetime import datetime
  3. from typing import Optional, Tuple
  4. from nacl import pwhash
  5. from nacl.exceptions import InvalidkeyError
  6. from atheneum.model import User, UserToken
  7. from atheneum.service import user_service, user_token_service
  8. def generate_token() -> uuid.UUID:
  9. return uuid.uuid4()
  10. def get_password_hash(password: str) -> Tuple[str, int]:
  11. """
  12. Retrieve argon2id password hash.
  13. :param password: plaintext password to convert
  14. :return: Tuple[password_hash, password_revision]
  15. """
  16. return pwhash.argon2id.str(password.encode('utf8')).decode('utf8'), 1
  17. def is_valid_password(user: User, password: str) -> bool:
  18. assert user
  19. try:
  20. return pwhash.verify(
  21. user.password_hash.encode('utf8'), password.encode('utf8'))
  22. except InvalidkeyError:
  23. pass
  24. return False
  25. def is_valid_token(user_token: Optional[UserToken]) -> bool:
  26. """
  27. Token must be enabled and if it has an expiration, it must be
  28. greater than now.
  29. :param user_token:
  30. :return:
  31. """
  32. if user_token is None:
  33. return False
  34. if not user_token.enabled:
  35. return False
  36. if (user_token.expiration_time is not None
  37. and user_token.expiration_time < datetime.utcnow()):
  38. return False
  39. return True
  40. def bump_login(user: Optional[User]):
  41. """
  42. Update the last login time for the user
  43. :param user:
  44. :return:
  45. """
  46. if user is not None:
  47. user_service.update_last_login_time(user)
  48. def logout(user_token: Optional[UserToken] = None):
  49. """
  50. Remove a user_token associated with a client session
  51. :param user_token:
  52. :return:
  53. """
  54. if user_token is not None:
  55. user_token_service.delete(user_token)