Skip to content

Instantly share code, notes, and snippets.

@mesuutt
Forked from strogonoff/middleware.py
Last active January 2, 2016 20:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mesuutt/8356176 to your computer and use it in GitHub Desktop.
Save mesuutt/8356176 to your computer and use it in GitHub Desktop.
Django middleware for cross-domain XHR. WARNING: Defaults are unsafe here. Make sure to set proper restrictions in production!
from django import http
class XsSharing(object):
"""
This middleware allows cross-domain XHR using the html5 postMessage API.
Access-Control-Allow-Origin: http://foo.example
Access-Control-Allow-Methods: POST, GET, OPTIONS, PUT, DELETE
Based off https://gist.github.com/426829
"""
def __init__(self):
self.XS_SHARING_ALLOWED_ORIGINS = getattr(settings, 'XS_SHARING_ALLOWED_ORIGINS', '*')
self.XS_SHARING_ALLOWED_METHODS = getattr(
settings,
'XS_SHARING_ALLOWED_METHODS',
['POST', 'GET', 'OPTIONS', 'PUT', 'DELETE']
)
self.XS_SHARING_ALLOWED_HEADERS = getattr(
settings,
'XS_SHARING_ALLOWED_HEADERS',
['Content-Type', '*']
)
self.XS_SHARING_ALLOWED_CREDENTIALS = getattr(
settings,
'XS_SHARING_ALLOWED_CREDENTIALS',
'true'
)
def process_request(self, request):
if 'HTTP_ACCESS_CONTROL_REQUEST_METHOD' in request.META:
response = http.HttpResponse()
response['Access-Control-Allow-Origin'] = self.XS_SHARING_ALLOWED_ORIGINS
response['Access-Control-Allow-Methods'] = ",".join(self.XS_SHARING_ALLOWED_METHODS)
response['Access-Control-Allow-Headers'] = ",".join(self.XS_SHARING_ALLOWED_HEADERS)
response['Access-Control-Allow-Credentials'] = self.XS_SHARING_ALLOWED_CREDENTIALS
return response
return None
def process_response(self, request, response):
response['Access-Control-Allow-Origin'] = self.XS_SHARING_ALLOWED_ORIGINS
response['Access-Control-Allow-Methods'] = ",".join(self.XS_SHARING_ALLOWED_METHODS)
response['Access-Control-Allow-Headers'] = ",".join(self.XS_SHARING_ALLOWED_HEADERS)
response['Access-Control-Allow-Credentials'] = self.XS_SHARING_ALLOWED_CREDENTIALS
return response
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment