Django provides a decorator called login_required
that takes one of your views and prevents a user from seeing it unless they are logged in. Every time we need to add this decorator above view. Sometimes it’s a real pain to use the login_required
decorator all over the views of your complicated site. What if you forget to add it to view that contains sensitive information?
Django allows you to write middleware that gets access to each request so you can add functionality that can be applied to your whole site. My middleware simply intercepts each request and redirects users to the site login page if they haven’t logged in. It also allows you to give of exceptions (in the form of regular expressions), i.e. pages that can be viewed without logging in.
Creates login_required_middleware.py
file.
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(object):
"""
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 __init__(self, get_response):
self.get_response = get_response
def __call__(self, request):
print "settings.DEBUG: ", settings.DEBUG
assert hasattr(request, 'user'), "The Login Required middleware\
requires authentication middleware to be installed. Edit your\
MIDDLEWARE 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)
return self.get_response(request)
Change or add settings.py
file as given below:
# settings.py
LOGIN_URL = '/login/'
LOGIN_EXEMPT_URLS = (
r'^$',
r'^oauth/',
r'^media/',
)
MIDDLEWARE_CLASSES = (
# ...
'python.path.to.LoginRequiredMiddleware',
)
Here is my login_required_middleware.py and settings.py file.
Source: http://onecreativeblog.com/post/59051248/django-login-required-middleware
https://docs.djangoproject.com/en/1.10/topics/http/middleware/#writing-your-own-middleware