Search code examples
pythonmysqldjangodjango-viewsdjango-templates

Django - Wants to restrict access to all of them to only logged-in users and I already have 100's of functions, is their anyway to add it directly?


In Python-Django views.py file I have 100's of functions and I want to restrict access to all of them to only logged-in users. I'm aware that I can add "@login_required(login_url='/admin/login/')" above every function and I works well.

But as there are lots of function then adding it can be quite cumbersome. So, is there any way to achieve this without manually adding it to each and every function.

Helps are highly appreciated.

@login_required(login_url='/member/login/')
def dashboard(request):
    id = request.user.id
    result = User.objects.get(pk=id)
    context={'result' : result}
    return render(request, 'member/dashboard.html', context)

I want to restrict access to all of them to only logged-in users.


Solution

  • Probably the easiest way would be to work with some middleware to do this:

    # app_name/middleware.py
    from django.conf import settings
    from django.contrib.auth.decorators import login_required
    
    
    class LoginRequiredMiddleware:
        def __init__(self, get_response):
            self.get_response = get_response
            self.restricted_get_response = login_required(
                get_response
            )
    
        def __call__(self, request):
            if request.path == settings.LOGIN_URL:
                return self.get_response(request)
            return self.restricted_get_response(request)

    We don't want to restrict the /member/login/ path, since then one could not log in anyway.

    You need to add the middleware below the AuthenticationMiddleware:

    # settings.py
    
    # …
    
    LOGIN_URL = '/member/login/'
    
    # …
    
    MIDDLEWARE = [
        # …,
        'django.contrib.auth.middleware.AuthenticationMiddleware',
        # …,
        'app_name.middleware.LoginRequiredMiddleware',
        # …
    ]