X-Git-Url: http://git.ithinksw.org/philo.git/blobdiff_plain/c518611f1b9da9f7960440df38bbc6f2e09e5821..8c6ffb8e54f201a0fb7776fdd865bbbb3d42a29b:/contrib/waldo/tokens.py diff --git a/contrib/waldo/tokens.py b/contrib/waldo/tokens.py index aff91ff..95ce0c0 100644 --- a/contrib/waldo/tokens.py +++ b/contrib/waldo/tokens.py @@ -10,20 +10,13 @@ from django.contrib.auth.tokens import PasswordResetTokenGenerator REGISTRATION_TIMEOUT_DAYS = getattr(settings, 'WALDO_REGISTRATION_TIMEOUT_DAYS', 1) +EMAIL_TIMEOUT_DAYS = getattr(settings, 'WALDO_EMAIL_TIMEOUT_DAYS', 1) class RegistrationTokenGenerator(PasswordResetTokenGenerator): """ Strategy object used to generate and check tokens for the user registration mechanism. """ - def make_token(self, user): - """ - Returns a token that can be used once to activate a user's account. - """ - if user.is_active: - return False - return self._make_token_with_timestamp(user, self._num_days(self._today())) - def check_token(self, user, token): """ Check that a registration token is correct for a given user. @@ -63,4 +56,51 @@ class RegistrationTokenGenerator(PasswordResetTokenGenerator): 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] return '%s-%s' % (ts_b36, hash) -default_token_generator = RegistrationTokenGenerator() \ No newline at end of file + +registration_token_generator = RegistrationTokenGenerator() + + +class EmailTokenGenerator(PasswordResetTokenGenerator): + """ + Strategy object used to generate and check tokens for a user email change mechanism. + """ + def make_token(self, user, email): + """ + Returns a token that can be used once to do an email change for the given user and email. + """ + return self._make_token_with_timestamp(user, email, self._num_days(self._today())) + + def check_token(self, user, email, token): + if email == user.email: + return False + + # Parse the token + try: + ts_b36, hash = token.split('-') + except ValueError: + return False + + try: + ts = base36_to_int(ts_b36) + except ValueError: + return False + + # Check that the timestamp and uid have not been tampered with. + if self._make_token_with_timestamp(user, email, ts) != token: + return False + + # Check that the timestamp is within limit + if (self._num_days(self._today()) - ts) > EMAIL_TIMEOUT_DAYS: + return False + + return True + + def _make_token_with_timestamp(self, user, email, timestamp): + ts_b36 = int_to_base36(timestamp) + + from django.utils.hashcompat import sha_constructor + hash = sha_constructor(settings.SECRET_KEY + unicode(user.id) + user.email + email + unicode(timestamp)).hexdigest()[::2] + return '%s-%s' % (ts_b36, hash) + + +email_token_generator = EmailTokenGenerator() \ No newline at end of file