Coverage for /var/srv/projects/api.amasfac.comuna18.com/tmp/venv/lib/python3.9/site-packages/django/contrib/auth/tokens.py: 60%
47 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
1from datetime import datetime
3from django.conf import settings
4from django.utils.crypto import constant_time_compare, salted_hmac
5from django.utils.http import base36_to_int, int_to_base36
8class PasswordResetTokenGenerator:
9 """
10 Strategy object used to generate and check tokens for the password
11 reset mechanism.
12 """
14 key_salt = "django.contrib.auth.tokens.PasswordResetTokenGenerator"
15 algorithm = None
16 _secret = None
18 def __init__(self):
19 self.algorithm = self.algorithm or "sha256"
21 def _get_secret(self):
22 return self._secret or settings.SECRET_KEY
24 def _set_secret(self, secret):
25 self._secret = secret
27 secret = property(_get_secret, _set_secret)
29 def make_token(self, user):
30 """
31 Return a token that can be used once to do a password reset
32 for the given user.
33 """
34 return self._make_token_with_timestamp(user, self._num_seconds(self._now()))
36 def check_token(self, user, token):
37 """
38 Check that a password reset token is correct for a given user.
39 """
40 if not (user and token):
41 return False
42 # Parse the token
43 try:
44 ts_b36, _ = token.split("-")
45 except ValueError:
46 return False
48 try:
49 ts = base36_to_int(ts_b36)
50 except ValueError:
51 return False
53 # Check that the timestamp/uid has not been tampered with
54 if not constant_time_compare(self._make_token_with_timestamp(user, ts), token):
55 return False
57 # Check the timestamp is within limit.
58 if (self._num_seconds(self._now()) - ts) > settings.PASSWORD_RESET_TIMEOUT:
59 return False
61 return True
63 def _make_token_with_timestamp(self, user, timestamp):
64 # timestamp is number of seconds since 2001-1-1. Converted to base 36,
65 # this gives us a 6 digit string until about 2069.
66 ts_b36 = int_to_base36(timestamp)
67 hash_string = salted_hmac(
68 self.key_salt,
69 self._make_hash_value(user, timestamp),
70 secret=self.secret,
71 algorithm=self.algorithm,
72 ).hexdigest()[
73 ::2
74 ] # Limit to shorten the URL.
75 return "%s-%s" % (ts_b36, hash_string)
77 def _make_hash_value(self, user, timestamp):
78 """
79 Hash the user's primary key, email (if available), and some user state
80 that's sure to change after a password reset to produce a token that is
81 invalidated when it's used:
82 1. The password field will change upon a password reset (even if the
83 same password is chosen, due to password salting).
84 2. The last_login field will usually be updated very shortly after
85 a password reset.
86 Failing those things, settings.PASSWORD_RESET_TIMEOUT eventually
87 invalidates the token.
89 Running this data through salted_hmac() prevents password cracking
90 attempts using the reset token, provided the secret isn't compromised.
91 """
92 # Truncate microseconds so that tokens are consistent even if the
93 # database doesn't support microseconds.
94 login_timestamp = (
95 ""
96 if user.last_login is None
97 else user.last_login.replace(microsecond=0, tzinfo=None)
98 )
99 email_field = user.get_email_field_name()
100 email = getattr(user, email_field, "") or ""
101 return f"{user.pk}{user.password}{login_timestamp}{timestamp}{email}"
103 def _num_seconds(self, dt):
104 return int((dt - datetime(2001, 1, 1)).total_seconds())
106 def _now(self):
107 # Used for mocking in tests
108 return datetime.now()
111default_token_generator = PasswordResetTokenGenerator()