annotate antispam/decorators.py @ 690:988782c6ce6c

For #48, rework blocking code to use fail2ban.
author Brian Neal <bgneal@gmail.com>
date Sun, 01 Sep 2013 00:15:42 -0500
parents 89b240fe9297
children 4a49d4ac319f
rev   line source
bgneal@472 1 """
bgneal@472 2 This module contains decorators for the antispam application.
bgneal@472 3
bgneal@472 4 """
bgneal@679 5 import json
bgneal@472 6 from functools import wraps
bgneal@690 7 import logging
bgneal@472 8
bgneal@472 9
bgneal@690 10 def log_auth_failures(auth_type):
bgneal@472 11
bgneal@472 12 def decorator(fn):
bgneal@690 13 logger = logging.getLogger('auth')
bgneal@472 14
bgneal@472 15 @wraps(fn)
bgneal@472 16 def wrapped(request, *args, **kwargs):
bgneal@472 17
bgneal@472 18 response = fn(request, *args, **kwargs)
bgneal@472 19
bgneal@472 20 if request.method == 'POST':
bgneal@505 21
bgneal@505 22 # Figure out if the view succeeded; if it is a non-ajax view,
bgneal@505 23 # then success means a redirect is about to occur. If it is
bgneal@505 24 # an ajax view, we have to decode the json response.
bgneal@505 25 success = False
bgneal@505 26 if not request.is_ajax():
bgneal@505 27 success = (response and response.has_header('location') and
bgneal@505 28 response.status_code == 302)
bgneal@505 29 elif response:
bgneal@679 30 json_resp = json.loads(response.content)
bgneal@505 31 success = json_resp['success']
bgneal@505 32
bgneal@505 33 if not success:
bgneal@690 34 username = request.POST.get('username')
bgneal@690 35 username = username if username else '(None)'
bgneal@690 36 logger.error("%s failure from [%s] for %s",
bgneal@690 37 auth_type,
bgneal@690 38 request.META.get('REMOTE_ADDR', '?'),
bgneal@690 39 username)
bgneal@479 40
bgneal@472 41 return response
bgneal@472 42
bgneal@472 43 return wrapped
bgneal@472 44 return decorator