Created
April 27, 2017 22:30
-
-
Save spacesailor24/1ce202d99ee148582db6ab9b85501405 to your computer and use it in GitHub Desktop.
Filestack Python Security Class
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 json | |
import base64 | |
import hmac | |
import hashlib | |
# This would be a constant sourced from a config.py file | |
ACCEPTED_SECURTIY_PARAMS = ('expiry', 'call', 'handle', 'url', | |
'maxSize', 'minSize', 'path', 'container') | |
ACCEPTED_SECURTIY_TYPES = {'expiry': int, 'call': list, | |
'handle': str, 'url': str, | |
'maxSize': int, 'minSize': int, | |
'path': str, 'container': str} | |
class Security(object): | |
def __init__(self, raw_policy, app_secret): | |
self._raw_policy = raw_policy | |
self._app_secret = app_secret | |
def _validate(self): | |
for param, value in self._raw_policy.items(): | |
if param not in ACCEPTED_SECURTIY_TYPES: | |
raise Exception('Invalid Security Parameter: {}'.format(param)) | |
for types_param, types_value in ACCEPTED_SECURTIY_TYPES.items(): | |
if types_param == param and types_value is not type(value): | |
raise Exception('Invalid Parameter Data Type for {}, ' | |
'Expecting: {} Received: {}'.format( | |
param, types_value, type(value)) | |
) | |
def _generate(self): | |
self._validate() | |
app_secret = self._app_secret | |
policy = self._raw_policy | |
policy_enc = base64.urlsafe_b64encode( | |
json.dumps(policy).encode('utf-8')) | |
signature = hmac.new(app_secret.encode('utf-8'), | |
policy_enc, | |
hashlib.sha256).hexdigest() | |
return {'policy': policy_enc, 'signature': signature} | |
fail_invalid_param = {'call': ['read', 'write'], 'expiry': 123456, | |
'not_real_param': 'not_real_value'} | |
fail_invalid_type = {'call': 'read', 'expiry': 123456} | |
good_policy = {'call': ['read', 'write'], 'expiry': 1234560} | |
another_good_policy = {'expiry': 1234560, 'call': ['read', 'write']} | |
APP_SECRET = 'ASQLS4WAPFE37DRBZPRRNXCYDQ' | |
thing = Security(another_good_policy, APP_SECRET) | |
print(thing._generate()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment