middleware.py 1.39 KB
Newer Older
Florent Chehab's avatar
Florent Chehab committed
1 2 3 4 5 6
from django.utils.deprecation import MiddlewareMixin

from django.http import HttpResponseRedirect
from django.conf import settings
from re import compile

Florent Chehab's avatar
Florent Chehab committed
7
EXEMPT_URLS = []
8 9
if hasattr(settings, "LOGIN_EXEMPT_URLS"):
    EXEMPT_URLS += [compile(str.lstrip("/")) for str in settings.LOGIN_EXEMPT_URLS]
Florent Chehab's avatar
Florent Chehab committed
10

Florent Chehab's avatar
Florent Chehab committed
11

Florent Chehab's avatar
Florent Chehab committed
12 13 14 15 16 17 18 19 20 21 22 23
class LoginRequiredMiddleware(MiddlewareMixin):
    """
    Middleware that requires a user to be authenticated to view any page other
    than LOGIN_URL. Exemptions to this requirement can optionally be specified
    in settings via a list of regular expressions in LOGIN_EXEMPT_URLS (which
    you can copy from your urls.py).

    Requires authentication middleware and template context processors to be
    loaded. You'll get an error if they aren't.
    """

    def process_request(self, request):
24 25 26
        assert hasattr(
            request, "user"
        ), "The Login Required middleware\
Florent Chehab's avatar
Florent Chehab committed
27 28 29 30 31 32
 requires authentication middleware to be installed. Edit your\
 MIDDLEWARE_CLASSES setting to insert\
 'django.contrib.auth.middlware.AuthenticationMiddleware'. If that doesn't\
 work, ensure your TEMPLATE_CONTEXT_PROCESSORS setting includes\
 'django.core.context_processors.auth'."
        if not request.user.is_authenticated:
33
            path = request.path_info.lstrip("/")
Florent Chehab's avatar
Florent Chehab committed
34
            if not any(m.match(path) for m in EXEMPT_URLS):
35
                return HttpResponseRedirect(settings.LOGIN_URL + "?next=/" + path)