base_user.py 4.7 KB

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