base_user.py 5.4 KB

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