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.
 
 
 
 

131 lines
4.3 KiB

  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. 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.encoding import python_2_unicode_compatible
  13. from django.utils.translation import ugettext_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 = '@'.join([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. @python_2_unicode_compatible
  41. class AbstractBaseUser(models.Model):
  42. password = models.CharField(_('password'), max_length=128)
  43. last_login = models.DateTimeField(_('last login'), blank=True, null=True)
  44. is_active = True
  45. REQUIRED_FIELDS = []
  46. class Meta:
  47. abstract = True
  48. def get_username(self):
  49. "Return the identifying username for this User"
  50. return getattr(self, self.USERNAME_FIELD)
  51. def __init__(self, *args, **kwargs):
  52. super(AbstractBaseUser, self).__init__(*args, **kwargs)
  53. # Stores the raw password if set_password() is called so that it can
  54. # be passed to password_changed() after the model is saved.
  55. self._password = None
  56. def __str__(self):
  57. return self.get_username()
  58. def save(self, *args, **kwargs):
  59. super(AbstractBaseUser, self).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. 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. 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. return is_password_usable(self.password)
  96. def get_full_name(self):
  97. raise NotImplementedError('subclasses of AbstractBaseUser must provide a get_full_name() method')
  98. def get_short_name(self):
  99. raise NotImplementedError('subclasses of AbstractBaseUser must provide a get_short_name() method.')
  100. def get_session_auth_hash(self):
  101. """
  102. Return an HMAC of the password field.
  103. """
  104. key_salt = "django.contrib.auth.models.AbstractBaseUser.get_session_auth_hash"
  105. return salted_hmac(key_salt, self.password).hexdigest()