Development of an internal social media platform with personalised dashboards for students
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.4KB

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 get_username(self):
  50. "Return the identifying username for this User"
  51. return getattr(self, self.USERNAME_FIELD)
  52. def __str__(self):
  53. return self.get_username()
  54. def clean(self):
  55. setattr(self, self.USERNAME_FIELD, self.normalize_username(self.get_username()))
  56. def save(self, *args, **kwargs):
  57. super().save(*args, **kwargs)
  58. if self._password is not None:
  59. password_validation.password_changed(self._password, self)
  60. self._password = None
  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