S
S
s1veme2020-07-26 15:05:17
Django
s1veme, 2020-07-26 15:05:17

How to secure django admin?

I have a Django site, you need to either hide the admin panel, or make protection from brute force (Ban IP). How can this be done?
If it's not difficult - throw an article or code.

Thanks in advance.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
V
Vadim Shatalov, 2020-07-26
@aleksegolubev

https://www.timo-zimmermann.de/2020/06/adding-two-...

S
Sergey Gornostaev, 2020-07-26
@sergey-gornostaev

auth.py

import datetime
import hashlib

from django.conf import settings
from django.contrib.auth.backends import ModelBackend
from django.contrib.auth.models import User
from django.core.cache import cache


class BruteForceProtectedAuthBackend(ModelBackend):
    def authenticate(self, request, username=None, password=None):
        if username is None:
            return None

        if getattr(settings, 'AUTH_BLOCK_RATE', None):
            now = datetime.datetime.now()
            key = hashlib.md5(username.encode('utf-8')).hexdigest()
            last_user_login = cache.get(key + '-login-timestamp', now - datetime.timedelta(days=1))
            cache.set(key + '-login-timestamp', now)
            if (now - last_user_login) < datetime.timedelta(seconds=settings.AUTH_BLOCK_RATE):
                return None

        try:
            user = User.objects.get(username=username)
            if user.check_password(password):
                return user
        except User.DoesNotExist:
            return None

settings.py
AUTHENTICATION_BACKENDS = [
    'auth.BruteForceProtectedAuthBackend',
]

Naturally, you need to set up centralized caching, for example, based on memcached.

D
Dr. Bacon, 2020-07-26
@bacon

"brute force protection" - nginx limit_req or configure fail2ban

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question