2๐
I use two methods:
The authentication backend caching a last login attempt and rejects the too frequents attempts.
from django.conf import settings
from django.contrib.auth.models import User
from django.contrib.auth.backends import ModelBackend
from django.core.cache import cache
import datetime
class BruteForceProtectedAuthBackend(ModelBackend):
def authenticate(self, username=None, password=None):
now = datetime.datetime.now()
last_login = cache.get(username + '-login-attempt', now - datetime.timedelta(days=1))
cache.set(username + '-login-attempt', now)
if (now - last_login) < datetime.timedelta(seconds=settings.AUTH_RATE):
return None
try:
user = User.objects.get(username=username)
if user.check_password(password):
return user
else:
return None
except User.DoesNotExist:
return None
def get_user(self, user_id):
try:
return User.objects.get(pk=user_id)
except User.DoesNotExist:
return None
Middleware rejecting request to admin urls from non local IP addresses.
from django.http import HttpResponseForbidden
from django.conf import settings
from ipware.ip import get_ip
class ProtectAdminSiteMiddleware(object):
def process_request(self, request):
if request.path.startswith(reverse('admin:index')):
remote_addr = get_ip(request)
if remote_addr is None:
return HttpResponseForbidden('Forbiden')
else:
if not remote_addr in settings.INTERNAL_IPS:
return HttpResponseForbidden('Forbiden')
return None
Source:stackexchange.com