Requiring a Login for an Entire Django Powered Site

October 26, 2006

UPDATE: Read a newer post about this here.

For work I’m building a system for us to keep track of our work orders, projects, clients and more. All of this data is semi-sensitive yet must be accessible on the internet. Therefore this entire project needs to be password protected. After viewing one obsolete and an alternative solution I decided to write my own.

And I’ll share it here. It’s very simple.

We’re going to utilize Django’s Middleware feature. A description from the docs page:

Middleware is a framework of hooks into Django’s request/response processing. It’s a light, low-level “plugin” system for globally altering Django’s input and/or output.

This allows us to run code on every request if necessary. Create a middleware.py in your project directory and put the following in it:

from django.contrib.auth.views import login
from django.http import HttpResponseRedirect
class SiteLogin:
    "This middleware requires a login for every view"
    def process_request(self, request):
        if request.path != '/accounts/login/' and request.user.is_anonymous():
            if request.POST:
                return login(request)
            else:
                return HttpResponseRedirect('/accounts/login/?next=%s' % request.path)

Then put myproject.middleware.SiteLogin in your MIDDLEWARE_CLASSES in settings.py (replace myproject with your project name) and you’re done! Simple, no? Another example of the beauty of Django.

A colleague asked me today why I didn’t just put an if statement in my base template. This would work, but with a very important caveat. Checking user authentication in the template requires the authentication system to be loaded in the template context. This is fine if you’re only using Generic Views, otherwise you’d have to be sure to pass the proper context on each other view.

I’d rather knock it out in one fell swoop using Middleware.


Comments

might be nice to add the urls.py entries to get this working...

Posted by Mogga

Thanks!

Posted by Sameer Maggon

Add your comment

No HTML; Only URLs and line breaks are converted.