Last active
August 29, 2015 14:01
-
-
Save inean/b46c956ed5bc443395cc to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import functools | |
def plivo_validate(func): | |
"""validate a request from plivo | |
returns true if the request passes validation, false if not | |
""" | |
@functools.wraps(func) | |
def wrapper(handler, *args, **kwargs): | |
# compute full URL without query elements | |
source = "{0}://{1}{2}".format( | |
handler.request.protocol, | |
handler.request.host, | |
handler.request.path) | |
# append GET query string sorted by key to the uri | |
plargs = handler.request.arguments.iteritems() | |
# POST Is treated differently | |
if handler.request.method == 'POST': | |
plargs = handler.request.body_arguments.iteritems() | |
source = handler.request.full_url() | |
# compute signature and compare signatures | |
source += "".join(sorted((arg[0] + arg[1][0] for arg in plargs))) | |
digest = hmac.new(handler.plivo_token, source, hashlib.sha1) | |
signed = handler.request.headers.get('X-Plivo-Signature') | |
# validate if signed is None, return None | |
if base64.encodestring(digest.digest()).strip() != signed: | |
# Send a not found error | |
raise HTTPError(404) | |
# invoke func | |
return func(handler, *args, **kwargs) | |
return wrapper | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment