Created
August 16, 2019 17:17
-
-
Save oscarmcm/9554e912dde82008cc418459b74bdbc5 to your computer and use it in GitHub Desktop.
Make Turbolinks know about redirects in Django
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Taken from: https://github.com/dgladkov/django-turbolinks/blob/master/turbolinks/middleware.py#L11 # NOQA | |
def same_origin(current_uri, redirect_uri): | |
a = urlparse(current_uri) | |
if not a.scheme: | |
return True | |
b = urlparse(redirect_uri) | |
return (a.scheme, a.hostname, a.port) == (b.scheme, b.hostname, b.port) | |
class TurbolinksMiddleware(object): | |
''' Send the `Turbolinks-Location` header in response to a visit | |
that was redirected, and Turbolinks will replace the browser’s topmost | |
history entry. | |
Taken from: https://github.com/viewflow/django-material/blob/v2/material/middleware.py#L38 # NOQA | |
Note: This is needed to handle redirects with TurboLinks, like what we're doing in | |
payments.decorators.plan_upgrade_required | |
''' | |
def __init__(self, get_response): | |
self.get_response = get_response | |
def __call__(self, request): | |
response = self.get_response(request) | |
turbolinks_referrer = request.META.get('HTTP_TURBOLINKS_REFERRER') | |
is_response_redirect = response.has_header('Location') | |
if turbolinks_referrer: | |
if is_response_redirect: | |
location = response['Location'] | |
prev_location = request.session.pop( | |
'_turbolinks_redirect_to', None) | |
if prev_location is not None: | |
# relative subsequent redirect | |
if location.startswith('.'): | |
location = prev_location.split('?')[0] + location | |
request.session['_turbolinks_redirect_to'] = location | |
# cross domain blocker | |
if not same_origin(location, turbolinks_referrer): | |
return HttpResponseForbidden() | |
else: | |
if request.session.get('_turbolinks_redirect_to'): | |
location = request.session.pop('_turbolinks_redirect_to') | |
response['Turbolinks-Location'] = location | |
return response |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment