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 | from django.conf import settings
from django.core.urlresolvers import reverse, NoReverseMatch
from django.http import Http404
class InternalUseOnlyMiddleware(object):
"""
Middleware to prevent access to the admin if the user IP
isn't in the INTERNAL_IPS setting.
"""
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
|
More like this
- Template tag - list punctuation for a list of items by shapiromatron 11 months, 2 weeks ago
- JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months, 3 weeks ago
- Serializer factory with Django Rest Framework by julio 1 year, 6 months ago
- Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 7 months ago
- Help text hyperlinks by sa2812 1 year, 7 months ago
Comments
What about raising "Forbidden" instead of "Not found"? Have you tried access control using Apache directives?
#
works like a charm, thanks
#
Version django 1.10 (and perhaps higher)
class RestrictAdminByIp(object): """ This middleware-class will blocked all the /admin request if : # not in DEBUG # the client IP is not in settings.INTERNAL_IPS """ def init(self, get_response): self.get_response = get_response # One-time configuration and initialization.
#
Please login first before commenting.