Unsafe redirect to URL with protocol 'account'

995 views Asked by At

I am trying to redirect to login page with return url through a middleware .

I am getting this error so can anyone answer the question why i am getting this error and how to solve this error

from django.shortcuts import redirect
def auth_middleware(get_response):
     def middleware(request):
        print("Middleware")
        return_url = request.META['PATH_INFO']
        if not request.session.get('user_id'):
            return redirect(f'account:login?return_url={return_url}')
        response = get_response(request)
        return response

    return middleware
1

There are 1 answers

5
willeM_ Van Onsem On

Django will make a redirect to account:login?return_url=some_url, but the browser does not understand this: since it sees a URL that starts with account:, it assumes that account: is the protocol.

We can reverse the view with reverse(…) [Django-doc]:

from django.urls import reverse
from django.http import HttpResponseRedirect

def auth_middleware(get_response):
     def middleware(request):
        print("Middleware")
        return_url = request.META['PATH_INFO']
        if not request.session.get('user_id'):
            return HttpResponseRedirect(f'{reverse("account:login")}?return_url={return_url}')
        response = get_response(request)
        return response

    return middleware

or you can make a decorator with:

from django.urls import reverse
from django.http import HttpResponseRedirect
from functools import wraps

def auth_decorator(view):
    @wraps(view)
    def wrapper(request, *args, **kwargs):
        print("Middleware")
        return_url = request.META['PATH_INFO']
        if not request.session.get('user_id'):
            return HttpResponseRedirect(f'{reverse("account:login")}?return_url={return_url}')
        return view(request, *args, **kwargs)

    return wrapper