mixins.py 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. class UserMixin:
  2. """
  3. This provides default implementations for the methods that Flask-Login
  4. expects user objects to have.
  5. """
  6. # Python 3 implicitly set __hash__ to None if we override __eq__
  7. # We set it back to its default implementation
  8. __hash__ = object.__hash__
  9. @property
  10. def is_active(self):
  11. return True
  12. @property
  13. def is_authenticated(self):
  14. return self.is_active
  15. @property
  16. def is_anonymous(self):
  17. return False
  18. def get_id(self):
  19. try:
  20. return str(self.id)
  21. except AttributeError:
  22. raise NotImplementedError("No `id` attribute - override `get_id`") from None
  23. def __eq__(self, other):
  24. """
  25. Checks the equality of two `UserMixin` objects using `get_id`.
  26. """
  27. if isinstance(other, UserMixin):
  28. return self.get_id() == other.get_id()
  29. return NotImplemented
  30. def __ne__(self, other):
  31. """
  32. Checks the inequality of two `UserMixin` objects using `get_id`.
  33. """
  34. equal = self.__eq__(other)
  35. if equal is NotImplemented:
  36. return NotImplemented
  37. return not equal
  38. class AnonymousUserMixin:
  39. """
  40. This is the default object for representing an anonymous user.
  41. """
  42. @property
  43. def is_authenticated(self):
  44. return False
  45. @property
  46. def is_active(self):
  47. return False
  48. @property
  49. def is_anonymous(self):
  50. return True
  51. def get_id(self):
  52. return