[Django]-DJANGO allow access to a certain view only from a VPN Network

0👍

You can use REMOTE_ADDR from HttpRequest.META (http://docs.djangoproject.com/en/dev/ref/request-response/) to check the requester IP in your view. And if it is different form the one you want just return 404 or 403 page.

1👍

You can implement a simple middleware which will block any requests outside allowed IP addresses:

from django.conf import settings
from django.core.urlresolvers import reverse, NoReverseMatch
from django.http import Http404

class InternalUseOnlyMiddleware(object):
    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

Original source: https://djangosnippets.org/snippets/2095/

👤Viliam

Leave a comment