I’ve recently been working on a project where I wanted to restrict access to my admin views by ip address in the form of a white list. With the aim being that it would provide an extra level of protection ontop of the existing login process.
The idea is fairly simple, if the requesters ip address is not in a predefined list then return a 404, otherwise render the view as normal. This can be achieved using a standard python decorator - easily allowing you to selectively restrict access to views .
The code is fairly short and included here. Firstly create a new entry in your settings file. note: I’ve used the same variable as the fantastic django debug toolbar.
settings.py
INTERNAL_IPS = ('127.0.0.1','192.168.1.2')
Then I’ve created a decorators.py in the project root which contains the key bit of code.
decorators.py:
from django.http import Http404
from project.settings import INTERNAL_IPS
def protectview(func):
def decorator(request,*args, **kwargs):
if request.META['REMOTE_ADDR'] not in INTERNAL_IPS:
raise Http404()
return func(request, *args, **kwargs)
return decorator
Then to restrict a sample view all you need to do is place the decorator above it.
views.py
from project.decorators import protectview
from django.shortcuts import render_to_response
@protectview
def adminlogin(request):
return render_to_response('adminlogin.html')
I’m certain that this is not fool proof but it will prevent the casual observer (or search spider) from finding the administrative section of your site.