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/models.py):

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/middleware.py):

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']
            try:
                ipaccess = IPAccess.objects.get(ip=remoteip)
                request.user = ipaccess.user
            except IPAccess.DoesNotExist:
                pass
        return None

Settings

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

The code should be something like this:

MIDDLEWARE_CLASSES = (
    'django.middleware.common.CommonMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.middleware.doc.XViewMiddleware',
    'myproj.apps.myapp.middleware.IPAccessMiddleware',
)

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 settings.py file:

INSTALLED_APPS = (
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    'django.contrib.comments',
    'django.contrib.admin',
    'myproj.apps.myapp',
    'myproj.apps.ipaccess',
)

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