PageRenderTime 44ms CodeModel.GetById 13ms RepoModel.GetById 0ms app.codeStats 0ms

/tests/auth_tests/test_tokens.py

http://github.com/django/django
Python | 177 lines | 145 code | 16 blank | 16 comment | 3 complexity | 0e213fb2acf09dc837dad6cda416d7f8 MD5 | raw file
Possible License(s): BSD-3-Clause, MIT
  1. from datetime import datetime, timedelta
  2. from django.conf import settings
  3. from django.contrib.auth.models import User
  4. from django.contrib.auth.tokens import PasswordResetTokenGenerator
  5. from django.core.exceptions import ImproperlyConfigured
  6. from django.test import TestCase
  7. from django.test.utils import override_settings
  8. from .models import CustomEmailField
  9. class MockedPasswordResetTokenGenerator(PasswordResetTokenGenerator):
  10. def __init__(self, now):
  11. self._now_val = now
  12. super().__init__()
  13. def _now(self):
  14. return self._now_val
  15. class TokenGeneratorTest(TestCase):
  16. def test_make_token(self):
  17. user = User.objects.create_user("tokentestuser", "test2@example.com", "testpw")
  18. p0 = PasswordResetTokenGenerator()
  19. tk1 = p0.make_token(user)
  20. self.assertIs(p0.check_token(user, tk1), True)
  21. def test_10265(self):
  22. """
  23. The token generated for a user created in the same request
  24. will work correctly.
  25. """
  26. user = User.objects.create_user("comebackkid", "test3@example.com", "testpw")
  27. user_reload = User.objects.get(username="comebackkid")
  28. p0 = MockedPasswordResetTokenGenerator(datetime.now())
  29. tk1 = p0.make_token(user)
  30. tk2 = p0.make_token(user_reload)
  31. self.assertEqual(tk1, tk2)
  32. def test_token_with_different_email(self):
  33. """Updating the user email address invalidates the token."""
  34. tests = [
  35. (CustomEmailField, None),
  36. (CustomEmailField, "test4@example.com"),
  37. (User, "test4@example.com"),
  38. ]
  39. for model, email in tests:
  40. with self.subTest(model=model.__qualname__, email=email):
  41. user = model.objects.create_user(
  42. "changeemailuser",
  43. email=email,
  44. password="testpw",
  45. )
  46. p0 = PasswordResetTokenGenerator()
  47. tk1 = p0.make_token(user)
  48. self.assertIs(p0.check_token(user, tk1), True)
  49. setattr(user, user.get_email_field_name(), "test4new@example.com")
  50. user.save()
  51. self.assertIs(p0.check_token(user, tk1), False)
  52. def test_timeout(self):
  53. """The token is valid after n seconds, but no greater."""
  54. # Uses a mocked version of PasswordResetTokenGenerator so we can change
  55. # the value of 'now'.
  56. user = User.objects.create_user("tokentestuser", "test2@example.com", "testpw")
  57. now = datetime.now()
  58. p0 = MockedPasswordResetTokenGenerator(now)
  59. tk1 = p0.make_token(user)
  60. p1 = MockedPasswordResetTokenGenerator(
  61. now + timedelta(seconds=settings.PASSWORD_RESET_TIMEOUT)
  62. )
  63. self.assertIs(p1.check_token(user, tk1), True)
  64. p2 = MockedPasswordResetTokenGenerator(
  65. now + timedelta(seconds=(settings.PASSWORD_RESET_TIMEOUT + 1))
  66. )
  67. self.assertIs(p2.check_token(user, tk1), False)
  68. with self.settings(PASSWORD_RESET_TIMEOUT=60 * 60):
  69. p3 = MockedPasswordResetTokenGenerator(
  70. now + timedelta(seconds=settings.PASSWORD_RESET_TIMEOUT)
  71. )
  72. self.assertIs(p3.check_token(user, tk1), True)
  73. p4 = MockedPasswordResetTokenGenerator(
  74. now + timedelta(seconds=(settings.PASSWORD_RESET_TIMEOUT + 1))
  75. )
  76. self.assertIs(p4.check_token(user, tk1), False)
  77. def test_check_token_with_nonexistent_token_and_user(self):
  78. user = User.objects.create_user("tokentestuser", "test2@example.com", "testpw")
  79. p0 = PasswordResetTokenGenerator()
  80. tk1 = p0.make_token(user)
  81. self.assertIs(p0.check_token(None, tk1), False)
  82. self.assertIs(p0.check_token(user, None), False)
  83. def test_token_with_different_secret(self):
  84. """
  85. A valid token can be created with a secret other than SECRET_KEY by
  86. using the PasswordResetTokenGenerator.secret attribute.
  87. """
  88. user = User.objects.create_user("tokentestuser", "test2@example.com", "testpw")
  89. new_secret = "abcdefghijkl"
  90. # Create and check a token with a different secret.
  91. p0 = PasswordResetTokenGenerator()
  92. p0.secret = new_secret
  93. tk0 = p0.make_token(user)
  94. self.assertIs(p0.check_token(user, tk0), True)
  95. # Create and check a token with the default secret.
  96. p1 = PasswordResetTokenGenerator()
  97. self.assertEqual(p1.secret, settings.SECRET_KEY)
  98. self.assertNotEqual(p1.secret, new_secret)
  99. tk1 = p1.make_token(user)
  100. # Tokens created with a different secret don't validate.
  101. self.assertIs(p0.check_token(user, tk1), False)
  102. self.assertIs(p1.check_token(user, tk0), False)
  103. def test_token_with_different_secret_subclass(self):
  104. class CustomPasswordResetTokenGenerator(PasswordResetTokenGenerator):
  105. secret = "test-secret"
  106. user = User.objects.create_user("tokentestuser", "test2@example.com", "testpw")
  107. custom_password_generator = CustomPasswordResetTokenGenerator()
  108. tk_custom = custom_password_generator.make_token(user)
  109. self.assertIs(custom_password_generator.check_token(user, tk_custom), True)
  110. default_password_generator = PasswordResetTokenGenerator()
  111. self.assertNotEqual(
  112. custom_password_generator.secret,
  113. default_password_generator.secret,
  114. )
  115. self.assertEqual(default_password_generator.secret, settings.SECRET_KEY)
  116. # Tokens created with a different secret don't validate.
  117. tk_default = default_password_generator.make_token(user)
  118. self.assertIs(custom_password_generator.check_token(user, tk_default), False)
  119. self.assertIs(default_password_generator.check_token(user, tk_custom), False)
  120. @override_settings(SECRET_KEY="")
  121. def test_secret_lazy_validation(self):
  122. default_token_generator = PasswordResetTokenGenerator()
  123. msg = "The SECRET_KEY setting must not be empty."
  124. with self.assertRaisesMessage(ImproperlyConfigured, msg):
  125. default_token_generator.secret
  126. def test_check_token_secret_fallbacks(self):
  127. user = User.objects.create_user("tokentestuser", "test2@example.com", "testpw")
  128. p1 = PasswordResetTokenGenerator()
  129. p1.secret = "secret"
  130. tk = p1.make_token(user)
  131. p2 = PasswordResetTokenGenerator()
  132. p2.secret = "newsecret"
  133. p2.secret_fallbacks = ["secret"]
  134. self.assertIs(p1.check_token(user, tk), True)
  135. self.assertIs(p2.check_token(user, tk), True)
  136. @override_settings(
  137. SECRET_KEY="secret",
  138. SECRET_KEY_FALLBACKS=["oldsecret"],
  139. )
  140. def test_check_token_secret_key_fallbacks(self):
  141. user = User.objects.create_user("tokentestuser", "test2@example.com", "testpw")
  142. p1 = PasswordResetTokenGenerator()
  143. p1.secret = "oldsecret"
  144. tk = p1.make_token(user)
  145. p2 = PasswordResetTokenGenerator()
  146. self.assertIs(p2.check_token(user, tk), True)
  147. @override_settings(
  148. SECRET_KEY="secret",
  149. SECRET_KEY_FALLBACKS=["oldsecret"],
  150. )
  151. def test_check_token_secret_key_fallbacks_override(self):
  152. user = User.objects.create_user("tokentestuser", "test2@example.com", "testpw")
  153. p1 = PasswordResetTokenGenerator()
  154. p1.secret = "oldsecret"
  155. tk = p1.make_token(user)
  156. p2 = PasswordResetTokenGenerator()
  157. p2.secret_fallbacks = []
  158. self.assertIs(p2.check_token(user, tk), False)