fe32274fd848c060ea6110fc0e4ef2a53f2a483f
[philo.git] / contrib / waldo / tokens.py
1 """
2 Based on django.contrib.auth.tokens
3 """
4
5
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
11
12 REGISTRATION_TIMEOUT_DAYS = getattr(settings, 'WALDO_REGISTRATION_TIMEOUT_DAYS', 1)
13
14
15 class RegistrationTokenGenerator(PasswordResetTokenGenerator):
16         """
17         Strategy object used to generate and check tokens for the user registration mechanism.
18         """
19         def make_token(self, user):
20                 """
21                 Returns a token that can be used once to activate a user's account.
22                 """
23                 if user.is_active:
24                         return False
25                 return self._make_token_with_timestamp(user, self._num_days(self._today()))
26         
27         def check_token(self, user, token):
28                 """
29                 Check that a registration token is correct for a given user.
30                 """
31                 # If the user is active, the hash can't be valid.
32                 if user.is_active:
33                         return False
34                 
35                 # Parse the token
36                 try:
37                         ts_b36, hash = token.split('-')
38                 except ValueError:
39                         return False
40                 
41                 try:
42                         ts = base36_to_int(ts_b36)
43                 except ValueError:
44                         return False
45                 
46                 # Check that the timestamp and uid have not been tampered with.
47                 if self._make_token_with_timestamp(user, ts) != token:
48                         return False
49                 
50                 # Check that the timestamp is within limit
51                 if (self._num_days(self._today()) - ts) > REGISTRATION_TIMEOUT_DAYS:
52                         return False
53                 
54                 return True
55         
56         def _make_token_with_timestamp(self, user, timestamp):
57                 ts_b36 = int_to_base36(timestamp)
58                 
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
61                 # is used.
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)
65
66 registration_token_generator = RegistrationTokenGenerator()