CookBook - IP Access Middleware

The idea

The idea of this recipe is to provide automatic user authentication based on specified IP addresses for some client computers.

IPAccess Model

You must define a model that allows to specify tuples of type (IP addr, user): IP of the client computer with the web browser, user to be authenticated.

This is the proposed model (suppose myproj/myapp/

from django.contrib.auth.models import User

class IPAccess(models.Model):
    ip = models.IPAddressField(unique=True, db_index=True)
    user = models.ForeignKey(User, verbose_name='user that authenticates')

    def __str__(self):
        return self.ip

    class Meta:
        verbose_name = 'IP Access'
        verbose_name_plural = 'IP Accesses'

    class Admin:
        list_display = ('ip', 'user')

IPAccess Middleware

The mission of this middleware is to authenticate automatically with an user defined in models, only if the browser's remote IP address exists in the IPAccess table.

This is the code (in file myproj/myapp/

from django.contrib.auth.models import AnonymousUser
from myproj.myapp.models import IPAccess

class IPAccessMiddleware(object):
    def process_request(self, request):
        if request.user == AnonymousUser():
            remoteip = request.META['REMOTE_ADDR']
                ipaccess = IPAccess.objects.get(ip=remoteip)
                request.user = ipaccess.user
            except IPAccess.DoesNotExist:
        return None


For the middleware to work, you have to insert a line with IPAccessMiddleware into MIDDLEWARE_CLASSES of the file. Obviously, it also requires the installation of AuthenticationMiddleware.

The code should be something like this:


A Complete Application

I have also developed an application which offers this functionality. To install it, just untar the files in this archive and put it in apps directory in your project, then change the import statements and add a two lines to the file:


Have fun.

Last modified 17 years ago Last modified on Dec 22, 2006, 5:37:33 AM

Attachments (1)

Download all attachments as: .zip

Note: See TracWiki for help on using the wiki.
Back to Top