forked from pd/httpie-api-auth
-
Notifications
You must be signed in to change notification settings - Fork 0
/
httpie_api_auth.py
58 lines (44 loc) · 1.6 KB
/
httpie_api_auth.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
"""
ApiAuth auth plugin for HTTPie.
"""
from httpie.plugins import AuthPlugin
import hmac, base64, hashlib, datetime
try:
import urlparse
except ImportError:
import urllib.parse
__version__ = '0.3.0'
__author__ = 'Kyle Hargraves'
__licence__ = 'MIT'
class ApiAuth:
def __init__(self, access_id, secret_key):
self.access_id = access_id
self.secret_key = secret_key.encode('ascii')
def __call__(self, r):
method = r.method.upper()
content_type = r.headers.get('content-type')
if not content_type:
content_type = ''
content_md5 = r.headers.get('content-md5')
if not content_md5:
content_md5 = ''
httpdate = r.headers.get('date')
if not httpdate:
now = datetime.datetime.utcnow()
httpdate = now.strftime('%a, %d %b %Y %H:%M:%S GMT')
r.headers['Date'] = httpdate
url = urlparse.urlparse(r.url)
path = url.path
if url.query:
path = path + '?' + url.query
string_to_sign = '%s,%s,%s,%s,%s' % (method, content_type, content_md5, path, httpdate)
digest = hmac.new(self.secret_key, string_to_sign, hashlib.sha1).digest()
signature = base64.encodestring(digest).rstrip()
r.headers['Authorization'] = 'APIAuth %s:%s' % (self.access_id, signature)
return r
class ApiAuthPlugin(AuthPlugin):
name = 'ApiAuth auth'
auth_type = 'api-auth'
description = 'Sign requests using the ApiAuth authentication method'
def get_auth(self, access_id, secret_key):
return ApiAuth(access_id, secret_key)