Created
December 6, 2014 17:51
-
-
Save gavinballard/49d56847acddc538c1fa to your computer and use it in GitHub Desktop.
This file contains hidden or 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 hashlib, base64, hmac, json, settings | |
def shopify_carrierservice_request(f): | |
""" | |
A decorator thats checks and validates a CarrierService request from Shopify. | |
""" | |
def _hmac_is_valid(body, secret, hmac_to_verify): | |
hash = hmac.new(body, secret, hashlib.sha256) | |
hmac_calculated = base64.b64encode(hash.digest()) | |
return hmac_calculated == hmac_to_verify | |
@wraps(f) | |
def wrapper(request, *args, **kwargs): | |
# Try to get required headers and decode the body of the request. | |
try: | |
request_hmac = request.META['HTTP_X_SHOPIFY_HMAC_SHA256'] | |
request_data = json.loads(request.body) | |
except: | |
return HttpResponseBadRequest() | |
# Verify the HMAC. | |
if not _hmac_is_valid(request.body, settings.SHOPIFY_API_SECRET, request_hmac): | |
return HttpResponseForbidden() | |
# Otherwise, set properties on the request object and return. | |
request.request_data = request_data | |
return f(request, args, kwargs) | |
return wrapper |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment