Login

Login Required Middleware

Author:
onecreativenerd
Posted:
November 10, 2008
Language:
Python
Version:
1.0
Score:
1 (after 1 ratings)

Sometimes it's a real pain to use the @login_required decorator all over the views of a complicated site. This middleware requires login on every page by default and supports a list of regular expression to figure out the exceptions. This way you don't have to worry about forgetting to decorate a view.

This snippet requires LOGIN_URL to be set in settings.py, and optionally allows you fill out LOGIN_EXEMPT_URLS, a tuple of regular expressions (similar to urls.py) that lists your exceptions.

Example:

`` LOGIN_EXEMPT_URLS = (

 r'^about\.html$',

 r'^legal/', # allow the entire /legal/* subsection

) ``

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
from django.http import HttpResponseRedirect
from django.conf import settings
from re import compile

EXEMPT_URLS = [compile(settings.LOGIN_URL.lstrip('/'))]
if hasattr(settings, 'LOGIN_EXEMPT_URLS'):
    EXEMPT_URLS += [compile(expr) for expr in settings.LOGIN_EXEMPT_URLS]

class LoginRequiredMiddleware:
    """
    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):
        assert hasattr(request, 'user'), "The Login Required middleware\
 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():
            path = request.path_info.lstrip('/')
            if not any(m.match(path) for m in EXEMPT_URLS):
                return HttpResponseRedirect(settings.LOGIN_URL)

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 10 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 10 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 5 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 6 months ago
  5. Help text hyperlinks by sa2812 1 year, 7 months ago

Comments

xiaket (on November 18, 2009):

Well, this would conflict with Django's default test framework, when you are running tests, you might have to disable this middleware.

#

nyambayar (on August 6, 2010):

great, thanks for posting.

#

cfingerh (on February 19, 2018):

if somebody still using this and migrating to Django 2 have a look at this https://stackoverflow.com/questions/42232606/django-exception-middleware-typeerror-object-takes-no-parameters

#

Please login first before commenting.