From 863958b4d6af1d01c68713a32c252007317100fe Mon Sep 17 00:00:00 2001 From: Marc 'risson' Schmitt Date: Tue, 15 Oct 2024 14:22:25 +0200 Subject: [PATCH] make sure we don't break something else Signed-off-by: Marc 'risson' Schmitt --- authentik/core/models.py | 12 +++++++++++- authentik/core/tasks.py | 7 +------ authentik/stages/consent/stage.py | 2 ++ 3 files changed, 14 insertions(+), 7 deletions(-) diff --git a/authentik/core/models.py b/authentik/core/models.py index e4ad6cdac8..3848436439 100644 --- a/authentik/core/models.py +++ b/authentik/core/models.py @@ -805,7 +805,17 @@ class ExpiringModel(models.Model): def filter_not_expired(cls, **kwargs) -> QuerySet["Token"]: """Filer for tokens which are not expired yet or are not expiring, and match filters in `kwargs`""" - return cls.objects.filter(expires__gte=now(), expiring=True).filter(**kwargs) + return cls.objects.filter(expires__gt=now(), expiring=True).filter(**kwargs) + + @classmethod + def delete_expired(cls) -> int: + objects = ( + cls.objects.all().exclude(expiring=False).exclude(expiring=True, expires__gt=now()) + ) + amount = objects.count() + for obj in objects: + obj.expire_action() + return amount @property def is_expired(self) -> bool: diff --git a/authentik/core/tasks.py b/authentik/core/tasks.py index 1a565d8f7f..9ec5bdc602 100644 --- a/authentik/core/tasks.py +++ b/authentik/core/tasks.py @@ -30,12 +30,7 @@ def clean_expired_models(self: SystemTask): messages = [] for cls in ExpiringModel.__subclasses__(): cls: ExpiringModel - objects = ( - cls.objects.all().exclude(expiring=False).exclude(expiring=True, expires__gt=now()) - ) - amount = objects.count() - for obj in objects: - obj.expire_action() + amount = cls.delete_expired() LOGGER.debug("Expired models", model=cls, amount=amount) messages.append(f"Expired {amount} {cls._meta.verbose_name_plural}") # Special case diff --git a/authentik/stages/consent/stage.py b/authentik/stages/consent/stage.py index 36648c899a..43702753b9 100644 --- a/authentik/stages/consent/stage.py +++ b/authentik/stages/consent/stage.py @@ -96,6 +96,8 @@ class ConsentStageView(ChallengeStageView): if PLAN_CONTEXT_PENDING_USER in self.executor.plan.context: user = self.executor.plan.context[PLAN_CONTEXT_PENDING_USER] + # Remove expired consents to prevent database unique constraints errors + UserConsent.delete_expired() consent: UserConsent | None = UserConsent.filter_not_expired( user=user, application=application ).first()