Created
October 15, 2016 10:45
-
-
Save Exchizz/9eb9dc68000af3aa6db153bb65ef80ff 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
#!/usr/bin/python | |
from requests import Request, Session, post,get | |
import base64, email, hmac, hashlib, urllib | |
integration_key = "" | |
host = "" | |
secret = "" | |
def sign(method, host, path, params, skey, ikey): | |
""" | |
Return HTTP Basic Authentication ("Authorization" and "Date") headers. | |
method, host, path: strings from request | |
params: dict of request parameters | |
skey: secret key | |
ikey: integration key | |
""" | |
# create canonical string | |
now = email.Utils.formatdate() | |
canon = [now, method.upper(), host.lower(), path] | |
args = [] | |
for key in sorted(params.keys()): | |
val = params[key] | |
if isinstance(val, unicode): | |
val = val.encode("utf-8") | |
args.append( | |
'%s=%s' % (urllib.quote(key, '~'), urllib.quote(val, '~'))) | |
canon.append('&'.join(args)) | |
canon = '\n'.join(canon) | |
# sign canonical string | |
sig = hmac.new(skey, canon, hashlib.sha1) | |
auth = '%s:%s' % (ikey, sig.hexdigest()) | |
# return headers | |
return {'Date': now, 'Authorization': 'Basic %s' % base64.b64encode(auth)} | |
path = "/auth/v2/check" | |
params = {"device" : "auto", "factor" : "push", "username" : "exchizz"} | |
# GET with AUTH | |
signature = sign("get", host, path, params, secret, integration_key) | |
headers = {'Authorization':signature['Authorization'], 'Date': signature['Date'], 'Host' : host } | |
params = urllib.urlencode(params) | |
resp = get('https://' + host + path + "?" + params, headers = headers).text | |
print resp | |
# POST with AUTH | |
params = {"device" : "auto", "factor" : "push", "username" : "exchizz"} | |
path = "/auth/v2/auth" | |
signature = sign("POST", host, path, params, secret, integration_key) | |
headers = {'Authorization':signature['Authorization'], 'Date': signature['Date'], 'Host' : host } | |
req = Request('POST', 'https://' + host + path, headers=headers) | |
prepped = req.prepare() | |
# do something with prepped.body | |
prepped.body = urllib.urlencode(params,doseq=True) | |
# do something with prepped.headers | |
prepped.headers['Content-Type'] = "application/x-www-form-urlencoded" | |
prepped.headers['Content-length'] = len(prepped.body) | |
s = Session() | |
resp = s.send(prepped).text | |
print resp |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment