Changes between Initial Version and Version 1 of CookBookIPAccessMiddleware


Ignore:
Timestamp:
Dec 21, 2006, 5:58:54 PM (17 years ago)
Author:
Manuel Saelices <msaelices@…>
Comment:

ip access control in middleware

Legend:

Unmodified
Added
Removed
Modified
  • CookBookIPAccessMiddleware

    v1 v1  
     1= IP Access Middleware =
     2
     3== The idea ==
     4
     5Control 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.
     6
     7== IPAccess Model ==
     8
     9You must define a model that permits defining a tuple (ip addr, user): ip from browser that connect, and users that authenticated.
     10
     11This is the model proposed (it would be in a file like ''myapp.models.py''):
     12
     13{{{
     14
     15from django.contrib.auth.models import User
     16
     17class IPAccess(models.Model):
     18    ip = models.IPAddressField(unique=True, db_index=True)
     19    user = models.ForeignKey(User, verbose_name='user that authenticates')
     20
     21    def __str__(self):
     22        return self.ip
     23
     24    class Meta:
     25        verbose_name = _('IP Access')
     26        verbose_name_plural = _('IP Accesses')
     27
     28    class Admin:
     29        list_display = ('ip', 'user')
     30
     31}}}
     32
     33
     34== IPAccess Middleware ==
     35
     36The middleware mission is authenticate automatically with an user defined in models, '''if''' the remote ip address exists in IPAccess table.
     37
     38This is the code (in file ''myapp.middleware.py''):
     39
     40{{{
     41
     42from django.contrib.auth.models import AnonymousUser
     43from myapp.models import IPAccess
     44
     45class IPAccessMiddleware(object):
     46    def process_request(self, request):
     47        if request.user == AnonymousUser():
     48            remoteip = request.META['REMOTE_ADDR']
     49            try:
     50                ipaccess = IPAccess.objects.get(ip=remoteip)
     51                request.user = ipaccess.user
     52            except IPAccess.DoesNotExist:
     53                pass
     54        return None
     55
     56}}}
     57
     58== Settings ==
     59
     60The middleware installation requires you insert ''IPAccessMiddleware'' into ''MIDDLEWARE_CLASSES''. Obviusly, it also requires the installation of ''AutenticationMiddleware''.
     61
     62The code would be like that:
     63
     64{{{
     65
     66MIDDLEWARE_CLASSES = (
     67    'django.middleware.common.CommonMiddleware',
     68    'django.contrib.sessions.middleware.SessionMiddleware',
     69    'django.contrib.auth.middleware.AuthenticationMiddleware',
     70    'django.middleware.doc.XViewMiddleware',
     71    'aceprensa.apps.news.middleware.IPAccessMiddleware',
     72)
     73
     74}}}
Back to Top