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
10 from hashlib import sha1
13 REGISTRATION_TIMEOUT_DAYS = getattr(settings, 'WALDO_REGISTRATION_TIMEOUT_DAYS', 1)
14 EMAIL_TIMEOUT_DAYS = getattr(settings, 'WALDO_EMAIL_TIMEOUT_DAYS', 1)
17 class RegistrationTokenGenerator(PasswordResetTokenGenerator):
19 Strategy object used to generate and check tokens for the user registration mechanism.
21 def check_token(self, user, token):
23 Check that a registration token is correct for a given user.
25 # If the user is active, the hash can't be valid.
31 ts_b36, hash = token.split('-')
36 ts = base36_to_int(ts_b36)
40 # Check that the timestamp and uid have not been tampered with.
41 if self._make_token_with_timestamp(user, ts) != token:
44 # Check that the timestamp is within limit
45 if (self._num_days(self._today()) - ts) > REGISTRATION_TIMEOUT_DAYS:
50 def _make_token_with_timestamp(self, user, timestamp):
51 ts_b36 = int_to_base36(timestamp)
53 # By hashing on the internal state of the user and using state that is
54 # sure to change, we produce a hash that will be invalid as soon as it
56 hash = sha1(settings.SECRET_KEY + unicode(user.id) + unicode(user.is_active) + user.last_login.strftime('%Y-%m-%d %H:%M:%S') + unicode(timestamp)).hexdigest()[::2]
57 return '%s-%s' % (ts_b36, hash)
60 registration_token_generator = RegistrationTokenGenerator()
63 class EmailTokenGenerator(PasswordResetTokenGenerator):
65 Strategy object used to generate and check tokens for a user email change mechanism.
67 def make_token(self, user, email):
69 Returns a token that can be used once to do an email change for the given user and email.
71 return self._make_token_with_timestamp(user, email, self._num_days(self._today()))
73 def check_token(self, user, email, token):
74 if email == user.email:
79 ts_b36, hash = token.split('-')
84 ts = base36_to_int(ts_b36)
88 # Check that the timestamp and uid have not been tampered with.
89 if self._make_token_with_timestamp(user, email, ts) != token:
92 # Check that the timestamp is within limit
93 if (self._num_days(self._today()) - ts) > EMAIL_TIMEOUT_DAYS:
98 def _make_token_with_timestamp(self, user, email, timestamp):
99 ts_b36 = int_to_base36(timestamp)
101 hash = sha1(settings.SECRET_KEY + unicode(user.id) + user.email + email + unicode(timestamp)).hexdigest()[::2]
102 return '%s-%s' % (ts_b36, hash)
105 email_token_generator = EmailTokenGenerator()