diff --git a/authentik/core/tasks.py b/authentik/core/tasks.py index ad46bf40f..14dbd8b60 100644 --- a/authentik/core/tasks.py +++ b/authentik/core/tasks.py @@ -34,9 +34,9 @@ def clean_expired_models(self: MonitoredTask): objects = ( cls.objects.all().exclude(expiring=False).exclude(expiring=True, expires__gt=now()) ) + amount = objects.count() for obj in objects: obj.expire_action() - amount = objects.count() LOGGER.debug("Expired models", model=cls, amount=amount) messages.append(f"Expired {amount} {cls._meta.verbose_name_plural}") # Special case diff --git a/authentik/events/settings.py b/authentik/events/settings.py new file mode 100644 index 000000000..4e41e3953 --- /dev/null +++ b/authentik/events/settings.py @@ -0,0 +1,12 @@ +"""Event Settings""" +from celery.schedules import crontab + +from authentik.lib.utils.time import fqdn_rand + +CELERY_BEAT_SCHEDULE = { + "events_notification_cleanup": { + "task": "authentik.events.tasks.notification_cleanup", + "schedule": crontab(minute=fqdn_rand("notification_cleanup"), hour="*/8"), + "options": {"queue": "authentik_scheduled"}, + }, +} diff --git a/authentik/events/tasks.py b/authentik/events/tasks.py index 3828dbd8e..2afefce07 100644 --- a/authentik/events/tasks.py +++ b/authentik/events/tasks.py @@ -1,4 +1,5 @@ """Event notification tasks""" +from django.db.models.query_utils import Q from guardian.shortcuts import get_anonymous_user from structlog.stdlib import get_logger @@ -10,7 +11,12 @@ from authentik.events.models import ( NotificationTransport, NotificationTransportError, ) -from authentik.events.monitored_tasks import MonitoredTask, TaskResult, TaskResultStatus +from authentik.events.monitored_tasks import ( + MonitoredTask, + TaskResult, + TaskResultStatus, + prefill_task, +) from authentik.policies.engine import PolicyEngine from authentik.policies.models import PolicyBinding, PolicyEngineMode from authentik.root.celery import CELERY_APP @@ -114,3 +120,15 @@ def gdpr_cleanup(user_pk: int): events = Event.objects.filter(user__pk=user_pk) LOGGER.debug("GDPR cleanup, removing events from user", events=events.count()) events.delete() + + +@CELERY_APP.task(bind=True, base=MonitoredTask) +@prefill_task +def notification_cleanup(self: MonitoredTask): + """Cleanup seen notifications and notifications whose event expired.""" + notifications = Notification.objects.filter(Q(event=None) | Q(seen=True)) + amount = notifications.count() + for notification in notifications: + notification.delete() + LOGGER.debug("Expired notifications", amount=amount) + self.set_status(TaskResult(TaskResultStatus.SUCCESSFUL, [f"Expired {amount} Notifications"]))