2020-07-07 15:03:57 +00:00
|
|
|
"""Reputation tasks"""
|
|
|
|
from django.core.cache import cache
|
|
|
|
from structlog import get_logger
|
|
|
|
|
|
|
|
from passbook.core.models import User
|
2020-10-16 12:20:24 +00:00
|
|
|
from passbook.lib.tasks import MonitoredTask, TaskResult, TaskResultStatus
|
2020-07-07 15:03:57 +00:00
|
|
|
from passbook.policies.reputation.models import IPReputation, UserReputation
|
|
|
|
from passbook.policies.reputation.signals import (
|
|
|
|
CACHE_KEY_IP_PREFIX,
|
|
|
|
CACHE_KEY_USER_PREFIX,
|
|
|
|
)
|
|
|
|
from passbook.root.celery import CELERY_APP
|
|
|
|
|
|
|
|
LOGGER = get_logger()
|
|
|
|
|
|
|
|
|
2020-10-16 12:20:24 +00:00
|
|
|
@CELERY_APP.task(bind=True, base=MonitoredTask)
|
|
|
|
def save_ip_reputation(self: MonitoredTask):
|
2020-07-07 15:03:57 +00:00
|
|
|
"""Save currently cached reputation to database"""
|
|
|
|
objects_to_update = []
|
2020-10-16 12:53:14 +00:00
|
|
|
for key, score in cache.get_many(cache.keys(CACHE_KEY_IP_PREFIX + "*")).items():
|
2020-07-07 15:03:57 +00:00
|
|
|
remote_ip = key.replace(CACHE_KEY_IP_PREFIX, "")
|
|
|
|
rep, _ = IPReputation.objects.get_or_create(ip=remote_ip)
|
|
|
|
rep.score = score
|
|
|
|
objects_to_update.append(rep)
|
|
|
|
IPReputation.objects.bulk_update(objects_to_update, ["score"])
|
2020-10-16 12:20:24 +00:00
|
|
|
self.set_status(
|
|
|
|
TaskResult(TaskResultStatus.SUCCESSFUL, ["Successfully updated IP Reputation"])
|
|
|
|
)
|
2020-07-07 15:03:57 +00:00
|
|
|
|
|
|
|
|
2020-10-16 12:20:24 +00:00
|
|
|
@CELERY_APP.task(bind=True, base=MonitoredTask)
|
|
|
|
def save_user_reputation(self: MonitoredTask):
|
2020-07-07 15:03:57 +00:00
|
|
|
"""Save currently cached reputation to database"""
|
|
|
|
objects_to_update = []
|
2020-10-16 12:53:14 +00:00
|
|
|
for key, score in cache.get_many(cache.keys(CACHE_KEY_USER_PREFIX + "*")).items():
|
2020-07-07 15:03:57 +00:00
|
|
|
username = key.replace(CACHE_KEY_USER_PREFIX, "")
|
|
|
|
users = User.objects.filter(username=username)
|
|
|
|
if not users.exists():
|
|
|
|
LOGGER.info("User in cache does not exist, ignoring", username=username)
|
|
|
|
continue
|
|
|
|
rep, _ = UserReputation.objects.get_or_create(user=users.first())
|
|
|
|
rep.score = score
|
|
|
|
objects_to_update.append(rep)
|
|
|
|
UserReputation.objects.bulk_update(objects_to_update, ["score"])
|
2020-10-16 12:20:24 +00:00
|
|
|
self.set_status(
|
|
|
|
TaskResult(
|
|
|
|
TaskResultStatus.SUCCESSFUL, ["Successfully updated User Reputation"]
|
|
|
|
)
|
|
|
|
)
|