import pickle import base64 import sha import hmac import time from dj

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
import pickle
import base64
import sha
import hmac
import time
from django.conf import settings
# Should probably be refactored to share code with the account.captcha
# and lib.authentication modules.
def _sign(value):
"""Returns a HMAC for the given value with `settings.SECRET_KEY`."""
signature = hmac.new(settings.SECRET_KEY, value, sha)
return signature.hexdigest()
def create_email_token(action, username, email, max_age=None):
"""Create a new token from the given data."""
dict = {'action': action,
'username': username,
'email': email}
if max_age:
dict.update({'expires': time.time() + max_age})
value = base64.urlsafe_b64encode(pickle.dumps(dict))
return _sign(value) + value
def is_valid_email_token(token, action, username, email):
"""Return true if the token is valid for the given data."""
valid = False
signature, value = token[:40], token[40:]
if value and _sign(value) == signature:
dict = pickle.loads(base64.urlsafe_b64decode(value))
valid = (dict.get('action') == action and
dict.get('username') == username and
dict.get('email') == email)
if 'expires' in dict:
valid = valid and dict.get('expires') > time.time()
return valid