base_user.py 4.9 KB

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