Last active
December 14, 2015 19:19
-
-
Save marconi/5135363 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 hmac | |
import hashlib | |
import time | |
import uuid | |
SYSTEM_WIDE_SECRET = 'supersecret' | |
GENERATED_TOKENS = {} | |
def generate_access_key(data): | |
data['uuid'] = str(uuid.uuid4()) # for uniqueness | |
payload = ''.join(['%s:%s' % (k, v) for k, v in data.items()]) | |
hasher = hashlib.sha256() | |
hasher.update(payload) | |
return hasher.hexdigest() | |
def create_api_access(person, ttl=60): | |
access_key = generate_access_key(person) | |
GENERATED_TOKENS[access_key] = int(time.time()) + (60 * ttl) | |
return access_key | |
def digest_data(key, data): | |
digester = hmac.new(key, data, hashlib.sha256) | |
return digester.hexdigest() | |
def verify_request(hash, data): | |
# lets cheat a bit :) | |
access_key, ttl = GENERATED_TOKENS.items()[0] | |
if ttl < int(time.time()): | |
raise Exception('Expired') | |
if not digest_data(access_key, data) == hash: | |
raise Exception('Invalid access key') | |
return 'OK' | |
if __name__ == '__main__': | |
person = {"name": "Juan Dela Cruz", | |
"age": 25, | |
"location": "Philippines"} | |
access_key = create_api_access(person) | |
data = 'action:access_resource' | |
data_hash = digest_data(access_key, data) | |
assert verify_request(data_hash, data) == 'OK' |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment