authentik.enterprise.lifecycle.offboarding.models

  1from uuid import uuid4
  2
  3from django.apps import apps
  4from django.db import models, transaction
  5from django.db.models import Q
  6from django.http import HttpRequest
  7from django.utils import timezone
  8from django.utils.translation import gettext_lazy as _
  9from rest_framework.serializers import BaseSerializer
 10
 11from authentik.core.models import User
 12from authentik.lib.models import SerializerModel
 13
 14
 15class OffboardingAction(models.TextChoices):
 16    """Action to take against a user when their offboarding is due.
 17
 18    Designed to grow a `target_state` style action once user state/status lands."""
 19
 20    DEACTIVATE = "deactivate", _("Deactivate")
 21    DELETE = "delete", _("Delete")
 22
 23
 24class OffboardingStatus(models.TextChoices):
 25    PENDING = "pending", _("Pending")
 26    COMPLETED = "completed", _("Completed")
 27    FAILED = "failed", _("Failed")
 28    CANCELED = "canceled", _("Canceled")
 29
 30
 31class UserOffboarding(SerializerModel):
 32    """Scheduled deactivation/deletion of a single user at an absolute point in time."""
 33
 34    id = models.UUIDField(primary_key=True, default=uuid4)
 35    user = models.ForeignKey(
 36        "authentik_core.User", on_delete=models.CASCADE, related_name="offboardings"
 37    )
 38    scheduled_at = models.DateTimeField(
 39        help_text=_("Absolute time at which the offboarding action is executed.")
 40    )
 41    action = models.TextField(
 42        choices=OffboardingAction.choices, default=OffboardingAction.DEACTIVATE
 43    )
 44    revoke_sessions = models.BooleanField(
 45        default=True, help_text=_("Revoke all of the user's sessions when offboarding.")
 46    )
 47    revoke_tokens = models.BooleanField(
 48        default=True, help_text=_("Revoke all of the user's tokens when offboarding.")
 49    )
 50
 51    status = models.TextField(choices=OffboardingStatus.choices, default=OffboardingStatus.PENDING)
 52    created_by = models.ForeignKey(
 53        "authentik_core.User", on_delete=models.SET_NULL, null=True, related_name="+"
 54    )
 55    created_at = models.DateTimeField(auto_now_add=True)
 56    executed_at = models.DateTimeField(null=True, default=None)
 57    attempts = models.PositiveSmallIntegerField(
 58        default=0, help_text=_("Number of times execution has been attempted and failed.")
 59    )
 60    # Set when a user expiration rule generated this row; `created_by` stays null.
 61    # Unlike `rule`, it survives the rule being deleted.
 62    generated = models.BooleanField(default=False, db_default=False)
 63    rule = models.ForeignKey(
 64        "authentik_lifecycle.UserExpirationRule",
 65        on_delete=models.SET_NULL,
 66        null=True,
 67        default=None,
 68        related_name="offboardings",
 69    )
 70
 71    class Meta:
 72        verbose_name = _("User Offboarding")
 73        verbose_name_plural = _("User Offboardings")
 74        constraints = [
 75            models.UniqueConstraint(
 76                fields=["user"],
 77                condition=Q(status=OffboardingStatus.PENDING),
 78                name="unique_pending_offboarding_per_user",
 79            )
 80        ]
 81        indexes = [
 82            # The sweeper only scans pending rows by scheduled_at; a partial
 83            # index keeps this small as terminal (completed/failed/cancelled)
 84            # rows accumulate as audit records.
 85            models.Index(
 86                fields=["scheduled_at"],
 87                condition=Q(status=OffboardingStatus.PENDING),
 88                name="pending_offboarding_idx",
 89            ),
 90            # The expiration sweeper looks up the latest generated row per user.
 91            models.Index(
 92                fields=["user", "executed_at"],
 93                condition=Q(generated=True),
 94                name="generated_offboarding_idx",
 95            ),
 96        ]
 97
 98    @property
 99    def serializer(self) -> type[BaseSerializer]:
