hobo/hobo/middleware/cors.py

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

32 lines
1.1 KiB
Python
Raw Normal View History

import os.path
from django.conf import settings
from django.http import HttpResponse
from django.utils.deprecation import MiddlewareMixin
2021-05-14 18:39:27 +02:00
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