diff --git a/django/contrib/auth/tokens.py b/django/contrib/auth/tokens.py index 55d80e3153..d2882200f4 100644 --- a/django/contrib/auth/tokens.py +++ b/django/contrib/auth/tokens.py @@ -12,12 +12,19 @@ class PasswordResetTokenGenerator: """ key_salt = "django.contrib.auth.tokens.PasswordResetTokenGenerator" algorithm = None - secret = None + _secret = None def __init__(self): - self.secret = self.secret or settings.SECRET_KEY self.algorithm = self.algorithm or 'sha256' + def _get_secret(self): + return self._secret or settings.SECRET_KEY + + def _set_secret(self, secret): + self._secret = secret + + secret = property(_get_secret, _set_secret) + def make_token(self, user): """ Return a token that can be used once to do a password reset diff --git a/tests/auth_tests/test_tokens.py b/tests/auth_tests/test_tokens.py index af823b1114..ff26bd626b 100644 --- a/tests/auth_tests/test_tokens.py +++ b/tests/auth_tests/test_tokens.py @@ -3,7 +3,9 @@ from datetime import datetime, timedelta from django.conf import settings from django.contrib.auth.models import User from django.contrib.auth.tokens import PasswordResetTokenGenerator +from django.core.exceptions import ImproperlyConfigured from django.test import TestCase +from django.test.utils import override_settings from .models import CustomEmailField @@ -131,3 +133,10 @@ class TokenGeneratorTest(TestCase): tk_default = default_password_generator.make_token(user) self.assertIs(custom_password_generator.check_token(user, tk_default), False) self.assertIs(default_password_generator.check_token(user, tk_custom), False) + + @override_settings(SECRET_KEY='') + def test_secret_lazy_validation(self): + default_token_generator = PasswordResetTokenGenerator() + msg = 'The SECRET_KEY setting must not be empty.' + with self.assertRaisesMessage(ImproperlyConfigured, msg): + default_token_generator.secret