Skip to content

Commit

Permalink
Force the username to lowercase (#90)
Browse files Browse the repository at this point in the history
  • Loading branch information
MattBlack85 authored and kencochrane committed Jul 1, 2017
1 parent fc9d51e commit 85817fd
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 3 deletions.
13 changes: 13 additions & 0 deletions defender/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
DJANGO_VERSION = StrictVersion(get_version())

VALID_USERNAME = VALID_PASSWORD = 'valid'
UPPER_USERNAME = 'VALID'


class AccessAttemptTest(DefenderTestCase):
Expand Down Expand Up @@ -210,6 +211,18 @@ def test_blocked_username_cannot_login(self):
response = self._login(username=VALID_USERNAME, remote_addr='8.8.8.8')
self.assertContains(response, self.LOCKED_MESSAGE)

def test_blocked_username_uppercase_saved_lower(self):
"""
Test that a uppercase username is saved in lowercase
within the cache.
"""
for i in range(0, config.FAILURE_LIMIT + 2):
ip = '74.125.239.{0}.'.format(i)
self._login(username=UPPER_USERNAME, remote_addr=ip)

self.assertNotIn(UPPER_USERNAME, utils.get_blocked_usernames())
self.assertIn(UPPER_USERNAME.lower(), utils.get_blocked_usernames())

def test_cooling_off(self):
""" Tests if the cooling time allows a user to login
"""
Expand Down
18 changes: 15 additions & 3 deletions defender/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,14 +48,25 @@ def get_ip(request):
return ip_address


def lower_username(username):
"""
Single entry point to force the username to lowercase, all the functions
that need to deal with username should call this.
"""
if username:
return username.lower()
return None


def get_ip_attempt_cache_key(ip_address):
""" get the cache key by ip """
return "{0}:failed:ip:{1}".format(config.CACHE_PREFIX, ip_address)


def get_username_attempt_cache_key(username):
""" get the cache key by username """
return "{0}:failed:username:{1}".format(config.CACHE_PREFIX, username)
return "{0}:failed:username:{1}".format(config.CACHE_PREFIX,
lower_username(username))


def get_ip_blocked_cache_key(ip_address):
Expand All @@ -65,7 +76,8 @@ def get_ip_blocked_cache_key(ip_address):

def get_username_blocked_cache_key(username):
""" get the cache key by username """
return "{0}:blocked:username:{1}".format(config.CACHE_PREFIX, username)
return "{0}:blocked:username:{1}".format(config.CACHE_PREFIX,
lower_username(username))


def strip_keys(key_list):
Expand Down Expand Up @@ -128,7 +140,7 @@ def get_user_attempts(request, get_username=get_username_from_request):
"""
ip_address = get_ip(request)

username = get_username(request)
username = lower_username(get_username(request))

# get by IP
ip_count = REDIS_SERVER.get(get_ip_attempt_cache_key(ip_address))
Expand Down

0 comments on commit 85817fd

Please sign in to comment.