Middleware to prevent access to the admin when user ip not in INTERNAL_IPS

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

fromdjango.confimportsettingsfromdjango.core.urlresolversimportreverse,NoReverseMatchfromdjango.httpimportHttp404classInternalUseOnlyMiddleware(object):""" Middleware to prevent access to the admin if the user IP isn't in the INTERNAL_IPS setting. """defprocess_request(self,request):try:admin_index=reverse('admin:index')exceptNoReverseMatch:returnifnotrequest.path.startswith(admin_index):returnremote_addr=request.META.get('HTTP_X_REAL_IP',request.META.get('REMOTE_ADDR',None))ifnotremote_addrinsettings.INTERNAL_IPSandnotsettings.DEBUG:raiseHttp404