base_user.py 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164
  1. """
  2. This module allows importing AbstractBaseUser even when django.contrib.auth is
  3. not in INSTALLED_APPS.
  4. """
  5. import unicodedata
  6. from django.conf import settings
  7. from django.contrib.auth import password_validation
  8. from django.contrib.auth.hashers import (
  9. acheck_password,
  10. check_password,
  11. is_password_usable,
  12. make_password,
  13. )
  14. from django.db import models
  15. from django.utils.crypto import salted_hmac
  16. from django.utils.translation import gettext_lazy as _
  17. class BaseUserManager(models.Manager):
  18. @classmethod
  19. def normalize_email(cls, email):
  20. """
  21. Normalize the email address by lowercasing the domain part of it.
  22. """
  23. email = email or ""
  24. try:
  25. email_name, domain_part = email.strip().rsplit("@", 1)
  26. except ValueError:
  27. pass
  28. else:
  29. email = email_name + "@" + domain_part.lower()
  30. return email
  31. def get_by_natural_key(self, username):
  32. return self.get(**{self.model.USERNAME_FIELD: username})
  33. class AbstractBaseUser(models.Model):
  34. password = models.CharField(_("password"), max_length=128)
  35. last_login = models.DateTimeField(_("last login"), blank=True, null=True)
  36. is_active = True
  37. REQUIRED_FIELDS = []
  38. # Stores the raw password if set_password() is called so that it can
  39. # be passed to password_changed() after the model is saved.
  40. _password = None
  41. class Meta:
  42. abstract = True
  43. def __str__(self):
  44. return self.get_username()
  45. # RemovedInDjango60Warning: When the deprecation ends, replace with:
  46. # def save(self, **kwargs):
  47. # super().save(**kwargs)
  48. def save(self, *args, **kwargs):
  49. super().save(*args, **kwargs)
  50. if self._password is not None:
  51. password_validation.password_changed(self._password, self)
  52. self._password = None
  53. def get_username(self):
  54. """Return the username for this User."""
  55. return getattr(self, self.USERNAME_FIELD)
  56. def clean(self):
  57. setattr(self, self.USERNAME_FIELD, self.normalize_username(self.get_username()))
  58. def natural_key(self):
  59. return (self.get_username(),)
  60. @property
  61. def is_anonymous(self):
  62. """
  63. Always return False. This is a way of comparing User objects to
  64. anonymous users.
  65. """
  66. return False
  67. @property
  68. def is_authenticated(self):
  69. """
  70. Always return True. This is a way to tell if the user has been
  71. authenticated in templates.
  72. """
  73. return True
  74. def set_password(self, raw_password):
  75. self.password = make_password(raw_password)
  76. self._password = raw_password
  77. def check_password(self, raw_password):
  78. """
  79. Return a boolean of whether the raw_password was correct. Handles
  80. hashing formats behind the scenes.
  81. """
  82. def setter(raw_password):
  83. self.set_password(raw_password)
  84. # Password hash upgrades shouldn't be considered password changes.
  85. self._password = None
  86. self.save(update_fields=["password"])
  87. return check_password(raw_password, self.password, setter)
  88. async def acheck_password(self, raw_password):
  89. """See check_password()."""
  90. async def setter(raw_password):
  91. self.set_password(raw_password)
  92. # Password hash upgrades shouldn't be considered password changes.
  93. self._password = None
  94. await self.asave(update_fields=["password"])
  95. return await acheck_password(raw_password, self.password, setter)
  96. def set_unusable_password(self):
  97. # Set a value that will never be a valid hash
  98. self.password = make_password(None)
  99. def has_usable_password(self):
  100. """
  101. Return False if set_unusable_password() has been called for this user.
  102. """
  103. return is_password_usable(self.password)
  104. def get_session_auth_hash(self):
  105. """
  106. Return an HMAC of the password field.
  107. """
  108. return self._get_session_auth_hash()
  109. def get_session_auth_fallback_hash(self):
  110. for fallback_secret in settings.SECRET_KEY_FALLBACKS:
  111. yield self._get_session_auth_hash(secret=fallback_secret)
  112. def _get_session_auth_hash(self, secret=None):
  113. key_salt = "django.contrib.auth.models.AbstractBaseUser.get_session_auth_hash"
  114. return salted_hmac(
  115. key_salt,
  116. self.password,
  117. secret=secret,
  118. algorithm="sha256",
  119. ).hexdigest()
  120. @classmethod
  121. def get_email_field_name(cls):
  122. try:
  123. return cls.EMAIL_FIELD
  124. except AttributeError:
  125. return "email"
  126. @classmethod
  127. def normalize_username(cls, username):
  128. return (
  129. unicodedata.normalize("NFKC", username)
  130. if isinstance(username, str)
  131. else username
  132. )