Initial release
[barker/.git] / barker.py
1 import hmac
2 import requests
3 import time
4 __version__ = "0.1"
5
6
7 class Webhook():
8     def __init__(self, url=None, data=None, timeout=5, key=None):
9         self.url = url
10         self.data = data
11         self.timeout = timeout
12         self.key = key if key is not None else 'BARKER'
13         self.headers = {}
14         self.response = None
15
16     def _calculate_hash(self):
17         """ Calculate hash to include as a header. """
18         self.headers['BARKER_TIMESTAMP'] = str(time.time())
19         hash = hmac.new(bytes(self.key, 'utf-8'))
20         hash.update(bytes(";".join((self.headers['BARKER_TIMESTAMP'], self.data)), 'utf-8'))
21         self.headers['BARKER_SIGNATURE'] = hash.hexdigest()
22
23     def send(self):
24         self._calculate_hash()
25         self.response = requests.post(self.url,
26                                       headers=self.headers,
27                                       data=self.data,
28                                       timeout=self.timeout)
29
30         return self.response
31
32     def verify_hash(self):
33         """ Verify the data matches the hash provided """
34         hash = hmac.new(bytes(self.key, 'utf-8'))
35         hash.update(bytes(";".join((self.headers['BARKER_TIMESTAMP'], self.data)), 'utf-8'))
36         return hmac.compare_digest(self.headers['BARKER_SIGNATURE'], hash.hexdigest())