Skip to content

Instantly share code, notes, and snippets.

@r0yfire
Created May 6, 2014 17:47
Show Gist options
  • Save r0yfire/09e61e04ae8bb68f49de to your computer and use it in GitHub Desktop.
Save r0yfire/09e61e04ae8bb68f49de to your computer and use it in GitHub Desktop.
Django Login Required Middleware
from re import compile
from django.conf import settings
from django.http import HttpResponseRedirect
from django.utils.http import is_safe_url
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.
Based on https://djangosnippets.org/snippets/1179/
My modification adds 'next' GET parameter to enable redirection after
successful login.
"""
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):
redirect_to = settings.LOGIN_URL
# Add 'next' GET variable to support redirection after login
if len(path) > 0 and is_safe_url(url=request.path_info, host=request.get_host()):
redirect_to = "%s?next=%s" %(settings.LOGIN_URL, request.path_info)
return HttpResponseRedirect(redirect_to)
@theshane
Copy link

Hello, thanks for posting this. I am getting TypeError: object() takes no parameters. If I remove this class from the Middleware array, it works fine.

Any Ideas?

@ajmaln
Copy link

ajmaln commented Feb 28, 2017

Hello, thanks for posting this. I am getting TypeError: object() takes no parameters. If I remove this class from the Middleware array, it works fine.
Any Ideas?

I think you are using django 1.10, there is a little modification to be done for django 1.10

Import the MiddlewareMixin from django.utils.deprecation. Modify the LoginRequiredMiddleware class to inherit from the MiddlewareMixin.

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