authentik.enterprise.lifecycle.offboarding.api

  1from django.db import IntegrityError, transaction
  2from django.utils.timezone import now
  3from django.utils.translation import gettext_lazy as _
  4from rest_framework.exceptions import PermissionDenied, ValidationError
  5from rest_framework.fields import CharField, UUIDField
  6from rest_framework.mixins import (
  7    CreateModelMixin,
  8    DestroyModelMixin,
  9    ListModelMixin,
 10    RetrieveModelMixin,
 11)
 12from rest_framework.request import Request
 13from rest_framework.response import Response
 14from rest_framework.viewsets import GenericViewSet
 15
 16from authentik.core.api.groups import PartialUserSerializer
 17from authentik.core.api.utils import ModelSerializer, PassiveSerializer
 18from authentik.core.models import User, UserTypes
 19from authentik.enterprise.api import EnterpriseRequiredMixin
 20from authentik.enterprise.lifecycle.offboarding.models import OffboardingStatus, UserOffboarding
 21
 22DUPLICATE_PENDING_ERROR = _("This user already has a pending offboarding scheduled.")
 23
 24
 25class PartialUserExpirationRuleSerializer(PassiveSerializer):
 26    pk = UUIDField(read_only=True)
 27    name = CharField(read_only=True)
 28
 29
 30class UserOffboardingSerializer(EnterpriseRequiredMixin, ModelSerializer):
 31    user_obj = PartialUserSerializer(source="user", read_only=True)
 32    created_by_obj = PartialUserSerializer(source="created_by", read_only=True)
 33    rule_obj = PartialUserExpirationRuleSerializer(source="rule", read_only=True)
 34
 35    class Meta:
 36        model = UserOffboarding
 37        fields = [
 38            "id",
 39            "user",
 40            "user_obj",
 41            "scheduled_at",
 42            "action",
 43            "revoke_sessions",
 44            "revoke_tokens",
 45            "status",
 46            "created_by_obj",
 47            "created_at",
 48            "executed_at",
 49            "rule",
 50            "rule_obj",
 51            "generated",
 52        ]
 53        read_only_fields = [
 54            "id",
 55            "user_obj",
 56            "status",
 57            "created_by_obj",
 58            "created_at",
 59            "executed_at",
 60            "rule",
 61            "rule_obj",
 62            "generated",
 63        ]
 64
 65    def validate_scheduled_at(self, value):
 66        if value <= now():
 67            raise ValidationError(_("Offboarding must be scheduled in the future."))
 68        return value
 69
 70    def validate_user(self, user: User) -> User:
 71        if user.type == UserTypes.INTERNAL_SERVICE_ACCOUNT:
 72            raise ValidationError(_("Internal service accounts cannot be offboarded."))
 73        request = self.context.get("request")
 74        if request is not None and user.pk == request.user.pk:
 75            raise ValidationError(_("You cannot offboard your own account."))
 76        return user
 77
 78    def validate(self, attrs: dict) -> dict:
 79        attrs = super().validate(attrs)
 80        # Enforce a single pending offboarding per user (mirrors the DB constraint
 81        # but returns a friendly error instead of an IntegrityError).
 82        user = attrs.get("user", getattr(self.instance, "user", None))
 83        if user is not None:
 84            existing = UserOffboarding.objects.filter(user=user, status=OffboardingStatus.PENDING)
 85            if self.instance is not None:
 86                existing = existing.exclude(pk=self.instance.pk)
 87            if existing.exists():
 88                raise ValidationError({"user": DUPLICATE_PENDING_ERROR})
 89        return attrs
 90
 91
 92# Offboarding records are immutable: they can be scheduled (POST), cancelled
 93# (DELETE → soft-cancel), and read — but never edited. The update mixins are
 94# deliberately left out so PUT/PATCH cannot rewrite a terminal audit row's
 95# action/schedule/user after the fact.
 96class UserOffboardingViewSet(
 97    CreateModelMixin,
 98    RetrieveModelMixin,
 99    ListModelMixin,
100    DestroyModelMixin,
101    GenericViewSet,
102):
103    queryset = UserOffboarding.objects.select_related("user", "created_by", "rule").all()
104    serializer_class = UserOffboardingSerializer
105    search_fields = ["user__username"]
106    ordering = ["scheduled_at"]
107    ordering_fields = ["scheduled_at", "created_at", "status"]
108    filterset_fields = {
109        "user__uuid": ["exact"],
110        "status": ["exact"],
111        "action": ["exact"],
112        "rule": ["exact", "isnull"],
113        "generated": ["exact"],
114    }
115
116    def perform_create(self, serializer: UserOffboardingSerializer) -> None:
117        # Two concurrent requests can both pass validate()'s duplicate check and
118        # race to insert; the unique constraint rejects the loser. Catch it behind
119        # a savepoint and return the same 400 instead of a 500.
120        try:
121            with transaction.atomic():
122                serializer.save(created_by=self.request.user)
123        except IntegrityError:
124            raise ValidationError({"user": DUPLICATE_PENDING_ERROR}) from None
125
126    def destroy(self, request: Request, *args, **kwargs) -> Response:
127        """Cancel a pending offboarding instead of deleting the record.
128
129        The row is retained (as `CANCELED`) so the offboarding stays visible in
130        the audit history; deletion would erase who scheduled and cancelled it.
131        You cannot cancel an offboarding that targets you.
132        """
133        offboarding: UserOffboarding = self.get_object()
134        if offboarding.user_id == request.user.pk:
135            raise PermissionDenied(_("You cannot cancel your own offboarding."))
136        if not offboarding.cancel():
137            raise ValidationError(_("Only a pending offboarding can be cancelled."))
138        return Response(status=204)
DUPLICATE_PENDING_ERROR = 'This user already has a pending offboarding scheduled.'
class PartialUserExpirationRuleSerializer(authentik.core.api.utils.PassiveSerializer):
26class PartialUserExpirationRuleSerializer(PassiveSerializer):
27    pk = UUIDField(read_only=True)
28    name = CharField(read_only=True)

