Last active
January 18, 2017 23:25
-
-
Save geeknam/0ac3a5c26b1f8f540e4b659081dddbfa to your computer and use it in GitHub Desktop.
Handy Django 1.10 middleware classes for Zappa
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
# NOTE: these are Django new style middleware classes, won't work with | |
# Django < 1.10 | |
from django.conf import settings | |
ACAH = [ | |
'Content-Type', 'X-Amz-Date', 'Authorization', | |
'X-Api-Key', 'X-Amz-Security-Token', 'x-requested-with', | |
] | |
ACAM = ['DELETE', 'GET', 'OPTIONS', 'PUT', 'POST'] | |
ACCESS_CONTROL_ALLOW_ORIGIN = getattr( | |
settings, 'ACCESS_CONTROL_ALLOW_ORIGIN', '*' | |
) | |
class ApiGatewayCorsMiddleware(object): | |
""" | |
Add CORS headers to the response. Optionally specify | |
ACCESS_CONTROL_ALLOW_ORIGIN in django settings | |
""" | |
def __init__(self, get_response): | |
self.get_response = get_response | |
def __call__(self, request): | |
response = self.get_response(request) | |
response['Access-Control-Allow-Headers'] = ','.join(ACAH) | |
response['Access-Control-Allow-Methods'] = ','.join(ACAM) | |
response['Access-Control-Allow-Origin'] = ACCESS_CONTROL_ALLOW_ORIGIN | |
return response | |
COGNITO_DEBUG_CLAIMS = getattr(settings, 'COGNITO_DEBUG_CLAIMS', {}) | |
class CognitoAuthMiddleware(object): | |
""" | |
Attach Cognito User Pool claims to the request. | |
Optionally fake claims for local development using | |
COGNITO_DEBUG_CLAIMS in settings | |
""" | |
def __init__(self, get_response): | |
self.get_response = get_response | |
def get_user_claims(self, request, attrs=None): | |
claims = request.META.get( | |
'API_GATEWAY_AUTHORIZER', {} | |
).get('claims', COGNITO_DEBUG_CLAIMS) | |
if attrs: | |
return {attr: claims[attr] for attr in attrs} | |
return claims | |
def __call__(self, request): | |
claims = self.get_user_claims(request) | |
# Stash claims to request | |
request.authorizer_claims = claims | |
response = self.get_response(request) | |
return response |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment