perf: 优化ip黑白名单

This commit is contained in:
feng626
2021-11-18 22:20:35 +08:00
committed by Jiangjie.Bai
parent bd92045b50
commit 3052c4cc19
7 changed files with 171 additions and 136 deletions

View File

@@ -11,7 +11,7 @@ from django.conf import settings
from django.core.cache import cache
from common.tasks import send_mail_async
from common.utils import reverse, get_object_or_none
from common.utils import reverse, get_object_or_none, ip
from .models import User
logger = logging.getLogger('jumpserver')
@@ -180,33 +180,37 @@ class BlockGlobalIpUtilBase:
self.ip = ip
self.limit_key = self.LIMIT_KEY_TMPL.format(ip)
self.block_key = self.BLOCK_KEY_TMPL.format(ip)
self.key_ttl = int(settings.SECURITY_LOGIN_LIMIT_TIME) * 60
self.key_ttl = int(settings.SECURITY_LOGIN_IP_LIMIT_TIME) * 60
@property
def ip_in_black_list(self):
return self.ip in settings.SECURITY_LOGIN_IP_BLACK_LIST
return ip.contains_ip(self.ip, settings.SECURITY_LOGIN_IP_BLACK_LIST)
@property
def ip_in_white_list(self):
return ip.contains_ip(self.ip, settings.SECURITY_LOGIN_IP_WHITE_LIST)
def set_block_if_need(self):
if not self.ip_in_black_list:
if self.ip_in_white_list or self.ip_in_black_list:
return
count = cache.get(self.limit_key, 0)
count += 1
cache.set(self.limit_key, count, self.key_ttl)
limit_count = settings.SECURITY_LOGIN_LIMIT_COUNT
limit_count = settings.SECURITY_LOGIN_IP_LIMIT_COUNT
if count < limit_count:
return
cache.set(self.block_key, True, self.key_ttl)
def clean_block_if_need(self):
if not self.ip_in_black_list:
return
cache.delete(self.limit_key)
cache.delete(self.block_key)
def is_block(self):
if not self.ip_in_black_list:
if self.ip_in_white_list:
return False
if self.ip_in_black_list:
return True
return bool(cache.get(self.block_key))