Base serializer class which doesn't implement create/update methods

pk
name
31class UserOffboardingSerializer(EnterpriseRequiredMixin, ModelSerializer):
32    user_obj = PartialUserSerializer(source="user", read_only=True)
33    created_by_obj = PartialUserSerializer(source="created_by", read_only=True)
34    rule_obj = PartialUserExpirationRuleSerializer(source="rule", read_only=True)
35
36    class Meta:
37        model = UserOffboarding
38        fields = [
39            "id",
40            "user",
41            "user_obj",
42            "scheduled_at",
43            "action",
44            "revoke_sessions",
45            "revoke_tokens",
46            "status",
47            "created_by_obj",
48            "created_at",
49            "executed_at",
50            "rule",
51            "rule_obj",
52            "generated",
53        ]
54        read_only_fields = [
55            "id",
56            "user_obj",
57            "status",
58            "created_by_obj",
59            "created_at",
60            "executed_at",
61            "rule",
62            "rule_obj",
63            "generated",
64        ]
65
66    def validate_scheduled_at(self, value):
67        if value <= now():
68            raise ValidationError(_("Offboarding must be scheduled in the future."))
69        return value
70
71    def validate_user(self, user: User) -> User:
72        if user.type == UserTypes.INTERNAL_SERVICE_ACCOUNT:
73            raise ValidationError(_("Internal service accounts cannot be offboarded."))
74        request = self.context.get("request")
75        if request is not None and user.pk == request.user.pk:
76            raise ValidationError(_("You cannot offboard your own account."))
77        return user
78
79    def validate(self, attrs: dict) -> dict:
80        attrs = super().validate(attrs)
81        # Enforce a single pending offboarding per user (mirrors the DB constraint
82        # but returns a friendly error instead of an IntegrityError).
83        user = attrs.get("user", getattr(self.instance, "user", None))
84        if user is not None:
85            existing = UserOffboarding.objects.filter(user=user, status=OffboardingStatus.PENDING)
86            if self.instance is not None:
87                existing = existing.exclude(pk=self.instance.pk)
88            if existing.exists():
89                raise ValidationError({"user": DUPLICATE_PENDING_ERROR})
90        return attrs

Mixin to validate that a valid enterprise license exists before allowing to save the object

user_obj
created_by_obj
rule_obj
def validate_scheduled_at(self, value):
66    def validate_scheduled_at(self, value):
67        if value <= now():
68            raise ValidationError(_("Offboarding must be scheduled in the future."))
69        return value
def validate_user(self, user: authentik.core.models.User) -> authentik.core.models.User:
71    def validate_user(self, user: User) -> User:
72        if user.type == UserTypes.INTERNAL_SERVICE_ACCOUNT:
73            raise ValidationError(_("Internal service accounts cannot be offboarded."))
74        request = self.context.get("request")
75        if request is not None and user.pk == request.user.pk:
76            raise ValidationError(_("You cannot offboard your own account."))
77        return user
def validate(self, attrs: dict) -> dict:
79    def validate(self, attrs: dict) -> dict:
80        attrs = super().validate(attrs)
81        # Enforce a single pending offboarding per user (mirrors the DB constraint
82        # but returns a friendly error instead of an IntegrityError).
83        user = attrs.get("user", getattr(self.instance, "user", None))
84        if user is not None:
85            existing = UserOffboarding.objects.filter(user=user, status=OffboardingStatus.PENDING)
86            if self.instance is not None:
87                existing = existing.exclude(pk=self.instance.pk)
88            if existing.exists():
89                raise ValidationError({"user": DUPLICATE_PENDING_ERROR})
90        return attrs

Check that a valid license exists

class UserOffboardingSerializer.Meta:
36    class Meta:
37        model = UserOffboarding
38        fields = [
39            "id",
40            "user",
41            "user_obj",
42            "scheduled_at",
43            "action",
44            "revoke_sessions",
45            "revoke_tokens",
46            "status",
47            "created_by_obj",
48            "created_at",
49            "executed_at",
50            "rule",
51            "rule_obj",
52            "generated",
53        ]
54        read_only_fields = [
55            "id",
56            "user_obj",
57            "status",
58            "created_by_obj",
59            "created_at",
60            "executed_at",
61            "rule",
62            "rule_obj",
63            "generated",
64        ]
fields = ['id', 'user', 'user_obj', 'scheduled_at', 'action', 'revoke_sessions', 'revoke_tokens', 'status', 'created_by_obj', 'created_at', 'executed_at', 'rule', 'rule_obj', 'generated']
read_only_fields = ['id', 'user_obj', 'status', 'created_by_obj', 'created_at', 'executed_at', 'rule', 'rule_obj', 'generated']
class UserOffboardingViewSet(rest_framework.mixins.CreateModelMixin, rest_framework.mixins.RetrieveModelMixin, rest_framework.mixins.ListModelMixin, rest_framework.mixins.DestroyModelMixin, rest_framework.viewsets.GenericViewSet):
 97class UserOffboardingViewSet(
 98    CreateModelMixin,
 99    RetrieveModelMixin,
100    ListModelMixin,
101    DestroyModelMixin,
102    GenericViewSet,
103):
104    queryset = UserOffboarding.objects.select_related("user", "created_by", "rule").all()
105    serializer_class = UserOffboardingSerializer
106    search_fields = ["user__username"]
107    ordering = ["scheduled_at"]
108    ordering_fields = ["scheduled_at", "created_at", "status"]
109    filterset_fields = {
110        "user__uuid": ["exact"],
111        "status": ["exact"],
112        "action": ["exact"],
113        "rule": ["exact", "isnull"],
114        "generated": ["exact"],
115    }
116
117    def perform_create(self, serializer: UserOffboardingSerializer) -> None:
118        # Two concurrent requests can both pass validate()'s duplicate check and
119        # race to insert; the unique constraint rejects the loser. Catch it behind
120        # a savepoint and return the same 400 instead of a 500.
121        try:
122            with transaction.atomic():
123                serializer.save(created_by=self.request.user)
124        except IntegrityError:
125            raise ValidationError({"user": DUPLICATE_PENDING_ERROR}) from None
126
127    def destroy(self, request: Request, *args, **kwargs) -> Response:
128        """Cancel a pending offboarding instead of deleting the record.
129
130        The row is retained (as `CANCELED`) so the offboarding stays visible in
131        the audit history; deletion would erase who scheduled and cancelled it.
132        You cannot cancel an offboarding that targets you.
133        """
134        offboarding: UserOffboarding = self.get_object()
135        if offboarding.user_id == request.user.pk:
136            raise PermissionDenied(_("You cannot cancel your own offboarding."))
137        if not offboarding.cancel():
138            raise ValidationError(_("Only a pending offboarding can be cancelled."))
139        return Response(status=204)

Create a model instance.

queryset = <QuerySet []>
serializer_class = <class 'UserOffboardingSerializer'>
search_fields = ['user__username']
ordering = ['scheduled_at']
ordering_fields = ['scheduled_at', 'created_at', 'status']
filterset_fields = {'user__uuid': ['exact'], 'status': ['exact'], 'action': ['exact'], 'rule': ['exact', 'isnull'], 'generated': ['exact']}
def perform_create( self, serializer: UserOffboardingSerializer) -> None:
117    def perform_create(self, serializer: UserOffboardingSerializer) -> None:
118        # Two concurrent requests can both pass validate()'s duplicate check and
119        # race to insert; the unique constraint rejects the loser. Catch it behind
120        # a savepoint and return the same 400 instead of a 500.
121        try:
122            with transaction.atomic():
123                serializer.save(created_by=self.request.user)
124        except IntegrityError:
125            raise ValidationError({"user": DUPLICATE_PENDING_ERROR}) from None
def destroy( self, request: rest_framework.request.Request, *args, **kwargs) -> rest_framework.response.Response:
127    def destroy(self, request: Request, *args, **kwargs) -> Response:
128        """Cancel a pending offboarding instead of deleting the record.
129
130        The row is retained (as `CANCELED`) so the offboarding stays visible in
131        the audit history; deletion would erase who scheduled and cancelled it.
132        You cannot cancel an offboarding that targets you.
133        """
134        offboarding: UserOffboarding = self.get_object()
135        if offboarding.user_id == request.user.pk:
136            raise PermissionDenied(_("You cannot cancel your own offboarding."))
137        if not offboarding.cancel():
138            raise ValidationError(_("Only a pending offboarding can be cancelled."))
139        return Response(status=204)

Cancel a pending offboarding instead of deleting the record.

The row is retained (as CANCELED) so the offboarding stays visible in the audit history; deletion would erase who scheduled and cancelled it. You cannot cancel an offboarding that targets you.

name = None
description = None
suffix = None
detail = None
basename = None