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