2015-04-20 16:52:06 +02:00
|
|
|
import os.path
|
|
|
|
|
|
|
|
from django.conf import settings
|
2015-05-06 10:01:36 +02:00
|
|
|
from django.http import HttpResponse
|
2019-09-22 20:04:17 +02:00
|
|
|
from django.utils.deprecation import MiddlewareMixin
|
2015-04-20 16:52:06 +02:00
|
|
|
|
2021-05-14 18:39:27 +02:00
|
|
|
|
2019-09-22 20:04:17 +02:00
|
|
|
class CORSMiddleware(MiddlewareMixin):
|
2015-04-20 16:52:06 +02:00
|
|
|
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
|
|
|
|
"""
|
2023-03-29 12:10:39 +02:00
|
|
|
if request.method == 'OPTIONS' and "access-control-request-method" in request.headers:
|
2015-05-06 10:01:36 +02:00
|
|
|
response = HttpResponse()
|
2015-04-20 16:52:06 +02:00
|
|
|
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
|
2015-05-06 10:05:03 +02:00
|
|
|
response['Access-Control-Allow-Origin'] = origin
|
|
|
|
response['Access-Control-Allow-Credentials'] = 'true'
|
|
|
|
response['Access-Control-Allow-Headers'] = 'x-requested-with'
|
2015-04-20 16:52:06 +02:00
|
|
|
return response
|