A multipurpose python flask API server and administration SPA
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.

75 lines
1.8 KiB

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