2019-10-07 14:33:48 +00:00
|
|
|
"""passbook reputation request signals"""
|
2019-03-03 19:26:25 +00:00
|
|
|
from django.contrib.auth.signals import user_logged_in, user_login_failed
|
2020-07-07 15:03:57 +00:00
|
|
|
from django.core.cache import cache
|
2019-03-03 19:26:25 +00:00
|
|
|
from django.dispatch import receiver
|
2020-07-07 15:03:57 +00:00
|
|
|
from django.http import HttpRequest
|
2019-10-01 08:24:10 +00:00
|
|
|
from structlog import get_logger
|
2019-03-03 19:26:25 +00:00
|
|
|
|
2019-12-05 13:33:55 +00:00
|
|
|
from passbook.lib.utils.http import get_client_ip
|
2020-07-07 15:03:57 +00:00
|
|
|
from passbook.policies.reputation.models import (
|
|
|
|
CACHE_KEY_IP_PREFIX,
|
|
|
|
CACHE_KEY_USER_PREFIX,
|
|
|
|
)
|
2019-03-03 19:26:25 +00:00
|
|
|
|
2019-10-04 08:08:53 +00:00
|
|
|
LOGGER = get_logger()
|
2019-03-03 19:26:25 +00:00
|
|
|
|
|
|
|
|
2020-07-07 15:03:57 +00:00
|
|
|
def update_score(request: HttpRequest, username: str, amount: int):
|
2019-03-03 19:26:25 +00:00
|
|
|
"""Update score for IP and User"""
|
2020-07-07 15:03:57 +00:00
|
|
|
remote_ip = get_client_ip(request) or "255.255.255.255"
|
|
|
|
|
|
|
|
# We only update the cache here, as its faster than writing to the DB
|
|
|
|
cache.get_or_set(CACHE_KEY_IP_PREFIX + remote_ip, 0)
|
|
|
|
cache.incr(CACHE_KEY_IP_PREFIX + remote_ip, amount)
|
|
|
|
|
|
|
|
cache.get_or_set(CACHE_KEY_USER_PREFIX + username, 0)
|
|
|
|
cache.incr(CACHE_KEY_USER_PREFIX + username, amount)
|
|
|
|
|
|
|
|
LOGGER.debug("Updated score", amount=amount, for_user=username, for_ip=remote_ip)
|
2019-03-03 19:26:25 +00:00
|
|
|
|
2019-12-09 20:00:45 +00:00
|
|
|
|
2019-03-03 19:26:25 +00:00
|
|
|
@receiver(user_login_failed)
|
2019-12-31 11:45:29 +00:00
|
|
|
# pylint: disable=unused-argument
|
|
|
|
def handle_failed_login(sender, request, credentials, **_):
|
2019-03-03 19:26:25 +00:00
|
|
|
"""Lower Score for failed loging attempts"""
|
2020-07-07 20:25:37 +00:00
|
|
|
if "username" in credentials:
|
|
|
|
update_score(request, credentials.get("username"), -1)
|
2019-03-03 19:26:25 +00:00
|
|
|
|
2019-12-09 20:00:45 +00:00
|
|
|
|
2019-03-03 19:26:25 +00:00
|
|
|
@receiver(user_logged_in)
|
2019-12-31 11:45:29 +00:00
|
|
|
# pylint: disable=unused-argument
|
|
|
|
def handle_successful_login(sender, request, user, **_):
|
2019-03-03 19:26:25 +00:00
|
|
|
"""Raise score for successful attempts"""
|
|
|
|
update_score(request, user.username, 1)
|