100        from authentik.enterprise.lifecycle.offboarding.api import UserOffboardingSerializer
101
102        return UserOffboardingSerializer
103
104    def __str__(self):
105        return f"User offboarding for user {self.user_id} ({self.action}) at {self.scheduled_at}"
106
107    def cancel(self) -> bool:
108        """Cancel iff still pending; returns whether it was cancelled.
109
110        Locked and re-checked under the lock so a concurrent execution can't have
111        its terminal status clobbered. The save() emits the audit event.
112        """
113        with transaction.atomic():
114            locked = (
115                UserOffboarding.objects.select_for_update()
116                .filter(pk=self.pk, status=OffboardingStatus.PENDING)
117                .first()
118            )
119            if locked is None:
120                return False
121            locked.status = OffboardingStatus.CANCELED
122            locked.executed_at = timezone.now()
123            locked.save(update_fields=["status", "executed_at"])
124        self.status = locked.status
125        self.executed_at = locked.executed_at
126        return True
127
128    def execute(self, request: HttpRequest | None = None):
129        """Run the offboarding action and record the outcome.
130
131        Revocations, the destructive action, and the status write run in one
132        transaction, so a mid-way failure rolls back completely: the user is
133        left untouched and the row stays `PENDING` for retry.
134        """
135        from authentik.enterprise.lifecycle.expiration.models import UserExpirationRule
136        from authentik.enterprise.lifecycle.offboarding.actions import offboard_user
137
138        context = {}
139        if self.rule_id is not None:
140            # Generated rows stay pending without a license.
141            if not apps.get_app_config("authentik_enterprise").enabled():
142                return
143            # The rule or the user may have changed since the last sweep.
144            self.user = User.objects.select_related("activity").get(pk=self.user_id)
145            kept, rewarn = self.rule.reconcile_offboarding(self)
146            if not kept:
147                return
148            if UserExpirationRule.resolve_winner(self):
149                rewarn = True
150            if self.scheduled_at > timezone.now():
151                if rewarn:
152                    # Warn after the row lock is released.
153                    transaction.on_commit(
154                        lambda rule=self.rule, user=self.user, row=self: rule._warn(user, row)
155                    )
156                return
157            context["rule"] = self.rule
158        # `delete` removes this row via cascade, so capture the action first.
159        is_delete = self.action == OffboardingAction.DELETE
160        with transaction.atomic():
161            offboard_user(
162                self.user,
163                self.action,
164                revoke_sessions=self.revoke_sessions,
165                revoke_tokens=self.revoke_tokens,
166                request=request,
167                initiator=self.created_by,
168                **context,
169            )
170            if is_delete:
171                return
172            self.status = OffboardingStatus.COMPLETED
173            self.executed_at = timezone.now()
174            self.save(update_fields=["status", "executed_at"])
class OffboardingAction(django.db.models.enums.TextChoices):
16class OffboardingAction(models.TextChoices):
17    """Action to take against a user when their offboarding is due.
18
19    Designed to grow a `target_state` style action once user state/status lands."""
20
21    DEACTIVATE = "deactivate", _("Deactivate")
22    DELETE = "delete", _("Delete")

Action to take against a user when their offboarding is due.

Designed to grow a target_state style action once user state/status lands.

class OffboardingStatus(django.db.models.enums.TextChoices):
25class OffboardingStatus(models.TextChoices):
26    PENDING = "pending", _("Pending")
27    COMPLETED = "completed", _("Completed")
28    FAILED = "failed", _("Failed")
29    CANCELED = "canceled", _("Canceled")

Class for creating enumerated string choices.

class UserOffboarding(authentik.lib.models.SerializerModel):
 32class UserOffboarding(SerializerModel):
 33    """Scheduled deactivation/deletion of a single user at an absolute point in time."""
 34
 35    id = models.UUIDField(primary_key=True, default=uuid4)
 36    user = models.ForeignKey(
 37        "authentik_core.User", on_delete=models.CASCADE, related_name="offboardings"
 38    )
 39    scheduled_at = models.DateTimeField(
 40        help_text=_("Absolute time at which the offboarding action is executed.")
 41    )
 42    action = models.TextField(
 43        choices=OffboardingAction.choices, default=OffboardingAction.DEACTIVATE
 44    )
 45    revoke_sessions = models.BooleanField(
 46        default=True, help_text=_("Revoke all of the user's sessions when offboarding.")
 47    )
 48    revoke_tokens = models.BooleanField(
 49        default=True, help_text=_("Revoke all of the user's tokens when offboarding.")
 50    )
 51
 52    status = models.TextField(choices=OffboardingStatus.choices, default=OffboardingStatus.PENDING)
 53    created_by = models.ForeignKey(
 54        "authentik_core.User", on_delete=models.SET_NULL, null=True, related_name="+"
 55    )
 56    created_at = models.DateTimeField(auto_now_add=True)
 57    executed_at = models.DateTimeField(null=True, default=None)
 58    attempts = models.PositiveSmallIntegerField(
 59        default=0, help_text=_("Number of times execution has been attempted and failed.")
 60    )
 61    # Set when a user expiration rule generated this row; `created_by` stays null.
 62    # Unlike `rule`, it survives the rule being deleted.
 63    generated = models.BooleanField(default=False, db_default=False)
 64    rule = models.ForeignKey(
 65        "authentik_lifecycle.UserExpirationRule",
 66        on_delete=models.SET_NULL,
 67        null=True,
 68        default=None,
 69        related_name="offboardings",
 70    )
 71
 72    class Meta:
 73        verbose_name = _("User Offboarding")
 74        verbose_name_plural = _("User Offboardings")
 75        constraints = [
 76            models.UniqueConstraint(
 77                fields=["user"],
 78                condition=Q(status=OffboardingStatus.PENDING),
 79                name="unique_pending_offboarding_per_user",
 80            )
 81        ]
 82        indexes = [
 83            # The sweeper only scans pending rows by scheduled_at; a partial
 84            # index keeps this small as terminal (completed/failed/cancelled)
 85            # rows accumulate as audit records.
 86            models.Index(
 87                fields=["scheduled_at"],
 88                condition=Q(status=OffboardingStatus.PENDING),
 89                name="pending_offboarding_idx",
 90            ),
 91            # The expiration sweeper looks up the latest generated row per user.
 92            models.Index(
 93                fields=["user", "executed_at"],
 94                condition=Q(generated=True),
 95                name="generated_offboarding_idx",
 96            ),
 97        ]
 98
 99    @property
