Code


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

added a completed app

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/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

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

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

The code would be like that:

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

Complete Application

I also developed ipaccess application which offers this functionality. For installing you have to untar compressed application and put in apps directory in your project. Then, you have to update import statements and add to applications installed settings:

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

Attachments (1)

Download all attachments as: .zip