From 15e6a40e0a40c6eccbdb6956e0890ffe89902148 Mon Sep 17 00:00:00 2001 From: Ken Cochrane Date: Wed, 31 Dec 2014 19:27:18 -0500 Subject: [PATCH] more refactoring to clean up the code --- defender/decorators.py | 24 ++++-------------------- defender/utils.py | 20 ++++++++++++++++++++ 2 files changed, 24 insertions(+), 20 deletions(-) diff --git a/defender/decorators.py b/defender/decorators.py index acfc1fc..b5ce8bb 100644 --- a/defender/decorators.py +++ b/defender/decorators.py @@ -1,16 +1,5 @@ -import logging -from django.conf import settings - -from .models import AccessAttempt from . import utils -# use a specific username field to retrieve from login POST data -USERNAME_FORM_FIELD = getattr(settings, - 'DEFENDER_USERNAME_FORM_FIELD', - 'username') - -log = logging.getLogger(__name__) - def watch_login(func): """ @@ -43,15 +32,10 @@ def watch_login(func): response.status_code != 302 ) - AccessAttempt.objects.create( - user_agent=request.META.get('HTTP_USER_AGENT', - '')[:255], - ip_address=utils.get_ip(request), - username=request.POST.get(USERNAME_FORM_FIELD, None), - http_accept=request.META.get('HTTP_ACCEPT', ''), - path_info=request.META.get('PATH_INFO', ''), - login_valid=not login_unsuccessful, - ) + # ideally make this background task, but to keep simple, keeping + # it inline for now. + utils.add_login_attempt(request, not login_unsuccessful) + if utils.check_request(request, login_unsuccessful): return response diff --git a/defender/utils.py b/defender/utils.py index 1db1a78..eae4436 100644 --- a/defender/utils.py +++ b/defender/utils.py @@ -9,6 +9,8 @@ from django.shortcuts import render_to_response from django.template import RequestContext from django.utils.translation import ugettext_lazy +from .models import AccessAttempt + REDIS_HOST = settings.REDIS_HOST REDIS_PORT = settings.REDIS_PORT REDIS_PASSWORD = settings.REDIS_PASSWORD @@ -47,6 +49,11 @@ LOCKOUT_TEMPLATE = getattr(settings, 'DEFENDER_LOCKOUT_TEMPLATE', None) ERROR_MESSAGE = ugettext_lazy("Please enter a correct username and password. " "Note that both fields are case-sensitive.") +# use a specific username field to retrieve from login POST data +USERNAME_FORM_FIELD = getattr(settings, + 'DEFENDER_USERNAME_FORM_FIELD', + 'username') + redis_server = redis.StrictRedis( host=REDIS_HOST, port=REDIS_PORT, db=REDIS_DB, password=REDIS_PASSWORD) @@ -264,3 +271,16 @@ def check_request(request, login_unsuccessful): else: # add a failed attempt for this user return record_failed_attempt(ip_address, username) + + +def add_login_attempt(request, login_valid): + """ Create a record for the login attempt """ + AccessAttempt.objects.create( + user_agent=request.META.get('HTTP_USER_AGENT', + '')[:255], + ip_address=get_ip(request), + username=request.POST.get(USERNAME_FORM_FIELD, None), + http_accept=request.META.get('HTTP_ACCEPT', ''), + path_info=request.META.get('PATH_INFO', ''), + login_valid=login_valid, + )