Set all pages to require login, globally?

user1067863 picture user1067863 · Dec 4, 2011 · Viewed 16.2k times · Source

I want to redirect access of unauthenticated users to the login page, after which the logged-in user should be redirected to the originally requested page.

According to documentation, this is easily achieved using the @user_passes_test decorator. But it seems I'd have to decorate every view, which is crazy, there are too many and it's error-prone.

What is a good way to turn on this functionality globally (except for a small fixed set of views, such as login)? That is, default everything to logged-in-only + handle anonymous viewing explicitly, where needed.

Answer

tulsluper picture tulsluper · Feb 28, 2018
from django.shortcuts import redirect
from django.conf import settings


class LoginRequiredMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response
        self.login_url = settings.LOGIN_URL
        self.open_urls = [self.login_url] + \
                         getattr(settings, 'OPEN_URLS', [])

    def __call__(self, request):
        if not request.user.is_authenticated \
        and not request.path_info in self.open_urls:
            return redirect(self.login_url+'?next='+request.path)

        return self.get_response(request)