开发者

DJANGO allow access to a certain view only from a VPN Network

开发者 https://www.devze.com 2023-01-09 07:32 出处:网络
I am trying to specify the access to a certain django view only to a client calling froma VPN IP(10.8.0.3 )

I am trying to specify the access to a certain django view only to a client calling from a VPN IP (10.8.0.3 )

My django server is supported by apache using the following .conf

<VirtualHost *>
    ServerAdmin webmaster@demo.cl
    DocumentRoot /home/project/virtualenvs/env1
    ServerName client1.project.cl
    ServerAlias www.client1.project.cl
    ErrorLog /var/log/apache2/error.log
    CustomLog /var/log/apache2/access.log combined

<Location "/">
SetHandler python-program
PythonHandler virtualhandler
SetEnv DJANGO_SETTINGS_MODULE project.settings
PythonOption django.root
SetEnv SITE_CLIENT_ID client1
PythonDebug On
PythonPath "['/home/project/virtualenvs/env1/django-site','/home/project/virtualenvs/env1/bin'] + sys.path"
</Location>

Alias /media "/home/project/virtualenvs/env1/lib/python2.6/site-packages/django/contrib/admin/media/"

<Location /media>
    SetHandler None
</Location>

<Location /nodesaccess >
        order Deny,Allow
        Deny from all
        Allow from 10.8.0.3
        SetHandler python-program
        PythonHandler virtualhandler
        SetEnv DJANGO_SETTINGS_MODULE project.settings
        PythonOption django.root
        Se开发者_JS百科tEnv SITE_CLIENT_ID client1
        PythonDebug On
        PythonPath "['/home/project/virtualenvs/env1/django-    site','/home/project/virtualenvs/env1/bin'] + sys.path"

</Location>


</VirtualHost>

This previous configuration allows to create many django applications depending of the url, I recover the env variable and then apache load a certain setting.py which is exclusive and depends of the subdomain. Very interesting

Everything works fine (my applications) except that the access can not be denied using the "Allow from 10.8.0.3"

Any ideas?

Thank you


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/


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消