I have a small Django application with a view that I want to restrict to certain users. Anyone from a specific network should be able to see that view without any further au
There are two suitable approaches for that kind of authentication:
A sample middleware can be something like:
ALLOWED_IP_BLOCKS = [......]
class NeedToLoginMiddleware(object):
def process_request(self, request):
ip = request.META['REMOTE_ADDR']
if not ip in ALLOWED_IP_BLOCKS: #ip check
if not request.user.is_authenticated(): #if ip check failed, make authentication check
return HttpResponseRedirect(...)
return None
If you are using django authentication and REMOTE_ADDR is not in ALLOWED_IP_BLOCKS list, then you can use is_authenticated to check if related user had logged in or not. But for using is_authenticated in a custom middleware, your custom middleware must be placed after AuthenticationMiddleware, because request.user is set on that level.
MIDDLEWARE_CLASSES = (
...
'django.contrib.auth.middleware.AuthenticationMiddleware',
'path.to.my.NeedToLoginMiddleware',
...
)
request.path and check if the request url requires ip check/authentication.More info about custom middleware classes