Tuesday, January 5, 2010

Blocking django admin to non-admin

Django is a fantastic web framework that makes web programming a breeze. One of its key features is the admin site which lets you create an admin panel almost without a line of code. But one of the problem I had with it is that the admin login page can be accessed from everyone, even if you are not an admin. Since I don't want people to see that page, I was looking for a way to disable the admin site and show it only if your have the superuser flag on your user, but didn't find anything useful. The solution is quite simple... Simply create a middleware that will disable any admin view unless your are logged in with an user with a superuser flag. Here is how your middleware should look like:

from django.http import Http404

class AdminDisableMiddleware(object):
    def process_view(self, request, view_func, view_args, view_kwargs):
        full_view_name = '%s.%s' % (view_func.__module__, view_func.__name__)
        if full_view_name.startswith('django.contrib.admin') and not request.user.is_superuser:
            raise Http404()
Note that I'm raising a http404 error, which should fool people trying to find the admin pages.