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.

base_user.py 4.3KB

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