base_user.py 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138
  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 = '@'.join([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. class Meta:
  45. abstract = True
  46. def get_username(self):
  47. "Return the identifying username for this User"
  48. return getattr(self, self.USERNAME_FIELD)
  49. def __init__(self, *args, **kwargs):
  50. super().__init__(*args, **kwargs)
  51. # Stores the raw password if set_password() is called so that it can
  52. # be passed to password_changed() after the model is saved.
  53. self._password = None
  54. def __str__(self):
  55. return self.get_username()
  56. def clean(self):
  57. setattr(self, self.USERNAME_FIELD, self.normalize_username(self.get_username()))
  58. def save(self, *args, **kwargs):
  59. super().save(*args, **kwargs)
  60. if self._password is not None:
  61. password_validation.password_changed(self._password, self)
  62. self._password = None
  63. def natural_key(self):
  64. return (self.get_username(),)
  65. @property
  66. def is_anonymous(self):
  67. """
  68. Always return False. This is a way of comparing User objects to
  69. anonymous users.
  70. """
  71. return False
  72. @property
  73. def is_authenticated(self):
  74. """
  75. Always return True. This is a way to tell if the user has been
  76. authenticated in templates.
  77. """
  78. return True
  79. def set_password(self, raw_password):
  80. self.password = make_password(raw_password)
  81. self._password = raw_password
  82. def check_password(self, raw_password):
  83. """
  84. Return a boolean of whether the raw_password was correct. Handles
  85. hashing formats behind the scenes.
  86. """
  87. def setter(raw_password):
  88. self.set_password(raw_password)
  89. # Password hash upgrades shouldn't be considered password changes.
  90. self._password = None
  91. self.save(update_fields=["password"])
  92. return check_password(raw_password, self.password, setter)
  93. def set_unusable_password(self):
  94. # Set a value that will never be a valid hash
  95. self.password = make_password(None)
  96. def has_usable_password(self):
  97. return is_password_usable(self.password)
  98. def get_session_auth_hash(self):
  99. """
  100. Return an HMAC of the password field.
  101. """
  102. key_salt = "django.contrib.auth.models.AbstractBaseUser.get_session_auth_hash"
  103. return salted_hmac(key_salt, self.password).hexdigest()
  104. @classmethod
  105. def get_email_field_name(cls):
  106. try:
  107. return cls.EMAIL_FIELD
  108. except AttributeError:
  109. return 'email'
  110. @classmethod
  111. def normalize_username(cls, username):
  112. return unicodedata.normalize('NFKC', username) if username else username