From c86ad06d9d82314b42c9429249bc5d6e9c166d41 Mon Sep 17 00:00:00 2001 From: Jack Sullivan Date: Sat, 22 Apr 2017 19:19:48 -0700 Subject: [PATCH] Fixed #222, cache blocks by user only and ip+user Cache hash keys now include usernames. The axes settings AXES_ONLY_USER_FAILURES and LOCK_OUT_BY_COMBINATION_USER_AND_IP are checked to decide which request attributes to include in generated cache hash keys. --- axes/decorators.py | 23 +++++++++++++++-------- axes/tests.py | 2 +- 2 files changed, 16 insertions(+), 9 deletions(-) diff --git a/axes/decorators.py b/axes/decorators.py index 2099013..7169ad6 100644 --- a/axes/decorators.py +++ b/axes/decorators.py @@ -499,23 +499,30 @@ def get_cache_key(request_or_object): :param request_or_object: Request or AccessAttempt object :return cache-key: String, key to be used in cache system """ - ua = None - ip = None - if isinstance(request_or_object, AccessAttempt): ip = request_or_object.ip_address + un = request_or_object.username ua = request_or_object.user_agent else: ip = get_ip(request_or_object) + un = request_or_object.POST.get(USERNAME_FORM_FIELD, None) ua = request_or_object.META.get('HTTP_USER_AGENT', '')[:255] - ip = ip.encode('utf-8') + ip = ip.encode('utf-8') if ip else '' + un = un.encode('utf-8') if un else '' + ua = ua.encode('utf-8') if ua else '' - if ua: - ua = ua.encode('utf-8') - cache_hash_key = 'axes-{}'.format(md5(ip+ua).hexdigest()) + if AXES_ONLY_USER_FAILURES: + attributes = un + elif LOCK_OUT_BY_COMBINATION_USER_AND_IP: + attributes = ip+un else: - cache_hash_key = 'axes-{}'.format(md5(ip).hexdigest()) + attributes = ip + + if USE_USER_AGENT: + attributes += ua + + cache_hash_key = 'axes-{}'.format(md5(attributes).hexdigest()) return cache_hash_key diff --git a/axes/tests.py b/axes/tests.py index f0e995b..1ce899e 100644 --- a/axes/tests.py +++ b/axes/tests.py @@ -213,7 +213,7 @@ class AccessAttemptTest(TestCase): ip = '127.0.0.1'.encode('utf-8') ua = ''.encode('utf-8') - cache_hash_key_checker = 'axes-{}'.format(md5((ip+ua)).hexdigest()) + cache_hash_key_checker = 'axes-{}'.format(md5((ip)).hexdigest()) request_factory = RequestFactory() request = request_factory.post('/admin/login/',