Coverage for /var/srv/projects/api.amasfac.comuna18.com/tmp/venv/lib/python3.9/site-packages/django/contrib/auth/base_user.py: 83%
70 statements
« prev ^ index » next coverage.py v6.4.4, created at 2023-07-17 14:22 -0600
« prev ^ index » next coverage.py v6.4.4, created at 2023-07-17 14:22 -0600
1"""
2This module allows importing AbstractBaseUser even when django.contrib.auth is
3not in INSTALLED_APPS.
4"""
5import unicodedata
7from django.contrib.auth import password_validation
8from django.contrib.auth.hashers import (
9 check_password,
10 is_password_usable,
11 make_password,
12)
13from django.db import models
14from django.utils.crypto import get_random_string, salted_hmac
15from django.utils.translation import gettext_lazy as _
18class BaseUserManager(models.Manager):
19 @classmethod
20 def normalize_email(cls, email):
21 """
22 Normalize the email address by lowercasing the domain part of it.
23 """
24 email = email or ""
25 try:
26 email_name, domain_part = email.strip().rsplit("@", 1)
27 except ValueError:
28 pass
29 else:
30 email = email_name + "@" + domain_part.lower()
31 return email
33 def make_random_password(
34 self,
35 length=10,
36 allowed_chars="abcdefghjkmnpqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ23456789",
37 ):
38 """
39 Generate a random password with the given length and given
40 allowed_chars. The default value of allowed_chars does not have "I" or
41 "O" or letters and digits that look similar -- just to avoid confusion.
42 """
43 return get_random_string(length, allowed_chars)
45 def get_by_natural_key(self, username):
46 return self.get(**{self.model.USERNAME_FIELD: username})
49class AbstractBaseUser(models.Model):
50 password = models.CharField(_("password"), max_length=128)
51 last_login = models.DateTimeField(_("last login"), blank=True, null=True)
53 is_active = True
55 REQUIRED_FIELDS = []
57 # Stores the raw password if set_password() is called so that it can
58 # be passed to password_changed() after the model is saved.
59 _password = None
61 class Meta:
62 abstract = True
64 def __str__(self):
65 return self.get_username()
67 def save(self, *args, **kwargs):
68 super().save(*args, **kwargs)
69 if self._password is not None:
70 password_validation.password_changed(self._password, self)
71 self._password = None
73 def get_username(self):
74 """Return the username for this User."""
75 return getattr(self, self.USERNAME_FIELD)
77 def clean(self):
78 setattr(self, self.USERNAME_FIELD, self.normalize_username(self.get_username()))
80 def natural_key(self):
81 return (self.get_username(),)
83 @property
84 def is_anonymous(self):
85 """
86 Always return False. This is a way of comparing User objects to
87 anonymous users.
88 """
89 return False
91 @property
92 def is_authenticated(self):
93 """
94 Always return True. This is a way to tell if the user has been
95 authenticated in templates.
96 """
97 return True
99 def set_password(self, raw_password):
100 self.password = make_password(raw_password)
101 self._password = raw_password
103 def check_password(self, raw_password):
104 """
105 Return a boolean of whether the raw_password was correct. Handles
106 hashing formats behind the scenes.
107 """
109 def setter(raw_password):
110 self.set_password(raw_password)
111 # Password hash upgrades shouldn't be considered password changes.
112 self._password = None
113 self.save(update_fields=["password"])
115 return check_password(raw_password, self.password, setter)
117 def set_unusable_password(self):
118 # Set a value that will never be a valid hash
119 self.password = make_password(None)
121 def has_usable_password(self):
122 """
123 Return False if set_unusable_password() has been called for this user.
124 """
125 return is_password_usable(self.password)
127 def get_session_auth_hash(self):
128 """
129 Return an HMAC of the password field.
130 """
131 key_salt = "django.contrib.auth.models.AbstractBaseUser.get_session_auth_hash"
132 return salted_hmac(
133 key_salt,
134 self.password,
135 algorithm="sha256",
136 ).hexdigest()
138 @classmethod
139 def get_email_field_name(cls):
140 try:
141 return cls.EMAIL_FIELD
142 except AttributeError:
143 return "email"
145 @classmethod
146 def normalize_username(cls, username):
147 return (
148 unicodedata.normalize("NFKC", username)
149 if isinstance(username, str)
150 else username
151 )