Login

Middleware to prevent access to the admin when user ip not in INTERNAL_IPS

Author:
jezdez
Posted:
July 5, 2010
Language:
Python
Version:
1.2
Tags:
middleware admin
Score:
2 (after 2 ratings)

This middleware will prevent access to the admin if the users IP isn't in the INTERNAL_IPS setting, by comparing the request path with the reversed index URL of the default admin site, ultimately raising a 404 (unless DEBUG = True).

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
from django.conf import settings
from django.core.urlresolvers import reverse, NoReverseMatch
from django.http import Http404

class InternalUseOnlyMiddleware(object):
    """
    Middleware to prevent access to the admin if the user IP
    isn't in the INTERNAL_IPS setting.
    """
    def process_request(self, request):
        try:
            admin_index = reverse('admin:index')
        except NoReverseMatch:
            return
        if not request.path.startswith(admin_index):
            return
        remote_addr = request.META.get(
            'HTTP_X_REAL_IP', request.META.get('REMOTE_ADDR', None))
        if not remote_addr in settings.INTERNAL_IPS and not settings.DEBUG:
            raise Http404

More like this

  1. Restrict staff access to admin pages by slink 4 years, 10 months ago
  2. Support IP ranges in INTERNAL_IPS by jdunck 5 years, 7 months ago
  3. Internal view decorator by gsakkis 5 years, 1 month ago
  4. Firebug Lite Middleware by jfw 6 years, 10 months ago
  5. IP Authorisation Decorator by pliskin 4 years, 11 months ago

Comments

diverman (on July 5, 2010):

What about raising "Forbidden" instead of "Not found"? Have you tried access control using Apache directives?

#

blueyonder (on March 29, 2012):

works like a charm, thanks

#

Please login first before commenting.