Version 7 (modified by Manuel Saelices <msaelices@…>, 13 years ago) (diff)

another fix

CookBook - IP Access Middleware

The idea

Controling IP access in your web app. The idea provided in this cookbook let you define specific ip addresses, and controlling accessing from those ips. If an user access from a certain IP, automatically authenticates with a defined user.

IPAccess Model

You must define a model that permits defining a tuple (ip addr, user): ip from browser that connect, and users that authenticated.

This is the model proposed (it would be in a file like 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

Middleware mission is authenticate automatically with an user defined in models, only if the remote ip address exists in 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


The middleware installation requires you insert IPAccessMiddleware into MIDDLEWARE_CLASSES. Obviusly, it also requires the installation of ''AuthenticationMiddleware.

The code would be like that:


Attachments (1)

Download all attachments as: .zip

Back to Top