Browse files

Added webhook validation

  • Loading branch information...
1 parent 0872d7b commit 848d2b4e14e41c931f1c19bff55313022d40e18e @alexjg alexjg committed May 1, 2012
Showing with 26 additions and 0 deletions.
  1. +12 −0 gocardless/client.py
  2. +6 −0 gocardless/utils.py
  3. +8 −0 test/test_utils.py
View
12 gocardless/client.py
@@ -378,3 +378,15 @@ def fetch_access_token(self, redirect_uri, authorization_code):
self._merchant_id = result["scope"].split(":")[1]
return self._access_token
+ def validate_webhook(self, params):
+ """Check whether a webhook signature is valid
+
+ Takes a dictionary of parameters, including the signature
+ and returns a boolean indicating whether the signature is
+ valid.
+
+ :param params: A dictionary of data to validate, must include
+ the key "signature"
+ """
+ utils.signature_valid(params, self._app_secret)
+
View
6 gocardless/utils.py
@@ -28,6 +28,12 @@ def generate_signature(data, secret):
"""
return hmac.new(secret, to_query(data), hashlib.sha256).hexdigest()
+def signature_valid(data, secret):
+ params = data.copy()
+ sig = params.pop("signature")
+ valid_sig = generate_signature(params, secret)
+ return sig == valid_sig
+
def camelize(to_uncamel):
result = []
for word in re.split("_", to_uncamel):
View
8 test/test_utils.py
@@ -50,6 +50,14 @@ def test_hmac(self):
# works correctly
sig = utils.generate_signature({"foo": "bar", "example": [1, "a"]},self.secret)
self.assertEqual(sig, '5a9447aef2ebd0e12d80d80c836858c6f9c13219f615ef5d135da408bcad453d')
+
+ def test_validate_signature(self):
+ params = {"key1":"val1", "key2":"val2"}
+ sig = utils.generate_signature(params, self.secret)
+ params["signature"] = sig
+ self.assertTrue(utils.signature_valid(params, self.secret))
+ params["signature"] = "123482494523435"
+ self.assertFalse(utils.signature_valid(params, self.secret))
class CamelizeTestCase(unittest.TestCase):

0 comments on commit 848d2b4

Please sign in to comment.