|
| 1 | +from __future__ import absolute_import |
| 2 | +from __future__ import division |
| 3 | +from __future__ import print_function |
| 4 | +from __future__ import unicode_literals |
| 5 | + |
| 6 | +import sys |
| 7 | +import hmac |
| 8 | +import hashlib |
| 9 | + |
| 10 | + |
| 11 | +def is_webhook_authentic(webhook_secret, request_body, sent_signature): |
| 12 | + '''Used to verify that requests sent to a webhook endpoint are from Button |
| 13 | + and that their payload can be trusted. Returns True if a webhook request |
| 14 | + body matches the sent signature and False otherwise. |
| 15 | +
|
| 16 | + Args: |
| 17 | + webhook_secret (basestring): Your webhooks's secret key. Find yours at |
| 18 | + https://app.usebutton.com/webhooks. |
| 19 | +
|
| 20 | + request_body (basestring): UTF8 encoded byte-string of the request body |
| 21 | +
|
| 22 | + sent_signature (basestring): "X-Button-Siganture" HTTP Header sent with |
| 23 | + the request. |
| 24 | +
|
| 25 | + Returns: |
| 26 | + (bool) Whether or not the request is authentic |
| 27 | + ''' |
| 28 | + |
| 29 | + computed_signature = hmac.new( |
| 30 | + as_bytes(webhook_secret), |
| 31 | + as_bytes(request_body), |
| 32 | + hashlib.sha256 |
| 33 | + ).hexdigest() |
| 34 | + |
| 35 | + if hasattr(hmac, 'compare_digest'): |
| 36 | + return hmac.compare_digest( |
| 37 | + computed_signature, |
| 38 | + as_bytes(sent_signature, True) |
| 39 | + ) |
| 40 | + |
| 41 | + return computed_signature == sent_signature |
| 42 | + |
| 43 | + |
| 44 | +def as_bytes(v, only_py_2=False): |
| 45 | + '''Converts v to a UTF-8 byte string if unicode, else returns identity. |
| 46 | +
|
| 47 | + Args: |
| 48 | + v (str|unicode): the string to convert |
| 49 | +
|
| 50 | + only_py_2 (bool): If true, only converts to bytes if running in a |
| 51 | + python 2 interpretter |
| 52 | +
|
| 53 | + Returns: |
| 54 | + (byte string): A byte string copy, UTF-8 enccoded |
| 55 | + ''' |
| 56 | + |
| 57 | + python_version = sys.version_info[0] |
| 58 | + |
| 59 | + if only_py_2 and python_version != 2: |
| 60 | + return v |
| 61 | + |
| 62 | + should_encode = ( |
| 63 | + python_version == 2 and isinstance(v, unicode) |
| 64 | + or python_version == 3 and isinstance(v, str) |
| 65 | + ) |
| 66 | + |
| 67 | + if should_encode: |
| 68 | + return v.encode('utf8') |
| 69 | + |
| 70 | + return v |
0 commit comments