Skip to content

Commit

Permalink
send user/ip blocked signal only once
Browse files Browse the repository at this point in the history
  • Loading branch information
horida authored and kencochrane committed Sep 16, 2019
1 parent fcfa88d commit ce95906
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 2 deletions.
28 changes: 28 additions & 0 deletions defender/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -948,6 +948,20 @@ def handler(sender, ip_address, **kwargs):
utils.unblock_ip('8.8.8.8')
self.assertIsNone(self.blocked_ip)

def test_should_not_send_signal_when_ip_already_blocked(self):
self.blocked_ip = None

def handler(sender, ip_address, **kwargs):
self.blocked_ip = ip_address

ip_block_signal.connect(handler)

key = utils.get_ip_blocked_cache_key('8.8.8.8')
utils.REDIS_SERVER.set(key, 'blocked')

utils.block_ip('8.8.8.8')
self.assertIsNone(self.blocked_ip)

def test_should_send_signal_when_blocking_username(self):
self.blocked_username = None

Expand All @@ -968,6 +982,20 @@ def handler(sender, username, **kwargs):
utils.unblock_username('richard_hendricks')
self.assertIsNone(self.blocked_username)

def test_should_not_send_signal_when_username_already_blocked(self):
self.blocked_username = None

def handler(sender, username, **kwargs):
self.blocked_username = username

username_block_signal.connect(handler)

key = utils.get_username_blocked_cache_key('richard hendricks')
utils.REDIS_SERVER.set(key, 'blocked')

utils.block_ip('richard hendricks')
self.assertIsNone(self.blocked_username)


class DefenderTestCaseTest(DefenderTestCase):
""" Make sure that we're cleaning the cache between tests """
Expand Down
8 changes: 6 additions & 2 deletions defender/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -174,12 +174,14 @@ def block_ip(ip_address):
if config.DISABLE_IP_LOCKOUT:
# no need to block, we disabled it.
return
already_blocked = is_source_ip_already_locked(ip_address)
key = get_ip_blocked_cache_key(ip_address)
if config.COOLOFF_TIME:
REDIS_SERVER.set(key, 'blocked', config.COOLOFF_TIME)
else:
REDIS_SERVER.set(key, 'blocked')
send_ip_block_signal(ip_address)
if not already_blocked:
send_ip_block_signal(ip_address)


def block_username(username):
Expand All @@ -190,12 +192,14 @@ def block_username(username):
if config.DISABLE_USERNAME_LOCKOUT:
# no need to block, we disabled it.
return
already_blocked = is_user_already_locked(username)
key = get_username_blocked_cache_key(username)
if config.COOLOFF_TIME:
REDIS_SERVER.set(key, 'blocked', config.COOLOFF_TIME)
else:
REDIS_SERVER.set(key, 'blocked')
send_username_block_signal(username)
if not already_blocked:
send_username_block_signal(username)


def record_failed_attempt(ip_address, username):
Expand Down

0 comments on commit ce95906

Please sign in to comment.