Skip to content

Instantly share code, notes, and snippets.

@ryanwitt
Last active November 25, 2017 15:33
Show Gist options
  • Star 13 You must be signed in to star a gist
  • Fork 8 You must be signed in to fork a gist
  • Save ryanwitt/130583 to your computer and use it in GitHub Desktop.
Save ryanwitt/130583 to your computer and use it in GitHub Desktop.
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.middleware.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)
@kevinlondon
Copy link

This is great, thanks.

Just an fyi, there's a slight typo:
'django.contrib.auth.middlware.AuthenticationMiddleware'
should be
'django.contrib.auth.middleware.AuthenticationMiddleware'
There's an e missing in "middleware".

@ryanwitt
Copy link
Author

👍 thanks!

@pwhipp
Copy link

pwhipp commented Jun 10, 2014

👍 Just found and used this with no problems on a Django 1.6 site. Nice.

@bhaugen
Copy link

bhaugen commented Aug 1, 2016

Works great in 1.8! 😺

@nobiki
Copy link

nobiki commented Mar 28, 2017

nobiki/login_required_middleware.py
I changed this way on the site of Django 1.10, and now it works without problems. Thank you.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment