audit: add basic login attempt tracking

This commit is contained in:
Jens Langhammer
2018-12-18 15:35:23 +01:00
parent 0c53a95b06
commit 2e4a0297a4
3 changed files with 69 additions and 6 deletions

View File

@ -10,7 +10,7 @@ from django.utils.translation import gettext as _
from ipware import get_client_ip
from reversion import register
from passbook.lib.models import UUIDModel
from passbook.lib.models import CreatedUpdatedModel, UUIDModel
LOGGER = getLogger(__name__)
@ -80,3 +80,40 @@ class AuditEntry(UUIDModel):
verbose_name = _('Audit Entry')
verbose_name_plural = _('Audit Entries')
class LoginAttempt(CreatedUpdatedModel):
"""Track failed login-attempts"""
target_uid = models.CharField(max_length=254)
request_ip = models.GenericIPAddressField()
attempts = models.IntegerField(default=1)
@staticmethod
def attempt(target_uid, request):
"""Helper function to create attempt or count up existing one"""
client_ip, _ = get_client_ip(request)
# Since we can only use 254 chars for target_uid, truncate target_uid.
target_uid = target_uid[:254]
existing_attempts = LoginAttempt.objects.filter(
target_uid=target_uid,
request_ip=client_ip).order_by('created')
# TODO: Add logic to group attempts by timeframe, i.e. within 10 minutes
if existing_attempts.exists():
attempt = existing_attempts.first()
attempt.attempts += 1
attempt.save()
LOGGER.debug("Increased attempts on %s", attempt)
else:
attempt = LoginAttempt.objects.create(
target_uid=target_uid,
request_ip=client_ip)
LOGGER.debug("Created new attempt %s", attempt)
def __str__(self):
return "LoginAttempt to %s from %s (x%d)" % (self.target_uid,
self.request_ip, self.attempts)
class Meta:
unique_together = (('target_uid', 'request_ip', 'created'),)