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.

tokens.py 3.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. from datetime import date
  2. from django.conf import settings
  3. from django.utils.crypto import constant_time_compare, salted_hmac
  4. from django.utils.http import base36_to_int, int_to_base36
  5. class PasswordResetTokenGenerator:
  6. """
  7. Strategy object used to generate and check tokens for the password
  8. reset mechanism.
  9. """
  10. key_salt = "django.contrib.auth.tokens.PasswordResetTokenGenerator"
  11. secret = settings.SECRET_KEY
  12. def make_token(self, user):
  13. """
  14. Return a token that can be used once to do a password reset
  15. for the given user.
  16. """
  17. return self._make_token_with_timestamp(user, self._num_days(self._today()))
  18. def check_token(self, user, token):
  19. """
  20. Check that a password reset token is correct for a given user.
  21. """
  22. if not (user and token):
  23. return False
  24. # Parse the token
  25. try:
  26. ts_b36, _ = token.split("-")
  27. except ValueError:
  28. return False
  29. try:
  30. ts = base36_to_int(ts_b36)
  31. except ValueError:
  32. return False
  33. # Check that the timestamp/uid has not been tampered with
  34. if not constant_time_compare(self._make_token_with_timestamp(user, ts), token):
  35. return False
  36. # Check the timestamp is within limit. Timestamps are rounded to
  37. # midnight (server time) providing a resolution of only 1 day. If a
  38. # link is generated 5 minutes before midnight and used 6 minutes later,
  39. # that counts as 1 day. Therefore, PASSWORD_RESET_TIMEOUT_DAYS = 1 means
  40. # "at least 1 day, could be up to 2."
  41. if (self._num_days(self._today()) - ts) > settings.PASSWORD_RESET_TIMEOUT_DAYS:
  42. return False
  43. return True
  44. def _make_token_with_timestamp(self, user, timestamp):
  45. # timestamp is number of days since 2001-1-1. Converted to
  46. # base 36, this gives us a 3 digit string until about 2121
  47. ts_b36 = int_to_base36(timestamp)
  48. hash_string = salted_hmac(
  49. self.key_salt,
  50. self._make_hash_value(user, timestamp),
  51. secret=self.secret,
  52. ).hexdigest()[::2] # Limit to 20 characters to shorten the URL.
  53. return "%s-%s" % (ts_b36, hash_string)
  54. def _make_hash_value(self, user, timestamp):
  55. """
  56. Hash the user's primary key and some user state that's sure to change
  57. after a password reset to produce a token that invalidated when it's
  58. used:
  59. 1. The password field will change upon a password reset (even if the
  60. same password is chosen, due to password salting).
  61. 2. The last_login field will usually be updated very shortly after
  62. a password reset.
  63. Failing those things, settings.PASSWORD_RESET_TIMEOUT_DAYS eventually
  64. invalidates the token.
  65. Running this data through salted_hmac() prevents password cracking
  66. attempts using the reset token, provided the secret isn't compromised.
  67. """
  68. # Truncate microseconds so that tokens are consistent even if the
  69. # database doesn't support microseconds.
  70. login_timestamp = '' if user.last_login is None else user.last_login.replace(microsecond=0, tzinfo=None)
  71. return str(user.pk) + user.password + str(login_timestamp) + str(timestamp)
  72. def _num_days(self, dt):
  73. return (dt - date(2001, 1, 1)).days
  74. def _today(self):
  75. # Used for mocking in tests
  76. return date.today()
  77. default_token_generator = PasswordResetTokenGenerator()