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
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. Template tag - list punctuation for a list of items by shapiromatron 11 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 6 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 7 months ago
  5. Help text hyperlinks by sa2812 1 year, 7 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

#

Dupietje (on December 21, 2016):

Version django 1.10 (and perhaps higher)

class RestrictAdminByIp(object): """ This middleware-class will blocked all the /admin request if : # not in DEBUG # the client IP is not in settings.INTERNAL_IPS """ def init(self, get_response): self.get_response = get_response # One-time configuration and initialization.

def __call__(self, request):
    # Code to be executed for each request before
    # the view (and later middleware) are called.
    try:
        admin_index = reverse('admin:index')
        if not settings.DEBUG and request.path.startswith(admin_index):
            remote_addr = request.META.get(
                'HTTP_X_REAL_IP',
                request.META.get('REMOTE_ADDR', None)
            )
            if not remote_addr in settings.INTERNAL_IPS:
                raise Http404
    except NoReverseMatch:
        pass

    response = self.get_response(request)

    # Code to be executed for each request/response after
    # the view is called.
    return response

#

Please login first before commenting.