hobo/hobo/middleware/cors.py

32 lines
1.1 KiB
Python

import os.path
from django.conf import settings
from django.http import HttpResponse
from django.utils.deprecation import MiddlewareMixin
class CORSMiddleware(MiddlewareMixin):
def process_request(self, request):
"""
If CORS preflight header, then create an
empty body response (200 OK) and return it
Django won't bother calling any other request
view/exception middleware along with the requested view;
it will call any response middlewares
"""
if request.method == 'OPTIONS' and "access-control-request-method" in request.headers:
response = HttpResponse()
return response
return None
def process_response(self, request, response):
origin = request.headers.get('Origin')
if origin:
whitelist = getattr(settings, 'CORS_ORIGIN_WHITELIST', [])
if origin not in whitelist:
return response
response['Access-Control-Allow-Origin'] = origin
response['Access-Control-Allow-Credentials'] = 'true'
response['Access-Control-Allow-Headers'] = 'x-requested-with'
return response