# Note that request.get_host() includes the port.
good_referer = 'https://%s/' % request.get_host()
if not same_origin(referer, good_referer):
reason = REASON_BAD_REFERER % (referer, good_referer)
return self._reject(request, reason)class CsrfViewMiddleware(object):
def process_view(self, request, callback, callback_args, callback_kwargs):
[...] # Assume that anything not defined as 'safe' by RFC2616 needs protection if request.method not in ('GET', 'HEAD', 'OPTIONS', 'TRACE'): [...] if request.is_secure(): [...] # Note that request.get_host() includes the port. good_referer = 'https://%s/' % request.get_host() if not self.is_same_origin(referer, good_referer): reason = REASON_BAD_REFERER % (referer, good_referer) return self._reject(request, reason)
[...] return self._accept(request)
def is_same_origin(self, referer, good_referer): return same_origin(referer, good_referer):
@staticmethod
def _https_referer_replace(request):
"""
When https is enabled, django CSRF checking includes referer checking
which breaks when using CORS. This function updates the HTTP_REFERER
header to make sure it matches HTTP_HOST, provided that our cors logic
succeeds.
Based on snippet taken from:
https://github.com/ottoyiu/django-cors-headers/blob/master/corsheaders/middleware.py
"""
if settings.YAPI.get('XS_SHARING_REPLACE_HTTPS_REFERER') is True:
origin = request.META.get('HTTP_ORIGIN')
allowed_origins = settings.YAPI['XS_SHARING_ALLOWED_ORIGINS']
if request.is_secure() and origin and 'ORIGINAL_HTTP_REFERER' not in request.META:
if allowed_origins != '*' and origin not in allowed_origins:
return
try:
http_referer = request.META['HTTP_REFERER']
http_host = "https://%s/" % request.META['HTTP_HOST']
request.META = request.META.copy()
request.META['ORIGINAL_HTTP_REFERER'] = http_referer
request.META['HTTP_REFERER'] = http_host
except KeyError:
pass
@staticmethod
def _https_referer_replace_reverse(request):
"""
Put the HTTP_REFERER back to its original value and delete the temporary storage.
Based on snippet taken from:
https://github.com/ottoyiu/django-cors-headers/blob/master/corsheaders/middleware.py
"""
if settings.YAPI.get('XS_SHARING_REPLACE_HTTPS_REFERER') is True and 'ORIGINAL_HTTP_REFERER' in request.META:
http_referer = request.META['ORIGINAL_HTTP_REFERER']
request.META['HTTP_REFERER'] = http_referer
del request.META['ORIGINAL_HTTP_REFERER']