100    def serializer(self) -> type[BaseSerializer]:
101        from authentik.enterprise.lifecycle.offboarding.api import UserOffboardingSerializer
102
103        return UserOffboardingSerializer
104
105    def __str__(self):
106        return f"User offboarding for user {self.user_id} ({self.action}) at {self.scheduled_at}"
107
108    def cancel(self) -> bool:
109        """Cancel iff still pending; returns whether it was cancelled.
110
111        Locked and re-checked under the lock so a concurrent execution can't have
112        its terminal status clobbered. The save() emits the audit event.
113        """
114        with transaction.atomic():
115            locked = (
116                UserOffboarding.objects.select_for_update()
117                .filter(pk=self.pk, status=OffboardingStatus.PENDING)
118                .first()
119            )
120            if locked is None:
121                return False
122            locked.status = OffboardingStatus.CANCELED
123            locked.executed_at = timezone.now()
124            locked.save(update_fields=["status", "executed_at"])
125        self.status = locked.status
126        self.executed_at = locked.executed_at
127        return True
128
129    def execute(self, request: HttpRequest | None = None):
130        """Run the offboarding action and record the outcome.
131
132        Revocations, the destructive action, and the status write run in one
133        transaction, so a mid-way failure rolls back completely: the user is
134        left untouched and the row stays `PENDING` for retry.
135        """
136        from authentik.enterprise.lifecycle.expiration.models import UserExpirationRule
137        from authentik.enterprise.lifecycle.offboarding.actions import offboard_user
138
139        context = {}
140        if self.rule_id is not None:
141            # Generated rows stay pending without a license.
142            if not apps.get_app_config("authentik_enterprise").enabled():
143                return
144            # The rule or the user may have changed since the last sweep.
145            self.user = User.objects.select_related("activity").get(pk=self.user_id)
146            kept, rewarn = self.rule.reconcile_offboarding(self)
147            if not kept:
148                return
149            if UserExpirationRule.resolve_winner(self):
150                rewarn = True
151            if self.scheduled_at > timezone.now():
152                if rewarn:
153                    # Warn after the row lock is released.
154                    transaction.on_commit(
155                        lambda rule=self.rule, user=self.user, row=self: rule._warn(user, row)
156                    )
157                return
158            context["rule"] = self.rule
159        # `delete` removes this row via cascade, so capture the action first.
160        is_delete = self.action == OffboardingAction.DELETE
161        with transaction.atomic():
162            offboard_user(
163                self.user,
164                self.action,
165                revoke_sessions=self.revoke_sessions,
166                revoke_tokens=self.revoke_tokens,
167                request=request,
168                initiator=self.created_by,
169                **context,
170            )
171            if is_delete:
172                return
173            self.status = OffboardingStatus.COMPLETED
174            self.executed_at = timezone.now()
175            self.save(update_fields=["status", "executed_at"])

Scheduled deactivation/deletion of a single user at an absolute point in time.

