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.

52 lines
1.5 KiB

  1. from datetime import datetime
  2. from typing import Optional
  3. from corvus import db
  4. from corvus.model import User, UserToken
  5. from corvus.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
  15. token
  16. :param enabled: A boolean to indicate whether a token can be considered
  17. eligible for authentication
  18. :param expiration_time: An optional argument to determine when the token
  19. becomes invalid as a means of authentication. Defaults to None, which means
  20. no expiration
  21. :return:
  22. """
  23. token = authentication_service.generate_token()
  24. user_token = UserToken(
  25. user_id=user.id,
  26. token=token.__str__(),
  27. note=note,
  28. enabled=enabled,
  29. creation_time=datetime.now(),
  30. expiration_time=expiration_time,
  31. version=0)
  32. db.session.add(user_token)
  33. db.session.commit()
  34. return user_token
  35. def delete(user_token: UserToken) -> bool:
  36. existing_user_token = db.session.delete(user_token)
  37. if existing_user_token is None:
  38. db.session.commit()
  39. return True
  40. return False
  41. def find_by_user_and_token(user: User, token: str) -> Optional[UserToken]:
  42. return UserToken.query.filter_by(user_id=user.id, token=token).first()