Created
October 13, 2011 16:27
-
-
Save readevalprint/1284703 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import hashlib | |
import datetime | |
import urllib | |
# TODO: Create a thin wrapper to use settings.SECRET_KEY | |
def create(secret, **kwargs): | |
"""Create a signed, timestamped single use nonce from the given kwargs""" | |
m = hashlib.md5() | |
microseconds = datetime.datetime.now().microsecond | |
m.update(str(microseconds)) | |
# Create a safe sorted string so that kwargs do not have to be | |
# unicode or even the same order. | |
m.update(urllib.urlencode(sorted(kwargs.iteritems(), | |
key=lambda (k, v): k))) | |
m.update(secret) | |
return "{ms}|{md5}".format(ms=microseconds, md5=m.hexdigest()) | |
def verify(nonce, secret, expires=None, **kwargs): | |
""" | |
Return boolean if the given nonce matches the wkargs | |
and has not expired | |
expires: timedelta when added to the timestamp is greaterthan now. | |
""" | |
microseconds, md5 = nonce.split('|') | |
# TODO: add expires check | |
m = hashlib.md5() | |
m.update(microseconds) | |
m.update(urllib.urlencode(sorted(kwargs.iteritems(), | |
key=lambda (k, v): k))) | |
m.update(secret) | |
return md5 == m.hexdigest() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment