authentik.enterprise.lifecycle.models

Model registry for the lifecycle app.

The lifecycle app is an umbrella for sibling features that each live in their own package: review/ (object access reviews), offboarding/ (user offboarding) and expiration/ (automatic user expiration). Django loads models through this module, so every feature's models must be imported here.

 1"""Model registry for the lifecycle app.
 2
 3The lifecycle app is an umbrella for sibling features that each live in their
 4own package: `review/` (object access reviews), `offboarding/` (user
 5offboarding) and `expiration/` (automatic user expiration). Django loads models
 6through this module, so every feature's models must be imported here.
 7"""
 8
 9# Import order sets model registration order, which the API schema's ModelEnum
10# follows; review stays first to match the pre-split layout.
11# isort: off
12from authentik.enterprise.lifecycle.review.models import (
13    LifecycleIteration,
14    LifecycleRule,
15    LifecycleRuleNotificationTransport,
16    LifecycleRuleReviewer,
17    LifecycleRuleReviewerGroup,
18    Review,
19    ReviewState,
20)
21from authentik.enterprise.lifecycle.offboarding.models import (
22    OffboardingAction,
23    OffboardingStatus,
24    UserOffboarding,
25)
26from authentik.enterprise.lifecycle.expiration.models import (
27    UserExpirationRule,
28    UserExpirationRuleNotificationTransport,
29)
30
31# isort: on
32
33__all__ = [
34    "LifecycleIteration",
35    "LifecycleRule",
36    "LifecycleRuleNotificationTransport",
37    "LifecycleRuleReviewer",
38    "LifecycleRuleReviewerGroup",
39    "OffboardingAction",
40    "OffboardingStatus",
41    "Review",
42    "ReviewState",
43    "UserExpirationRule",
44    "UserExpirationRuleNotificationTransport",
45    "UserOffboarding",
46]
245class LifecycleIteration(SerializerModel, ManagedModel):
246    id = models.UUIDField(primary_key=True, default=uuid4)
247    content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
248    object_id = models.TextField(null=False)
249    object = GenericForeignKey("content_type", "object_id")
250
251    rule = models.ForeignKey(LifecycleRule, null=True, on_delete=models.SET_NULL)
252
253    state = models.CharField(max_length=10, choices=ReviewState, default=ReviewState.PENDING)
254    opened_on = models.DateTimeField(auto_now_add=True)
255
256    class Meta:
257        indexes = [models.Index(fields=["content_type", "opened_on"])]
258
259    @property
260    def serializer(self) -> type[BaseSerializer]:
261        from authentik.enterprise.lifecycle.review.api.iterations import (
262            LifecycleIterationSerializer,
263        )
264
265        return LifecycleIterationSerializer
266
267    def _get_model_name(self) -> str:
268        return self.content_type.name.lower()
269
270    def _get_event_args(self) -> dict:
271        return {
272            "target": self.object,
273            "hyperlink": link_for_model(self.object),
274            "hyperlink_label": _("Go to {model_name}").format(model_name=self._get_model_name()),
275            "lifecycle_iteration": self.id,
276        }
277
278    def initialize(self):
279        if (self.content_type.app_label, self.content_type.model) == ("authentik_core", "group"):
280            object_label = self.object.name
281        elif (self.content_type.app_label, self.content_type.model) == ("authentik_rbac", "role"):
282            object_label = self.object.name
283        else:
284            object_label = str(self.object)
285        event = Event.new(
286            EventAction.REVIEW_INITIATED,
287            message=_("Access review is due for {model_name} {object_label}").format(
288                model_name=self.content_type.name.lower(), object_label=object_label
289            ),
290            **self._get_event_args(),
291        )
292        event.save()
293        self.rule.notify_reviewers(event, NotificationSeverity.NOTICE)
294
295    def make_overdue(self):
296        self.state = ReviewState.OVERDUE
297
298        event = Event.new(
299            EventAction.REVIEW_OVERDUE,
300            message=_("Access review is overdue for {model_name} {object_label}").format(
301                model_name=self.content_type.name, object_label=str(self.object)
302            ),
303            **self._get_event_args(),
304        )
305        event.save()
306        self.rule.notify_reviewers(event, NotificationSeverity.ALERT)
307        self.save()
308
309    @staticmethod
310    def start(content_type: ContentType, object_id: str, rule: LifecycleRule) -> LifecycleIteration:
311        iteration = LifecycleIteration.objects.create(
312            content_type=content_type, object_id=object_id, rule=rule
313        )
314        iteration.initialize()
315        return iteration
316
317    def make_reviewed(self, request: HttpRequest):
318        self.state = ReviewState.REVIEWED
319        event = Event.new(
320            EventAction.REVIEW_COMPLETED,
321            message=_("Access review completed for {model_name} {object_label}").format(
322                model_name=self.content_type.name, object_label=str(self.object)
323            ),
324            **self._get_event_args(),
325        ).from_http(request)
326        event.save()
327        self.rule.notify_reviewers(event, NotificationSeverity.NOTICE)
328        self.save()
329
330    def on_review(self, review: Review, request: HttpRequest):
331        if self.state not in (ReviewState.PENDING, ReviewState.OVERDUE):
332            raise AssertionError("Review is not pending or overdue")
333        Event.new(
334            EventAction.REVIEW_ATTESTED,
335            message=_("Access review attested for {model_name} {object_label}").format(
336                model_name=self.content_type.name, object_label=str(self.object)
337            ),
338            note=review.note,
339            **self._get_event_args(),
340        ).from_http(request, review.reviewer)
341        if self.rule.is_satisfied_for_iteration(self):
342            self.make_reviewed(request)
343
344    def user_can_review(self, user: User) -> bool:
345        if self.state not in (ReviewState.PENDING, ReviewState.OVERDUE):
346            return False
347        if self.review_set.filter(reviewer=user).exists():
348            return False
349        groups = self.rule.reviewer_groups.all()
350        if groups:
351            for group in groups:
352                if group.is_member(user):
353                    return True
354            return False
355        else:
356            return user in self.rule.get_reviewers()

LifecycleIteration(managed, id, content_type, object_id, rule, state, opened_on)

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.

content_type

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 object_id(unknown):

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

object

Provide a generic many-to-one relation through the content_type and object_id fields.

This class also doubles as an accessor to the related object (similar to ForwardManyToOneDescriptor) by adding itself as a model attribute.

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.

def state(unknown):

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

def opened_on(unknown):

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

serializer: type[rest_framework.serializers.BaseSerializer]
259    @property
260    def serializer(self) -> type[BaseSerializer]:
261        from authentik.enterprise.lifecycle.review.api.iterations import (
262            LifecycleIterationSerializer,
263        )
264
265        return LifecycleIterationSerializer

Get serializer for this model

def initialize(self):
278    def initialize(self):
279        if (self.content_type.app_label, self.content_type.model) == ("authentik_core", "group"):
280            object_label = self.object.name
281        elif (self.content_type.app_label, self.content_type.model) == ("authentik_rbac", "role"):
282            object_label = self.object.name
283        else:
284            object_label = str(self.object)
285        event = Event.new(
286            EventAction.REVIEW_INITIATED,
287            message=_("Access review is due for {model_name} {object_label}").format(
288                model_name=self.content_type.name.lower(), object_label=object_label
289            ),
290            **self._get_event_args(),
291        )
292        event.save()
293        self.rule.notify_reviewers(event, NotificationSeverity.NOTICE)
def make_overdue(self):
295    def make_overdue(self):
296        self.state = ReviewState.OVERDUE
297
298        event = Event.new(
299            EventAction.REVIEW_OVERDUE,
300            message=_("Access review is overdue for {model_name} {object_label}").format(
301                model_name=self.content_type.name, object_label=str(self.object)
302            ),
303            **self._get_event_args(),
304        )
305        event.save()
306        self.rule.notify_reviewers(event, NotificationSeverity.ALERT)
307        self.save()
@staticmethod
def start( content_type: django.contrib.contenttypes.models.ContentType, object_id: str, rule: LifecycleRule) -> LifecycleIteration:
309    @staticmethod
310    def start(content_type: ContentType, object_id: str, rule: LifecycleRule) -> LifecycleIteration:
311        iteration = LifecycleIteration.objects.create(
312            content_type=content_type, object_id=object_id, rule=rule
313        )
314        iteration.initialize()
315        return iteration
def make_reviewed(self, request: django.http.request.HttpRequest):
317    def make_reviewed(self, request: HttpRequest):
318        self.state = ReviewState.REVIEWED
319        event = Event.new(
320            EventAction.REVIEW_COMPLETED,
321            message=_("Access review completed for {model_name} {object_label}").format(
322                model_name=self.content_type.name, object_label=str(self.object)
323            ),
324            **self._get_event_args(),
325        ).from_http(request)
326        event.save()
327        self.rule.notify_reviewers(event, NotificationSeverity.NOTICE)
328        self.save()
def on_review( self, review: Review, request: django.http.request.HttpRequest):
330    def on_review(self, review: Review, request: HttpRequest):
331        if self.state not in (ReviewState.PENDING, ReviewState.OVERDUE):
332            raise AssertionError("Review is not pending or overdue")
333        Event.new(
334            EventAction.REVIEW_ATTESTED,
335            message=_("Access review attested for {model_name} {object_label}").format(
336                model_name=self.content_type.name, object_label=str(self.object)
337            ),
338            note=review.note,
339            **self._get_event_args(),
340        ).from_http(request, review.reviewer)
341        if self.rule.is_satisfied_for_iteration(self):
342            self.make_reviewed(request)
def user_can_review(self, user: authentik.core.models.User) -> bool:
344    def user_can_review(self, user: User) -> bool:
345        if self.state not in (ReviewState.PENDING, ReviewState.OVERDUE):
346            return False
347        if self.review_set.filter(reviewer=user).exists():
348            return False
349        groups = self.rule.reviewer_groups.all()
350        if groups:
351            for group in groups:
352                if group.is_member(user):
353                    return True
354            return False
355        else:
356            return user in self.rule.get_reviewers()
def managed(unknown):

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

content_type_id
rule_id
def get_state_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_next_by_opened_on(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_opened_on(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 objects(unknown):

The type of the None singleton.

review_set

Accessor to the related objects manager on the reverse side of a many-to-one relation.

In the example::

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

Parent.children is a ReverseManyToOneDescriptor instance.

Most of the implementation is delegated to a dynamically defined manager class built by create_forward_many_to_many_manager() defined below.

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

The requested object does not exist

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

The query returned multiple objects when only one was expected.

class LifecycleRule(authentik.lib.models.SerializerModel):
 24class LifecycleRule(SerializerModel):
 25
 26    id = models.UUIDField(primary_key=True, default=uuid4)
 27    name = models.TextField(unique=True)
 28    content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
 29    object_id = models.TextField(null=True, default=None)
 30    object = GenericForeignKey("content_type", "object_id")
 31
 32    interval = models.TextField(
 33        default="days=60",
 34        validators=[timedelta_string_validator],
 35    )
 36    # Grace period starts after a review is due
 37    grace_period = models.TextField(
 38        default="days=30",
 39        validators=[timedelta_string_validator],
 40    )
 41
 42    # The review has to be conducted by `min_reviewers` members of `reviewer_groups`
 43    # (total or per group depending on `min_reviewers_is_per_group` flag) as well
 44    # as all of `reviewers`
 45    reviewer_groups = models.ManyToManyField(
 46        "authentik_core.Group", blank=True, through="LifecycleRuleReviewerGroup"
 47    )
 48    min_reviewers = models.PositiveSmallIntegerField(default=1)
 49    min_reviewers_is_per_group = models.BooleanField(default=False)
 50    reviewers = models.ManyToManyField(
 51        "authentik_core.User", blank=True, through="LifecycleRuleReviewer"
 52    )
 53
 54    notification_transports = models.ManyToManyField(
 55        NotificationTransport,
 56        help_text=_(
 57            "Select which transports should be used to notify the reviewers. If none are "
 58            "selected, the notification will only be shown in the authentik UI."
 59        ),
 60        blank=True,
 61        through="LifecycleRuleNotificationTransport",
 62    )
 63
 64    class Meta:
 65        indexes = [models.Index(fields=["content_type"])]
 66
 67    @property
 68    def serializer(self) -> type[BaseSerializer]:
 69        from authentik.enterprise.lifecycle.review.api.rules import LifecycleRuleSerializer
 70
 71        return LifecycleRuleSerializer
 72
 73    def _get_pk_field(self) -> Field:
 74        model = self.content_type.model_class()
 75        pk = model._meta.pk
 76        while hasattr(pk, "target_field"):
 77            pk = pk.target_field
 78        return pk.__class__()
 79
 80    def get_objects(self) -> QuerySet:
 81        qs = self.content_type.get_all_objects_for_this_type()
 82        if self.object_id:
 83            qs = qs.filter(pk=self.object_id)
 84        return qs
 85
 86    def _get_stale_iterations(self) -> QuerySet[LifecycleIteration]:
 87        filter = ~Q(content_type=self.content_type)
 88        if self.object_id:
 89            filter = filter | ~Q(object_id=self.object_id)
 90        filter = Q(state__in=(ReviewState.PENDING, ReviewState.OVERDUE)) & filter
 91        return self.lifecycleiteration_set.filter(filter)
 92
 93    def _get_newly_overdue_iterations(self) -> QuerySet[LifecycleIteration]:
 94        return self.lifecycleiteration_set.filter(
 95            opened_on__lt=start_of_day(
 96                timezone.now() + timedelta(days=1) - timedelta_from_string(self.grace_period)
 97            ),
 98            state=ReviewState.PENDING,
 99        )
100
101    def _get_newly_due_objects(self) -> QuerySet:
102        recent_iteration_ids = LifecycleIteration.objects.filter(
103            rule=self,
104            opened_on__gte=start_of_day(
105                timezone.now() + timedelta(days=1) - timedelta_from_string(self.interval)
106            ),
107        ).values_list(Cast("object_id", output_field=self._get_pk_field()), flat=True)
108
109        return self.get_objects().exclude(pk__in=recent_iteration_ids)
110
111    def apply(self):
112        self._get_stale_iterations().update(state=ReviewState.CANCELED)
113
114        for iteration in self._get_newly_overdue_iterations():
115            iteration.make_overdue()
116
117        for obj in self._get_newly_due_objects():
118            LifecycleIteration.start(content_type=self.content_type, object_id=obj.pk, rule=self)
119
120    def is_satisfied_for_iteration(self, iteration: LifecycleIteration) -> bool:
121        reviewers = self.reviewers.all()
122        if (
123            iteration.review_set.filter(reviewer__in=reviewers).distinct("reviewer").count()
124            < reviewers.count()
125        ):
126            return False
127        if self.reviewer_groups.count() == 0:
128            return True
129        if self.min_reviewers_is_per_group:
130            for g in self.reviewer_groups.all():
131                if (
132                    iteration.review_set.filter(
133                        reviewer__groups__in=Group.objects.filter(pk=g.pk).with_descendants()
134                    )
135                    .distinct()
136                    .count()
137                    < self.min_reviewers
138                ):
139                    return False
140            return True
141        else:
142            return (
143                iteration.review_set.filter(
144                    reviewer__groups__in=self.reviewer_groups.all().with_descendants()
145                )
146                .distinct()
147                .count()
148                >= self.min_reviewers
149            )
150
151    def get_reviewers(self) -> QuerySet[User]:
152        return User.objects.filter(
153            Q(id__in=self.reviewers.all().values_list("pk", flat=True))
154            | Q(groups__in=self.reviewer_groups.all().with_descendants())
155        ).distinct()
156
157    def notify_reviewers(self, event: Event, severity: str):
158        from authentik.enterprise.lifecycle.review.tasks import send_notification
159
160        for transport in self.notification_transports.all():
161            for user in self.get_reviewers():
162                send_notification.send_with_options(
163                    args=(transport.pk, event.pk, user.pk, severity),
164                    rel_obj=transport,
165                )
166                if transport.send_once:
167                    break

LifecycleRule(id, name, content_type, object_id, interval, grace_period, min_reviewers, min_reviewers_is_per_group)

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.

def name(unknown):

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

content_type

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 object_id(unknown):

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

object

Provide a generic many-to-one relation through the content_type and object_id fields.

This class also doubles as an accessor to the related object (similar to ForwardManyToOneDescriptor) by adding itself as a model attribute.

def interval(unknown):

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

def grace_period(unknown):

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

reviewer_groups

Accessor to the related objects manager on the forward and reverse sides of a many-to-many relation.

In the example::

class Pizza(Model):
    toppings = ManyToManyField(Topping, related_name='pizzas')

Pizza.toppings and Topping.pizzas are ManyToManyDescriptor instances.

Most of the implementation is delegated to a dynamically defined manager class built by create_forward_many_to_many_manager() defined below.

def min_reviewers(unknown):

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

def min_reviewers_is_per_group(unknown):

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

reviewers

Accessor to the related objects manager on the forward and reverse sides of a many-to-many relation.

In the example::

class Pizza(Model):
    toppings = ManyToManyField(Topping, related_name='pizzas')

Pizza.toppings and Topping.pizzas are ManyToManyDescriptor instances.

Most of the implementation is delegated to a dynamically defined manager class built by create_forward_many_to_many_manager() defined below.

notification_transports

Accessor to the related objects manager on the forward and reverse sides of a many-to-many relation.

In the example::

class Pizza(Model):
    toppings = ManyToManyField(Topping, related_name='pizzas')

Pizza.toppings and Topping.pizzas are ManyToManyDescriptor instances.

Most of the implementation is delegated to a dynamically defined manager class built by create_forward_many_to_many_manager() defined below.

serializer: type[rest_framework.serializers.BaseSerializer]
67    @property
68    def serializer(self) -> type[BaseSerializer]:
69        from authentik.enterprise.lifecycle.review.api.rules import LifecycleRuleSerializer
70
71        return LifecycleRuleSerializer

Get serializer for this model

def get_objects(self) -> django.db.models.query.QuerySet:
80    def get_objects(self) -> QuerySet:
81        qs = self.content_type.get_all_objects_for_this_type()
82        if self.object_id:
83            qs = qs.filter(pk=self.object_id)
84        return qs
def apply(self):
111    def apply(self):
112        self._get_stale_iterations().update(state=ReviewState.CANCELED)
113
114        for iteration in self._get_newly_overdue_iterations():
115            iteration.make_overdue()
116
117        for obj in self._get_newly_due_objects():
118            LifecycleIteration.start(content_type=self.content_type, object_id=obj.pk, rule=self)
def is_satisfied_for_iteration( self, iteration: LifecycleIteration) -> bool:
120    def is_satisfied_for_iteration(self, iteration: LifecycleIteration) -> bool:
121        reviewers = self.reviewers.all()
122        if (
123            iteration.review_set.filter(reviewer__in=reviewers).distinct("reviewer").count()
124            < reviewers.count()
125        ):
126            return False
127        if self.reviewer_groups.count() == 0:
128            return True
129        if self.min_reviewers_is_per_group:
130            for g in self.reviewer_groups.all():
131                if (
132                    iteration.review_set.filter(
133                        reviewer__groups__in=Group.objects.filter(pk=g.pk).with_descendants()
134                    )
135                    .distinct()
136                    .count()
137                    < self.min_reviewers
138                ):
139                    return False
140            return True
141        else:
142            return (
143                iteration.review_set.filter(
144                    reviewer__groups__in=self.reviewer_groups.all().with_descendants()
145                )
146                .distinct()
147                .count()
148                >= self.min_reviewers
149            )
def get_reviewers(self) -> django.db.models.query.QuerySet:
151    def get_reviewers(self) -> QuerySet[User]:
152        return User.objects.filter(
153            Q(id__in=self.reviewers.all().values_list("pk", flat=True))
154            | Q(groups__in=self.reviewer_groups.all().with_descendants())
155        ).distinct()
def notify_reviewers(self, event: authentik.events.models.Event, severity: str):
157    def notify_reviewers(self, event: Event, severity: str):
158        from authentik.enterprise.lifecycle.review.tasks import send_notification
159
160        for transport in self.notification_transports.all():
161            for user in self.get_reviewers():
162                send_notification.send_with_options(
163                    args=(transport.pk, event.pk, user.pk, severity),
164                    rel_obj=transport,
165                )
166                if transport.send_once:
167                    break
content_type_id
def objects(unknown):

The type of the None singleton.

lifecyclerulereviewergroup_set

Accessor to the related objects manager on the reverse side of a many-to-one relation.

In the example::

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

Parent.children is a ReverseManyToOneDescriptor instance.

Most of the implementation is delegated to a dynamically defined manager class built by create_forward_many_to_many_manager() defined below.

lifecyclerulereviewer_set

Accessor to the related objects manager on the reverse side of a many-to-one relation.

In the example::

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

Parent.children is a ReverseManyToOneDescriptor instance.

Most of the implementation is delegated to a dynamically defined manager class built by create_forward_many_to_many_manager() defined below.

lifecyclerulenotificationtransport_set

Accessor to the related objects manager on the reverse side of a many-to-one relation.

In the example::

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

Parent.children is a ReverseManyToOneDescriptor instance.

Most of the implementation is delegated to a dynamically defined manager class built by create_forward_many_to_many_manager() defined below.

lifecycleiteration_set

Accessor to the related objects manager on the reverse side of a many-to-one relation.

In the example::

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

Parent.children is a ReverseManyToOneDescriptor instance.

Most of the implementation is delegated to a dynamically defined manager class built by create_forward_many_to_many_manager() defined below.

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

The requested object does not exist

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

The query returned multiple objects when only one was expected.

class LifecycleRuleNotificationTransport(authentik.lib.models.SimpleThroughModel):
214class LifecycleRuleNotificationTransport(SimpleThroughModel):
215    lifecycle_rule = models.ForeignKey(
216        LifecycleRule,
217        on_delete=models.CASCADE,
218        db_column="lifecyclerule_id",
219    )
220    notification_transport = models.ForeignKey(
221        NotificationTransport, on_delete=models.CASCADE, db_column="notificationtransport_id"
222    )
223
224    class Meta:
225        db_table = "authentik_lifecycle_lifecyclerule_notification_transports"
226        unique_together = (("lifecycle_rule", "notification_transport"),)
227        verbose_name = _("Lifecycle Rule Notification Transport")
228        verbose_name_plural = _("Lifecycle Rule Notification Transports")
229
230    def __str__(self):
231        return (
232            "LifecycleRuleNotificationTransport for LifecycleRule "
233            f"{self.lifecycle_rule_id} "
234            f"and NotificationTransport {self.notification_transport_id}."
235        )

LifecycleRuleNotificationTransport(id, lifecycle_rule, notification_transport)

lifecycle_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.

notification_transport

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.

lifecycle_rule_id
notification_transport_id
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.

def objects(unknown):

The type of the None singleton.

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

The requested object does not exist

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

The query returned multiple objects when only one was expected.

class LifecycleRuleReviewer(authentik.lib.models.SimpleThroughModel):
192class LifecycleRuleReviewer(SimpleThroughModel):
193    lifecycle_rule = models.ForeignKey(
194        LifecycleRule,
195        on_delete=models.CASCADE,
196        db_column="lifecyclerule_id",
197    )
198    user = models.ForeignKey("authentik_core.User", on_delete=models.CASCADE)
199
200    class Meta:
201        db_table = "authentik_lifecycle_lifecyclerule_reviewers"
202        unique_together = (("lifecycle_rule", "user"),)
203        verbose_name = _("Lifecycle Rule Reviewer")
204        verbose_name_plural = _("Lifecycle Rule Reviewers")
205
206    def __str__(self):
207        return (
208            "LifecycleRuleReviewer for LifecycleRule "
209            f"{self.lifecycle_rule_id} "
210            f"and User {self.user_id}."
211        )

LifecycleRuleReviewer(id, lifecycle_rule, user)

lifecycle_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.

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.

lifecycle_rule_id
user_id
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.

def objects(unknown):

The type of the None singleton.

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

The requested object does not exist

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

The query returned multiple objects when only one was expected.

class LifecycleRuleReviewerGroup(authentik.lib.models.SimpleThroughModel):
170class LifecycleRuleReviewerGroup(SimpleThroughModel):
171    lifecycle_rule = models.ForeignKey(
172        LifecycleRule,
173        on_delete=models.CASCADE,
174        db_column="lifecyclerule_id",
175    )
176    group = models.ForeignKey("authentik_core.Group", on_delete=models.CASCADE)
177
178    class Meta:
179        db_table = "authentik_lifecycle_lifecyclerule_reviewer_groups"
180        unique_together = (("lifecycle_rule", "group"),)
181        verbose_name = _("Lifecycle Rule Reviewer Group")
182        verbose_name_plural = _("Lifecycle Rule Reviewer Groups")
183
184    def __str__(self):
185        return (
186            "LifecycleRuleReviewerGroup for LifecycleRule "
187            f"{self.lifecycle_rule_id} "
188            f"and Group {self.group_id}."
189        )

LifecycleRuleReviewerGroup(id, lifecycle_rule, group)

lifecycle_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.

group

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.

lifecycle_rule_id
group_id
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.

def objects(unknown):

The type of the None singleton.

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

The requested object does not exist

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

The query returned multiple objects when only one was expected.

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 Review(authentik.lib.models.SerializerModel):
359class Review(SerializerModel):
360    id = models.UUIDField(primary_key=True, default=uuid4)
361    iteration = models.ForeignKey(LifecycleIteration, on_delete=models.CASCADE)
362
363    reviewer = models.ForeignKey("authentik_core.User", on_delete=models.CASCADE)
364    timestamp = models.DateTimeField(auto_now_add=True)
365    note = models.TextField(null=True)
366
367    class Meta:
368        unique_together = [["iteration", "reviewer"]]
369
370    @property
371    def serializer(self) -> type[BaseSerializer]:
372        from authentik.enterprise.lifecycle.review.api.reviews import ReviewSerializer
373
374        return ReviewSerializer

Review(id, iteration, reviewer, timestamp, note)

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.

iteration

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.

reviewer

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 timestamp(unknown):

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

def note(unknown):

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

serializer: type[rest_framework.serializers.BaseSerializer]
370    @property
371    def serializer(self) -> type[BaseSerializer]:
372        from authentik.enterprise.lifecycle.review.api.reviews import ReviewSerializer
373
374        return ReviewSerializer

Get serializer for this model

iteration_id
reviewer_id
def get_next_by_timestamp(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_timestamp(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 objects(unknown):

The type of the None singleton.

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

The requested object does not exist

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

The query returned multiple objects when only one was expected.

class ReviewState(django.db.models.enums.TextChoices):
238class ReviewState(models.TextChoices):
239    REVIEWED = "REVIEWED", _("Reviewed")
240    PENDING = "PENDING", _("Pending")
241    OVERDUE = "OVERDUE", _("Overdue")
242    CANCELED = "CANCELED", _("Canceled")

Class for creating enumerated string choices.

 66class UserExpirationRule(SerializerModel, PolicyBindingModel):
 67    """Schedule an offboarding for every user in scope who has been inactive for
 68    `inactivity_duration`, using the selected activity clock."""
 69
 70    id = models.UUIDField(primary_key=True, default=uuid4)
 71    name = models.TextField(unique=True)
 72    # Disabled by default so rules can be previewed before the first sweep.
 73    enabled = models.BooleanField(default=False)
 74    activity_basis = models.TextField(
 75        choices=ActivityBasis.choices,
 76        default=ActivityBasis.SUCCESSFUL_EVENTS,
 77        help_text=_("Measure inactivity from the last login or successful user activity."),
 78    )
 79    group = models.ForeignKey(
 80        "authentik_core.Group",
 81        on_delete=models.CASCADE,
 82        null=True,
 83        blank=True,
 84        default=None,
 85        help_text=_(
 86            "Only expire members of this group (including descendant groups). "
 87            "Leave empty to apply to every user."
 88        ),
 89    )
 90    user_types = ArrayField(
 91        models.TextField(choices=UserTypes.choices),
 92        default=default_user_types,
 93        blank=True,
 94        help_text=_("Only expire users of these types. Service accounts are excluded by default."),
 95    )
 96    inactivity_duration = models.TextField(
 97        default="days=90",
 98        validators=[timedelta_string_validator],
 99        help_text=_("How long a user may be inactive before they are expired."),
100    )
101    action = models.TextField(
102        choices=OffboardingAction.choices, default=OffboardingAction.DEACTIVATE
103    )
104    revoke_sessions = models.BooleanField(default=True)
105    revoke_tokens = models.BooleanField(default=True)
106    warn_before = models.TextField(
107        null=True,
108        blank=True,
109        default=None,
110        validators=[timedelta_string_validator],
111        help_text=_(
112            "Schedule the offboarding and notify the user this long before they expire. "
113            "Leave empty to expire users without warning."
114        ),
115    )
116    notification_transports = models.ManyToManyField(
117        NotificationTransport,
118        blank=True,
119        through="UserExpirationRuleNotificationTransport",
120        help_text=_(
121            "Select which transports should be used to warn the user. If none are "
122            "selected, the notification will only be shown in the authentik UI."
123        ),
124    )
125    exclude_superusers = models.BooleanField(
126        default=True,
127        help_text=_("Never expire members of a superuser group."),
128    )
129
130    class Meta:
131        verbose_name = _("User Expiration Rule")
132        verbose_name_plural = _("User Expiration Rules")
133
134    @property
135    def serializer(self) -> type[BaseSerializer]:
136        from authentik.enterprise.lifecycle.expiration.api import UserExpirationRuleSerializer
137
138        return UserExpirationRuleSerializer
139
140    def __str__(self):
141        return f"User Expiration Rule {self.name}"
142
143    @property
144    def inactivity_timedelta(self) -> timedelta:
145        return timedelta_from_string(self.inactivity_duration)
146
147    def due_at(self, user: User) -> datetime:
148        last_activity = max(filter(None, (user.last_login, user.date_joined)))
149        if self.activity_basis == ActivityBasis.SUCCESSFUL_EVENTS:
150            activity = getattr(user, "activity", None)
151            if activity is not None:
152                last_activity = max(
153                    last_activity, activity.last_activity_at + USER_ACTIVITY_INTERVAL
154                )
155        return last_activity + self.inactivity_timedelta
156
157    def scheduled_at(self, due_at: datetime, created_at: datetime) -> datetime:
158        """When to run an offboarding due at `due_at`. Users always get the full warning
159        period after it's created, even if they were already overdue."""
160        if not self.warn_before:
161            return due_at
162        return max(due_at, created_at + timedelta_from_string(self.warn_before))
163
164    def rank(self, row: UserOffboarding) -> Rank:
165        """How this rule would rank the user's pending row if it owned it."""
166        return Rank(
167            self.scheduled_at(self.due_at(row.user), row.created_at),
168            ACTION_SEVERITY[self.action],
169            self.pk,
170        )
171
172    @staticmethod
173    def row_rank(row: UserOffboarding) -> Rank:
174        return Rank(row.scheduled_at, ACTION_SEVERITY[row.action], row.rule_id)
175
176    @staticmethod
177    def withdraw_pending(user: User, logged_in_at: datetime | None = None):
178        """Delete the user's pending generated offboardings, optionally only those
179        created before `logged_in_at`."""
180        rows = UserOffboarding.objects.filter(
181            user=user, rule__isnull=False, status=OffboardingStatus.PENDING
182        )
183        if logged_in_at is not None:
184            rows = rows.filter(created_at__lte=logged_in_at)
185        rows.delete()
186
187    def _row_matches(self, row: UserOffboarding, due_at: datetime) -> bool:
188        return (row.scheduled_at, row.action, row.revoke_sessions, row.revoke_tokens) == (
189            due_at,
190            self.action,
191            self.revoke_sessions,
192            self.revoke_tokens,
193        )
194
195    def _update_offboarding(self, row: UserOffboarding, due_at: datetime):
196        row.rule = self
197        row.scheduled_at = due_at
198        row.action = self.action
199        row.revoke_sessions = self.revoke_sessions
200        row.revoke_tokens = self.revoke_tokens
201        row.save(
202            update_fields=["rule", "scheduled_at", "action", "revoke_sessions", "revoke_tokens"]
203        )
204
205    @classmethod
206    def resolve_winner(cls, row: UserOffboarding) -> bool:
207        """Hand a locked pending row to the enabled rule that outranks its owner, if any.
208        Returns whether the owner changed."""
209        best: UserExpirationRule | None = None
210        best_rank = cls.row_rank(row)
211        for rule in cls.objects.filter(enabled=True).exclude(pk=row.rule_id):
212            rank = rule.rank(row)
213            if rank < best_rank and rule._in_scope(row.user):
214                best, best_rank = rule, rank
215        if best is None:
216            return False
217        best._update_offboarding(row, best_rank.due_at)
218        return True
219
220    def scope(
221        self, *, threshold: datetime | None = None, user: User | None = None
222    ) -> QuerySet[User]:
223        """Users this rule applies to, before policies. With `threshold`, only users
224        inactive since then."""
225        types = [t for t in self.user_types if t != UserTypes.INTERNAL_SERVICE_ACCOUNT]
226        qs = (
227            User.objects.exclude_anonymous()
228            .select_related("activity")
229            .filter(is_active=True, type__in=types)
230        )
231        if user is not None:
232            qs = qs.filter(pk=user.pk)
233        if self.group_id:
234            members = Group.objects.filter(pk=self.group_id).with_descendants()
235            qs = qs.filter(pk__in=User.objects.filter(groups__in=members).values("pk"))
236        if self.exclude_superusers:
237            superuser_groups = Group.objects.filter(is_superuser=True).with_descendants()
238            qs = qs.exclude(pk__in=User.objects.filter(groups__in=superuser_groups).values("pk"))
239        if threshold is not None:
240            # Two range tests instead of GREATEST() so the last_login index is used.
241            qs = qs.filter(
242                Q(last_login__isnull=True) | Q(last_login__lte=threshold),
243                date_joined__lte=threshold,
244            )
245            if self.activity_basis == ActivityBasis.SUCCESSFUL_EVENTS:
246                qs = qs.filter(
247                    Q(activity__isnull=True)
248                    | Q(activity__last_activity_at__lte=threshold - USER_ACTIVITY_INTERVAL)
249                )
250        return qs
251
252    def _apply_policies(self, qs: QuerySet[User]) -> QuerySet[User]:
253        """Policies run per user, so only apply them to an already narrowed set."""
254        if not PolicyBinding.objects.filter(target=self, enabled=True).exists():
255            return qs
256        from authentik.policies.engine import FilterPolicyEngine
257
258        return FilterPolicyEngine(self, qs).build().result
259
260    def _eligible_user_ids(self, user_ids: Collection[int]) -> set[int]:
261        return set(
262            self._apply_policies(self.scope().filter(pk__in=user_ids)).values_list("pk", flat=True)
263        )
264
265    def _in_scope(self, user: User) -> bool:
266        return self._apply_policies(self.scope(user=user)).exists()
267
268    def _threshold(self) -> datetime:
269        warn = timedelta_from_string(self.warn_before) if self.warn_before else timedelta()
270        return timezone.now() - self.inactivity_timedelta + warn
271
272    def candidates(self, *, withdrawn: Collection[UUID] = ()) -> QuerySet[User]:
273        """Users this rule would schedule a new offboarding for on its next run."""
274        qs = self.scope(threshold=self._threshold()).annotate(
275            login_activity=Greatest("last_login", "date_joined")
276        )
277        pending = UserOffboarding.objects.filter(
278            user=OuterRef("pk"), status=OffboardingStatus.PENDING
279        ).exclude(pk__in=withdrawn)
280        qs = qs.exclude(models.Exists(pending))
281        # Canceled, completed or failed generated rows exempt the user until they
282        # log in again.
283        terminal = UserOffboarding.objects.filter(
284            user=OuterRef("pk"),
285            generated=True,
286            status__in=[
287                OffboardingStatus.COMPLETED,
288                OffboardingStatus.CANCELED,
289                OffboardingStatus.FAILED,
290            ],
291            executed_at__gte=OuterRef("login_activity"),
292        )
293        qs = qs.exclude(models.Exists(terminal))
294        return self._apply_policies(qs)
295
296    def _warn(self, user: User, offboarding: UserOffboarding):
297        if not self.warn_before:
298            return
299
300        from authentik.enterprise.lifecycle.review.tasks import send_notification
301
302        event = Event.new(
303            EventAction.USER_EXPIRATION_WARNING,
304            message=gettext(
305                "User %(username)s will be offboarded (%(action)s) on %(scheduled_at)s "
306                "due to inactivity"
307            )
308            % {
309                "username": user.username,
310                "action": offboarding.action,
311                "scheduled_at": offboarding.scheduled_at.isoformat(),
312            },
313            rule=self,
314            scheduled_at=offboarding.scheduled_at,
315            offboarding_action=offboarding.action,
316        )
317        event.set_user(user)
318        event.save()
319        transports = self._transports
320        if not transports:
321            send_notification.send_with_options(
322                args=(None, event.pk, user.pk, NotificationSeverity.NOTICE),
323                rel_obj=self,
324            )
325        for transport in transports:
326            send_notification.send_with_options(
327                args=(transport.pk, event.pk, user.pk, NotificationSeverity.NOTICE),
328                rel_obj=transport,
329            )
330
331    @cached_property
332    def _transports(self) -> list[NotificationTransport]:
333        return list(self.notification_transports.all())
334
335    def _pending_due_at(
336        self, row: UserOffboarding, *, in_scope: bool | None = None
337    ) -> datetime | None:
338        """Due date for an owned row, or None if it should be withdrawn, assuming the rule
339        is enabled."""
340        if in_scope is None:
341            in_scope = self._in_scope(row.user)
342        activity = getattr(row.user, "activity", None)
343        event_after_creation = (
344            self.activity_basis == ActivityBasis.SUCCESSFUL_EVENTS
345            and activity is not None
346            and activity.last_activity_at >= row.created_at
347        )
348        if (
349            not in_scope
350            or (row.user.last_login is not None and row.user.last_login >= row.created_at)
351            or event_after_creation
352        ):
353            return None
354        return self.scheduled_at(self.due_at(row.user), row.created_at)
355
356    def reconcile_offboarding(
357        self, row: UserOffboarding, *, in_scope: bool | None = None
358    ) -> tuple[bool, bool]:
359        """Refresh a locked pending row owned by this rule. Returns whether the row was
360        kept and whether the user needs another warning."""
361        due_at = self._pending_due_at(row, in_scope=in_scope) if self.enabled else None
362        if due_at is None:
363            row.delete()
364            return False, False
365        rewarn = due_at < row.scheduled_at or row.action != self.action
366        if not self._row_matches(row, due_at):
367            self._update_offboarding(row, due_at)
368        return True, rewarn
369
370    def _revisit_owned_rows(self):
371        rows = UserOffboarding.objects.filter(rule=self, status=OffboardingStatus.PENDING)
372        if not self.enabled:
373            # Lock before deleting, since `delete()` selects the rows first. Rows that were
374            # taken over or executed in the meantime no longer match and are kept.
375            while True:
376                with transaction.atomic():
377                    pks = list(
378                        rows.select_for_update(of=("self",)).values_list("pk", flat=True)[
379                            :CHUNK_SIZE
380                        ]
381                    )
382                    if not pks:
383                        return
384                    UserOffboarding.objects.filter(pk__in=pks).delete()
385        rows = rows.select_related("user", "user__activity")
386        for batch in batched(rows.iterator(chunk_size=CHUNK_SIZE), CHUNK_SIZE, strict=False):
387            eligible = self._eligible_user_ids([row.user_id for row in batch])
388            for row in batch:
389                due_at = self._pending_due_at(row, in_scope=row.user_id in eligible)
390                if due_at is not None and self._row_matches(row, due_at):
391                    continue
392                # Re-read changed rows under the lock before reconciling them.
393                with transaction.atomic():
394                    locked = (
395                        UserOffboarding.objects.select_for_update(of=("self",))
396                        .filter(pk=row.pk, rule=self, status=OffboardingStatus.PENDING)
397                        .select_related("user", "user__activity")
398                        .first()
399                    )
400                    if locked is None:
401                        continue
402                    _, rewarn = self.reconcile_offboarding(
403                        locked, in_scope=locked.user_id in eligible
404                    )
405                if rewarn:
406                    self._warn(locked.user, locked)
407
408    def _foreign_rows(self) -> QuerySet[UserOffboarding]:
409        return (
410            UserOffboarding.objects.filter(status=OffboardingStatus.PENDING, rule__isnull=False)
411            .exclude(rule=self)
412            .filter(user__in=self.scope(threshold=self._threshold()))
413        )
414
415    def preview_pending(
416        self,
417    ) -> Iterator[tuple[PendingChange, UserOffboarding, datetime | None]]:
418        """Changes to pending rows if this rule were enabled, without writing anything."""
419        activity = Prefetch("user", queryset=User.objects.select_related("activity"))
420        owned = UserOffboarding.objects.filter(rule=self, status=OffboardingStatus.PENDING)
421        owned_rows = owned.order_by("user__username").prefetch_related(activity)
422        for batch in batched(owned_rows.iterator(chunk_size=CHUNK_SIZE), CHUNK_SIZE, strict=False):
423            eligible = self._eligible_user_ids([row.user_id for row in batch])
424            for row in batch:
425                due_at = self._pending_due_at(row, in_scope=row.user_id in eligible)
426                if due_at is None:
427                    yield PendingChange.REMOVED, row, None
428                elif not self._row_matches(row, due_at):
429                    yield PendingChange.UPDATED, row, due_at
430        for batch in batched(
431            self._foreign_rows()
432            .order_by("user__username")
433            .prefetch_related(activity)
434            .iterator(chunk_size=CHUNK_SIZE),
435            CHUNK_SIZE,
436            strict=False,
437        ):
438            ranked = [(row, self.rank(row)) for row in batch]
439            ranked = [(row, rank) for row, rank in ranked if rank < self.row_rank(row)]
440            if not ranked:
441                continue
442            eligible = self._eligible_user_ids([row.user_id for row, _ in ranked])
443            for row, rank in ranked:
444                if row.user_id in eligible:
445                    yield PendingChange.TAKEN_OVER, row, rank.due_at
446
447    def _tighten_foreign_rows(self):
448        """Take over other rules' pending rows that this rule outranks."""
449        rows = self._foreign_rows().select_related("user", "user__activity")
450        for batch in batched(rows.iterator(chunk_size=CHUNK_SIZE), CHUNK_SIZE, strict=False):
451            ranked = [(row, self.rank(row)) for row in batch]
452            ranked = [(row, rank) for row, rank in ranked if rank < self.row_rank(row)]
453            if not ranked:
454                continue
455            eligible = self._eligible_user_ids([row.user_id for row, _ in ranked])
456            for row, rank in ranked:
457                if row.user_id not in eligible:
458                    continue
459                with transaction.atomic():
460                    locked = (
461                        UserOffboarding.objects.select_for_update(of=("self",))
462                        .filter(pk=row.pk, status=OffboardingStatus.PENDING, rule__isnull=False)
463                        .first()
464                    )
465                    if locked is None or rank >= self.row_rank(locked):
466                        continue
467                    self._update_offboarding(locked, rank.due_at)
468                self._warn(row.user, locked)
469
470    def apply(self) -> int:
471        """Run one sweep. Returns the number of offboardings created."""
472        # Transports don't change during a sweep, so read them once.
473        self.__dict__.pop("_transports", None)
474        self._revisit_owned_rows()
475        if not self.enabled:
476            return 0
477        self._tighten_foreign_rows()
478        created = 0
479        candidates = self.candidates().iterator(chunk_size=CHUNK_SIZE)
480        for batch in batched(candidates, CHUNK_SIZE, strict=False):
481            # Activity may have changed since candidates were selected.
482            still_inactive = set(
483                self.scope(threshold=self._threshold())
484                .filter(pk__in=[user.pk for user in batch])
485                .values_list("pk", flat=True)
486            )
487            for user in batch:
488                if user.pk not in still_inactive:
489                    continue
490                try:
491                    with transaction.atomic():
492                        due_at = self.due_at(user)
493                        offboarding = UserOffboarding.objects.create(
494                            user=user,
495                            rule=self,
496                            generated=True,
497                            scheduled_at=due_at,
498                            action=self.action,
499                            revoke_sessions=self.revoke_sessions,
500                            revoke_tokens=self.revoke_tokens,
501                        )
502                        # `created_at` is only known after the insert.
503                        scheduled_at = self.scheduled_at(due_at, offboarding.created_at)
504                        if scheduled_at != due_at:
505                            offboarding.scheduled_at = scheduled_at
506                            offboarding.save(update_fields=["scheduled_at"])
507                except IntegrityError:
508                    # Another offboarding was scheduled since selection.
509                    continue
510                self._warn(user, offboarding)
511                created += 1
512        LOGGER.info("Applied user expiration rule", rule=self.name, created=created)
513        return created

Schedule an offboarding for every user in scope who has been inactive for inactivity_duration, using the selected activity clock.

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.

def name(unknown):

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

def enabled(unknown):

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

def activity_basis(unknown):

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

group

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 user_types(unknown):

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

def inactivity_duration(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 warn_before(unknown):

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

notification_transports

Accessor to the related objects manager on the forward and reverse sides of a many-to-many relation.

In the example::

class Pizza(Model):
    toppings = ManyToManyField(Topping, related_name='pizzas')

Pizza.toppings and Topping.pizzas are ManyToManyDescriptor instances.

Most of the implementation is delegated to a dynamically defined manager class built by create_forward_many_to_many_manager() defined below.

def exclude_superusers(unknown):

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

serializer: type[rest_framework.serializers.BaseSerializer]
134    @property
135    def serializer(self) -> type[BaseSerializer]:
136        from authentik.enterprise.lifecycle.expiration.api import UserExpirationRuleSerializer
137
138        return UserExpirationRuleSerializer

Get serializer for this model

inactivity_timedelta: datetime.timedelta
143    @property
144    def inactivity_timedelta(self) -> timedelta:
145        return timedelta_from_string(self.inactivity_duration)
def due_at(self, user: authentik.core.models.User) -> datetime.datetime:
147    def due_at(self, user: User) -> datetime:
148        last_activity = max(filter(None, (user.last_login, user.date_joined)))
149        if self.activity_basis == ActivityBasis.SUCCESSFUL_EVENTS:
150            activity = getattr(user, "activity", None)
151            if activity is not None:
152                last_activity = max(
153                    last_activity, activity.last_activity_at + USER_ACTIVITY_INTERVAL
154                )
155        return last_activity + self.inactivity_timedelta
def scheduled_at( self, due_at: datetime.datetime, created_at: datetime.datetime) -> datetime.datetime:
157    def scheduled_at(self, due_at: datetime, created_at: datetime) -> datetime:
158        """When to run an offboarding due at `due_at`. Users always get the full warning
159        period after it's created, even if they were already overdue."""
160        if not self.warn_before:
161            return due_at
162        return max(due_at, created_at + timedelta_from_string(self.warn_before))

When to run an offboarding due at due_at. Users always get the full warning period after it's created, even if they were already overdue.

164    def rank(self, row: UserOffboarding) -> Rank:
165        """How this rule would rank the user's pending row if it owned it."""
166        return Rank(
167            self.scheduled_at(self.due_at(row.user), row.created_at),
168            ACTION_SEVERITY[self.action],
169            self.pk,
170        )

How this rule would rank the user's pending row if it owned it.

@staticmethod
def row_rank( row: UserOffboarding) -> authentik.enterprise.lifecycle.expiration.models.Rank:
172    @staticmethod
173    def row_rank(row: UserOffboarding) -> Rank:
174        return Rank(row.scheduled_at, ACTION_SEVERITY[row.action], row.rule_id)
@staticmethod
def withdraw_pending( user: authentik.core.models.User, logged_in_at: datetime.datetime | None = None):
176    @staticmethod
177    def withdraw_pending(user: User, logged_in_at: datetime | None = None):
178        """Delete the user's pending generated offboardings, optionally only those
179        created before `logged_in_at`."""
180        rows = UserOffboarding.objects.filter(
181            user=user, rule__isnull=False, status=OffboardingStatus.PENDING
182        )
183        if logged_in_at is not None:
184            rows = rows.filter(created_at__lte=logged_in_at)
185        rows.delete()

Delete the user's pending generated offboardings, optionally only those created before logged_in_at.

@classmethod
def resolve_winner( cls, row: UserOffboarding) -> bool:
205    @classmethod
206    def resolve_winner(cls, row: UserOffboarding) -> bool:
207        """Hand a locked pending row to the enabled rule that outranks its owner, if any.
208        Returns whether the owner changed."""
209        best: UserExpirationRule | None = None
210        best_rank = cls.row_rank(row)
211        for rule in cls.objects.filter(enabled=True).exclude(pk=row.rule_id):
212            rank = rule.rank(row)
213            if rank < best_rank and rule._in_scope(row.user):
214                best, best_rank = rule, rank
215        if best is None:
216            return False
217        best._update_offboarding(row, best_rank.due_at)
218        return True

Hand a locked pending row to the enabled rule that outranks its owner, if any. Returns whether the owner changed.

def scope( self, *, threshold: datetime.datetime | None = None, user: authentik.core.models.User | None = None) -> django.db.models.query.QuerySet:
220    def scope(
221        self, *, threshold: datetime | None = None, user: User | None = None
222    ) -> QuerySet[User]:
223        """Users this rule applies to, before policies. With `threshold`, only users
224        inactive since then."""
225        types = [t for t in self.user_types if t != UserTypes.INTERNAL_SERVICE_ACCOUNT]
226        qs = (
227            User.objects.exclude_anonymous()
228            .select_related("activity")
229            .filter(is_active=True, type__in=types)
230        )
231        if user is not None:
232            qs = qs.filter(pk=user.pk)
233        if self.group_id:
234            members = Group.objects.filter(pk=self.group_id).with_descendants()
235            qs = qs.filter(pk__in=User.objects.filter(groups__in=members).values("pk"))
236        if self.exclude_superusers:
237            superuser_groups = Group.objects.filter(is_superuser=True).with_descendants()
238            qs = qs.exclude(pk__in=User.objects.filter(groups__in=superuser_groups).values("pk"))
239        if threshold is not None:
240            # Two range tests instead of GREATEST() so the last_login index is used.
241            qs = qs.filter(
242                Q(last_login__isnull=True) | Q(last_login__lte=threshold),
243                date_joined__lte=threshold,
244            )
245            if self.activity_basis == ActivityBasis.SUCCESSFUL_EVENTS:
246                qs = qs.filter(
247                    Q(activity__isnull=True)
248                    | Q(activity__last_activity_at__lte=threshold - USER_ACTIVITY_INTERVAL)
249                )
250        return qs

Users this rule applies to, before policies. With threshold, only users inactive since then.

def candidates( self, *, withdrawn: Collection[uuid.UUID] = ()) -> django.db.models.query.QuerySet:
272    def candidates(self, *, withdrawn: Collection[UUID] = ()) -> QuerySet[User]:
273        """Users this rule would schedule a new offboarding for on its next run."""
274        qs = self.scope(threshold=self._threshold()).annotate(
275            login_activity=Greatest("last_login", "date_joined")
276        )
277        pending = UserOffboarding.objects.filter(
278            user=OuterRef("pk"), status=OffboardingStatus.PENDING
279        ).exclude(pk__in=withdrawn)
280        qs = qs.exclude(models.Exists(pending))
281        # Canceled, completed or failed generated rows exempt the user until they
282        # log in again.
283        terminal = UserOffboarding.objects.filter(
284            user=OuterRef("pk"),
285            generated=True,
286            status__in=[
287                OffboardingStatus.COMPLETED,
288                OffboardingStatus.CANCELED,
289                OffboardingStatus.FAILED,
290            ],
291            executed_at__gte=OuterRef("login_activity"),
292        )
293        qs = qs.exclude(models.Exists(terminal))
294        return self._apply_policies(qs)

Users this rule would schedule a new offboarding for on its next run.

def reconcile_offboarding( self, row: UserOffboarding, *, in_scope: bool | None = None) -> tuple[bool, bool]:
356    def reconcile_offboarding(
357        self, row: UserOffboarding, *, in_scope: bool | None = None
358    ) -> tuple[bool, bool]:
359        """Refresh a locked pending row owned by this rule. Returns whether the row was
360        kept and whether the user needs another warning."""
361        due_at = self._pending_due_at(row, in_scope=in_scope) if self.enabled else None
362        if due_at is None:
363            row.delete()
364            return False, False
365        rewarn = due_at < row.scheduled_at or row.action != self.action
366        if not self._row_matches(row, due_at):
367            self._update_offboarding(row, due_at)
368        return True, rewarn

Refresh a locked pending row owned by this rule. Returns whether the row was kept and whether the user needs another warning.

def preview_pending( self) -> Iterator[tuple[authentik.enterprise.lifecycle.expiration.models.PendingChange, UserOffboarding, datetime.datetime | None]]:
415    def preview_pending(
416        self,
417    ) -> Iterator[tuple[PendingChange, UserOffboarding, datetime | None]]:
418        """Changes to pending rows if this rule were enabled, without writing anything."""
419        activity = Prefetch("user", queryset=User.objects.select_related("activity"))
420        owned = UserOffboarding.objects.filter(rule=self, status=OffboardingStatus.PENDING)
421        owned_rows = owned.order_by("user__username").prefetch_related(activity)
422        for batch in batched(owned_rows.iterator(chunk_size=CHUNK_SIZE), CHUNK_SIZE, strict=False):
423            eligible = self._eligible_user_ids([row.user_id for row in batch])
424            for row in batch:
425                due_at = self._pending_due_at(row, in_scope=row.user_id in eligible)
426                if due_at is None:
427                    yield PendingChange.REMOVED, row, None
428                elif not self._row_matches(row, due_at):
429                    yield PendingChange.UPDATED, row, due_at
430        for batch in batched(
431            self._foreign_rows()
432            .order_by("user__username")
433            .prefetch_related(activity)
434            .iterator(chunk_size=CHUNK_SIZE),
435            CHUNK_SIZE,
436            strict=False,
437        ):
438            ranked = [(row, self.rank(row)) for row in batch]
439            ranked = [(row, rank) for row, rank in ranked if rank < self.row_rank(row)]
440            if not ranked:
441                continue
442            eligible = self._eligible_user_ids([row.user_id for row, _ in ranked])
443            for row, rank in ranked:
444                if row.user_id in eligible:
445                    yield PendingChange.TAKEN_OVER, row, rank.due_at

Changes to pending rows if this rule were enabled, without writing anything.

def apply(self) -> int:
470    def apply(self) -> int:
471        """Run one sweep. Returns the number of offboardings created."""
472        # Transports don't change during a sweep, so read them once.
473        self.__dict__.pop("_transports", None)
474        self._revisit_owned_rows()
475        if not self.enabled:
476            return 0
477        self._tighten_foreign_rows()
478        created = 0
479        candidates = self.candidates().iterator(chunk_size=CHUNK_SIZE)
480        for batch in batched(candidates, CHUNK_SIZE, strict=False):
481            # Activity may have changed since candidates were selected.
482            still_inactive = set(
483                self.scope(threshold=self._threshold())
484                .filter(pk__in=[user.pk for user in batch])
485                .values_list("pk", flat=True)
486            )
487            for user in batch:
488                if user.pk not in still_inactive:
489                    continue
490                try:
491                    with transaction.atomic():
492                        due_at = self.due_at(user)
493                        offboarding = UserOffboarding.objects.create(
494                            user=user,
495                            rule=self,
496                            generated=True,
497                            scheduled_at=due_at,
498                            action=self.action,
499                            revoke_sessions=self.revoke_sessions,
500                            revoke_tokens=self.revoke_tokens,
501                        )
502                        # `created_at` is only known after the insert.
503                        scheduled_at = self.scheduled_at(due_at, offboarding.created_at)
504                        if scheduled_at != due_at:
505                            offboarding.scheduled_at = scheduled_at
506                            offboarding.save(update_fields=["scheduled_at"])
507                except IntegrityError:
508                    # Another offboarding was scheduled since selection.
509                    continue
510                self._warn(user, offboarding)
511                created += 1
512        LOGGER.info("Applied user expiration rule", rule=self.name, created=created)
513        return created

Run one sweep. Returns the number of offboardings created.

def get_activity_basis_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.

group_id
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.

policybindingmodel_ptr_id
policybindingmodel_ptr

Accessor to the related object on the forward side of a one-to-one relation.

In the example::

class Restaurant(Model):
    place = OneToOneField(Place, related_name='restaurant')

Restaurant.place is a ForwardOneToOneDescriptor instance.

offboardings

Accessor to the related objects manager on the reverse side of a many-to-one relation.

In the example::

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

Parent.children is a ReverseManyToOneDescriptor instance.

Most of the implementation is delegated to a dynamically defined manager class built by create_forward_many_to_many_manager() defined below.

userexpirationrulenotificationtransport_set

Accessor to the related objects manager on the reverse side of a many-to-one relation.

In the example::

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

Parent.children is a ReverseManyToOneDescriptor instance.

Most of the implementation is delegated to a dynamically defined manager class built by create_forward_many_to_many_manager() defined below.

class UserExpirationRule.DoesNotExist(authentik.policies.models.PolicyBindingModel.DoesNotExist):

The requested object does not exist

class UserExpirationRule.MultipleObjectsReturned(authentik.policies.models.PolicyBindingModel.MultipleObjectsReturned):

The query returned multiple objects when only one was expected.

class UserExpirationRuleNotificationTransport(authentik.lib.models.SimpleThroughModel):
516class UserExpirationRuleNotificationTransport(SimpleThroughModel):
517    user_expiration_rule = models.ForeignKey(
518        UserExpirationRule,
519        on_delete=models.CASCADE,
520        db_column="userexpirationrule_id",
521    )
522    notification_transport = models.ForeignKey(
523        NotificationTransport, on_delete=models.CASCADE, db_column="notificationtransport_id"
524    )
525
526    class Meta:
527        db_table = "authentik_lifecycle_userexpirationrule_notification_transports"
528        unique_together = (("user_expiration_rule", "notification_transport"),)
529        verbose_name = _("User Expiration Rule Notification Transport")
530        verbose_name_plural = _("User Expiration Rule Notification Transports")
531
532    def __str__(self):
533        return (
534            "UserExpirationRuleNotificationTransport for UserExpirationRule "
535            f"{self.user_expiration_rule_id} "
536            f"and NotificationTransport {self.notification_transport_id}."
537        )

UserExpirationRuleNotificationTransport(id, user_expiration_rule, notification_transport)

user_expiration_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.

notification_transport

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.

user_expiration_rule_id
notification_transport_id
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.

def objects(unknown):

The type of the None singleton.

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

The requested object does not exist

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

The query returned multiple objects when only one was expected.

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.