django.contrib.auth.tokens: 33 total statements, 0.0% covered

Generated: Wed 2013-03-13 10:33 CET

Source file: /media/Envs/Envs/filer-gallery/lib/python2.7/site-packages/django/contrib/auth/tokens.py

Stats: 0 executed, 29 missed, 4 excluded, 38 ignored

  1. from datetime import date
  2. from django.conf import settings
  3. from django.utils.http import int_to_base36, base36_to_int
  4. from django.utils.crypto import constant_time_compare, salted_hmac
  5. class PasswordResetTokenGenerator(object):
  6. """
  7. Strategy object used to generate and check tokens for the password
  8. reset mechanism.
  9. """
  10. def make_token(self, user):
  11. """
  12. Returns a token that can be used once to do a password reset
  13. for the given user.
  14. """
  15. return self._make_token_with_timestamp(user, self._num_days(self._today()))
  16. def check_token(self, user, token):
  17. """
  18. Check that a password reset token is correct for a given user.
  19. """
  20. # Parse the token
  21. try:
  22. ts_b36, hash = token.split("-")
  23. except ValueError:
  24. return False
  25. try:
  26. ts = base36_to_int(ts_b36)
  27. except ValueError:
  28. return False
  29. # Check that the timestamp/uid has not been tampered with
  30. if not constant_time_compare(self._make_token_with_timestamp(user, ts), token):
  31. return False
  32. # Check the timestamp is within limit
  33. if (self._num_days(self._today()) - ts) > settings.PASSWORD_RESET_TIMEOUT_DAYS:
  34. return False
  35. return True
  36. def _make_token_with_timestamp(self, user, timestamp):
  37. # timestamp is number of days since 2001-1-1. Converted to
  38. # base 36, this gives us a 3 digit string until about 2121
  39. ts_b36 = int_to_base36(timestamp)
  40. # By hashing on the internal state of the user and using state
  41. # that is sure to change (the password salt will change as soon as
  42. # the password is set, at least for current Django auth, and
  43. # last_login will also change), we produce a hash that will be
  44. # invalid as soon as it is used.
  45. # We limit the hash to 20 chars to keep URL short
  46. key_salt = "django.contrib.auth.tokens.PasswordResetTokenGenerator"
  47. # Ensure results are consistent across DB backends
  48. login_timestamp = user.last_login.replace(microsecond=0, tzinfo=None)
  49. value = (unicode(user.id) + user.password +
  50. unicode(login_timestamp) + unicode(timestamp))
  51. hash = salted_hmac(key_salt, value).hexdigest()[::2]
  52. return "%s-%s" % (ts_b36, hash)
  53. def _num_days(self, dt):
  54. return (dt - date(2001, 1, 1)).days
  55. def _today(self):
  56. # Used for mocking in tests
  57. return date.today()
  58. default_token_generator = PasswordResetTokenGenerator()