sanderl-mediamonks
1/22/2014 - 3:40 PM

Slumber Tastypie HMACAuthentication class

Slumber Tastypie HMACAuthentication class

import hashlib
import hmac
from urlparse import urlparse
from datetime import datetime
from requests.auth import AuthBase

#shared secret key
SECRET_KEY = 'enter shared key here'

class TastypieHMACAuth(AuthBase):
    """
        Usage:
        api = slumber.API("http://domain.com/api/v1/", auth=TastypieHMACAuth("username", "api-key"))
    """

    def __init__(self, username, apikey):
        self.username = username
        self.apikey = apikey

    def __call__(self, req):
        timestamp = datetime.now().strftime('%a, %d %b %Y %H:%M:%S')
        req.headers['Date'] = timestamp
        req.headers['Authorization'] = "HMAC {0}:{1}:{2}".format(self.username, self.apikey, self.build_hmac_header(req.method, req.url, timestamp, req.body))
        return req

    def build_hmac_header(self, method, url, timestamp, body):
        p_parsed = urlparse(url)
        path = p_parsed.path
        if p_parsed.query:
            path += '?' + p_parsed.query

        document = u"%s %s\n%s\n%s" % (method, path, timestamp, body or '')
        signature = sha1_hmac(SECRET_KEY, document)
        return signature


def sha1_hmac(secret, document):
    """
        Calculate the Base 64 encoding of the HMAC for the given document.
    """
    signature = hmac.new(secret, document, hashlib.sha1).digest().encode("base64")[:-1]
    return signature