Search code examples
pythondjangoauthenticationmiddlewaredjango-middleware

Django Middleware Login check


I want to restrict all pages for unauthenticated users. I wrote the following middleware:

from django.shortcuts import redirect


def require_login(get_response):

    def middleware(request):
        if request.user.is_authenticated:
            response = get_response(request)
            return response

        return redirect('/login/')

    return middleware

The issue is that it also redirects to my Login page when it redirects to Login page (hope you got it). So it continuously redirects to my login page. What do I need to do about it? Is it okay to check if the requested page is Login page then don't check the if statement above. Thanks!


Solution

  • Inspect request.path and if it equals your login URL then return the regular response

    from django.shortcuts import redirect
    
    
    def require_login(get_response):
    
        def middleware(request):
            if request.user.is_authenticated or request.path == '/login/':
                response = get_response(request)
                return response
    
            return redirect('/login/')
    
        return middleware