2 Based on django.contrib.auth.tokens
6 from datetime import date
7 from django.conf import settings
8 from django.utils.http import int_to_base36, base36_to_int
9 from django.contrib.auth.tokens import PasswordResetTokenGenerator
12 REGISTRATION_TIMEOUT_DAYS = getattr(settings, 'WALDO_REGISTRATION_TIMEOUT_DAYS', 1)
15 class RegistrationTokenGenerator(PasswordResetTokenGenerator):
17 Strategy object used to generate and check tokens for the user registration mechanism.
19 def make_token(self, user):
21 Returns a token that can be used once to activate a user's account.
25 return self._make_token_with_timestamp(user, self._num_days(self._today()))
27 def check_token(self, user, token):
29 Check that a registration token is correct for a given user.
31 # If the user is active, the hash can't be valid.
37 ts_b36, hash = token.split('-')
42 ts = base36_to_int(ts_b36)
46 # Check that the timestamp and uid have not been tampered with.
47 if self._make_token_with_timestamp(user, ts) != token:
50 # Check that the timestamp is within limit
51 if (self._num_days(self._today()) - ts) > REGISTRATION_TIMEOUT_DAYS:
56 def _make_token_with_timestamp(self, user, timestamp):
57 ts_b36 = int_to_base36(timestamp)
59 # By hashing on the internal state of the user and using state that is
60 # sure to change, we produce a hash that will be invalid as soon as it
62 from django.utils.hashcompat import sha_constructor
63 hash = sha_constructor(settings.SECRET_KEY + unicode(user.id) + unicode(user.is_active) + user.last_login.strftime('%Y-%m-%d %H:%M:%S') + unicode(timestamp)).hexdigest()[::2]
64 return '%s-%s' % (ts_b36, hash)
66 registration_token_generator = RegistrationTokenGenerator()