def id(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

user

Accessor to the related object on the forward side of a many-to-one or one-to-one (via ForwardOneToOneDescriptor subclass) relation.

In the example::

class Child(Model):
    parent = ForeignKey(Parent, related_name='children')

Child.parent is a ForwardManyToOneDescriptor instance.

def scheduled_at(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

def action(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

def revoke_sessions(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

def revoke_tokens(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

def status(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

created_by

Accessor to the related object on the forward side of a many-to-one or one-to-one (via ForwardOneToOneDescriptor subclass) relation.

In the example::

class Child(Model):
    parent = ForeignKey(Parent, related_name='children')

Child.parent is a ForwardManyToOneDescriptor instance.

def created_at(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

def executed_at(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

def attempts(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

def generated(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

rule

Accessor to the related object on the forward side of a many-to-one or one-to-one (via ForwardOneToOneDescriptor subclass) relation.

In the example::

class Child(Model):
    parent = ForeignKey(Parent, related_name='children')

Child.parent is a ForwardManyToOneDescriptor instance.

serializer: type[rest_framework.serializers.BaseSerializer]
 99    @property
100    def serializer(self) -> type[BaseSerializer]:
101        from authentik.enterprise.lifecycle.offboarding.api import UserOffboardingSerializer
102
103        return UserOffboardingSerializer

Get serializer for this model

def cancel(self) -> bool:
108    def cancel(self) -> bool:
109        """Cancel iff still pending; returns whether it was cancelled.
110
111        Locked and re-checked under the lock so a concurrent execution can't have
112        its terminal status clobbered. The save() emits the audit event.
113        """
114        with transaction.atomic():
115            locked = (
116                UserOffboarding.objects.select_for_update()
117                .filter(pk=self.pk, status=OffboardingStatus.PENDING)
118                .first()
119            )
120            if locked is None:
121                return False
122            locked.status = OffboardingStatus.CANCELED
123            locked.executed_at = timezone.now()
124            locked.save(update_fields=["status", "executed_at"])
125        self.status = locked.status
126        self.executed_at = locked.executed_at
127        return True

Cancel iff still pending; returns whether it was cancelled.

Locked and re-checked under the lock so a concurrent execution can't have its terminal status clobbered. The save() emits the audit event.

def execute(self, request: django.http.request.HttpRequest | None = None):
129    def execute(self, request: HttpRequest | None = None):
130        """Run the offboarding action and record the outcome.
131
132        Revocations, the destructive action, and the status write run in one
133        transaction, so a mid-way failure rolls back completely: the user is
134        left untouched and the row stays `PENDING` for retry.
135        """
136        from authentik.enterprise.lifecycle.expiration.models import UserExpirationRule
137        from authentik.enterprise.lifecycle.offboarding.actions import offboard_user
138
139        context = {}
140        if self.rule_id is not None:
141            # Generated rows stay pending without a license.
142            if not apps.get_app_config("authentik_enterprise").enabled():
143                return
144            # The rule or the user may have changed since the last sweep.
145            self.user = User.objects.select_related("activity").get(pk=self.user_id)
146            kept, rewarn = self.rule.reconcile_offboarding(self)
147            if not kept:
148                return
149            if UserExpirationRule.resolve_winner(self):
150                rewarn = True
151            if self.scheduled_at > timezone.now():
152                if rewarn:
153                    # Warn after the row lock is released.
154                    transaction.on_commit(
155                        lambda rule=self.rule, user=self.user, row=self: rule._warn(user, row)
156                    )
157                return
158            context["rule"] = self.rule
159        # `delete` removes this row via cascade, so capture the action first.
160        is_delete = self.action == OffboardingAction.DELETE
161        with transaction.atomic():
162            offboard_user(
163                self.user,
164                self.action,
165                revoke_sessions=self.revoke_sessions,
166                revoke_tokens=self.revoke_tokens,
167                request=request,
168                initiator=self.created_by,
169                **context,
170            )
171            if is_delete:
172                return
173            self.status = OffboardingStatus.COMPLETED
174            self.executed_at = timezone.now()
175            self.save(update_fields=["status", "executed_at"])

Run the offboarding action and record the outcome.

Revocations, the destructive action, and the status write run in one transaction, so a mid-way failure rolls back completely: the user is left untouched and the row stays PENDING for retry.

user_id
def get_next_by_scheduled_at(unknown):

Method descriptor with partial application of the given arguments and keywords.

Supports wrapping existing descriptors and handles non-descriptor callables as instance methods.

def get_previous_by_scheduled_at(unknown):

Method descriptor with partial application of the given arguments and keywords.

Supports wrapping existing descriptors and handles non-descriptor callables as instance methods.

def get_action_display(unknown):

Method descriptor with partial application of the given arguments and keywords.

Supports wrapping existing descriptors and handles non-descriptor callables as instance methods.

def get_status_display(unknown):

Method descriptor with partial application of the given arguments and keywords.

Supports wrapping existing descriptors and handles non-descriptor callables as instance methods.

created_by_id
def get_next_by_created_at(unknown):

Method descriptor with partial application of the given arguments and keywords.

Supports wrapping existing descriptors and handles non-descriptor callables as instance methods.

def get_previous_by_created_at(unknown):

Method descriptor with partial application of the given arguments and keywords.

Supports wrapping existing descriptors and handles non-descriptor callables as instance methods.

rule_id
def objects(unknown):

The type of the None singleton.

class UserOffboarding.DoesNotExist(django.core.exceptions.ObjectDoesNotExist):

The requested object does not exist

class UserOffboarding.MultipleObjectsReturned(django.core.exceptions.MultipleObjectsReturned):

The query returned multiple objects when only one was expected.