fixing typo
[oweals/karmaworld.git] / karmaworld / utils / filepicker.py
1 import hmac
2 import json
3 import base64
4
5 from hashlib import sha256
6 import os
7
8 FILEPICKER_SECRET = os.environ['FILEPICKER_SECRET']
9
10 def encode_fp_policy(policy):
11     """ Return URL-safe Base64 encoded JSON Filepicker policy. """
12     # Validate the JSON before trying to sign it and send it off to FP. It'll
13     # be easier to trap exceptions in Python than read errors out of FP.
14
15     # drop an exception bomb if the policy is not valid JSON.
16     pypolicy = json.loads(policy)
17     # ensure expiry is included. drop excepbomb if it isn't.
18     pypolicy['expiry']
19
20     # https://developers.inkfilepicker.com/docs/security/#signPolicy
21     # encode and return
22     return base64.urlsafe_b64encode(policy)
23
24 def sign_fp_policy(policy):
25     """ Return a signature appropriate for the given encoded policy. """
26     # https://developers.inkfilepicker.com/docs/security/#signPolicy
27     # hash it up, bra!
28     engine = hmac.new(FILEPICKER_SECRET, digestmod=sha256)
29     engine.update(policy)
30     return engine.hexdigest()