| 1 | = IP Access Middleware = |
| 2 | |
| 3 | == The idea == |
| 4 | |
| 5 | Control 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 | |
| 9 | You must define a model that permits defining a tuple (ip addr, user): ip from browser that connect, and users that authenticated. |
| 10 | |
| 11 | This is the model proposed (it would be in a file like ''myapp.models.py''): |
| 12 | |
| 13 | {{{ |
| 14 | |
| 15 | from django.contrib.auth.models import User |
| 16 | |
| 17 | class 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 | |
| 36 | The middleware mission is authenticate automatically with an user defined in models, '''if''' the remote ip address exists in IPAccess table. |
| 37 | |
| 38 | This is the code (in file ''myapp.middleware.py''): |
| 39 | |
| 40 | {{{ |
| 41 | |
| 42 | from django.contrib.auth.models import AnonymousUser |
| 43 | from myapp.models import IPAccess |
| 44 | |
| 45 | class 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 | |
| 60 | The middleware installation requires you insert ''IPAccessMiddleware'' into ''MIDDLEWARE_CLASSES''. Obviusly, it also requires the installation of ''AutenticationMiddleware''. |
| 61 | |
| 62 | The code would be like that: |
| 63 | |
| 64 | {{{ |
| 65 | |
| 66 | MIDDLEWARE_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 | }}} |