Code


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

Included link to Cookbook index

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 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 remote ip address exists in IPAccess table.

This is the code (in file myapp/middleware.py):

from django.contrib.auth.models import AnonymousUser
from 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',
)

Attachments (1)

Download all attachments as: .zip