authentik.enterprise.lifecycle.expiration.api
1from copy import copy 2from datetime import timedelta 3from uuid import UUID 4 5from django.db import transaction 6from django.utils.translation import gettext as _ 7from drf_spectacular.utils import extend_schema 8from rest_framework.decorators import action 9from rest_framework.exceptions import ValidationError 10from rest_framework.fields import ( 11 BooleanField, 12 CharField, 13 ChoiceField, 14 DateTimeField, 15 IntegerField, 16 UUIDField, 17) 18from rest_framework.permissions import IsAuthenticated 19from rest_framework.request import Request 20from rest_framework.response import Response 21from rest_framework.viewsets import ModelViewSet 22 23from authentik.core.api.used_by import UsedByMixin 24from authentik.core.api.utils import ModelSerializer, PassiveSerializer 25from authentik.core.models import UserTypes 26from authentik.enterprise.api import EnterpriseRequiredMixin 27from authentik.enterprise.lifecycle.expiration.models import PendingChange, UserExpirationRule 28from authentik.enterprise.lifecycle.offboarding.models import OffboardingAction 29from authentik.lib.utils.time import timedelta_from_string 30from authentik.rbac.decorators import permission_required 31 32PREVIEW_LIMIT = 20 33 34 35class UserExpirationRuleUserSerializer(PassiveSerializer): 36 pk = IntegerField(read_only=True) 37 username = CharField(read_only=True) 38 name = CharField(read_only=True) 39 40 41class UserExpirationRuleGroupSerializer(PassiveSerializer): 42 pk = UUIDField(read_only=True) 43 name = CharField(read_only=True) 44 45 46class UserExpirationRuleSerializer(EnterpriseRequiredMixin, ModelSerializer): 47 group_obj = UserExpirationRuleGroupSerializer(source="group", read_only=True) 48 49 class Meta: 50 model = UserExpirationRule 51 fields = [ 52 "pk", 53 "pbm_uuid", 54 "name", 55 "enabled", 56 "activity_basis", 57 "group", 58 "group_obj", 59 "user_types", 60 "inactivity_duration", 61 "action", 62 "revoke_sessions", 63 "revoke_tokens", 64 "warn_before", 65 "notification_transports", 66 "exclude_superusers", 67 "policy_engine_mode", 68 ] 69 70 def validate_user_types(self, value: list[str]) -> list[str]: 71 if not value: 72 raise ValidationError(_("Select at least one user type.")) 73 if UserTypes.INTERNAL_SERVICE_ACCOUNT in value: 74 raise ValidationError(_("Internal service accounts cannot be expired.")) 75 return value 76 77 def validate_inactivity_duration(self, value: str) -> str: 78 if timedelta_from_string(value) <= timedelta(): 79 raise ValidationError(_("Inactivity duration must be positive.")) 80 return value 81 82 def validate_warn_before(self, value: str | None) -> str | None: 83 if value and timedelta_from_string(value) <= timedelta(): 84 raise ValidationError(_("Warning period must be positive.")) 85 return value or None 86 87 def validate(self, attrs: dict) -> dict: 88 attrs = super().validate(attrs) 89 duration = attrs.get( 90 "inactivity_duration", 91 getattr( 92 self.instance, 93 "inactivity_duration", 94 UserExpirationRule._meta.get_field("inactivity_duration").get_default(), 95 ), 96 ) 97 warn_before = attrs.get("warn_before", getattr(self.instance, "warn_before", None)) 98 transports = attrs.get("notification_transports") 99 if transports is None and self.instance is not None: 100 transports = self.instance.notification_transports.exists() 101 if not warn_before and transports: 102 raise ValidationError( 103 {"notification_transports": _("A warning period is required for notifications.")} 104 ) 105 if ( 106 duration 107 and warn_before 108 and timedelta_from_string(warn_before) >= timedelta_from_string(duration) 109 ): 110 raise ValidationError( 111 {"warn_before": _("Warning period must be shorter than the inactivity duration.")} 112 ) 113 return attrs 114 115 # Save the rule and its transports in one transaction, so the sweep queued on 116 # commit sees both. 117 def create(self, validated_data: dict) -> UserExpirationRule: 118 with transaction.atomic(): 119 return super().create(validated_data) 120 121 def update(self, instance: UserExpirationRule, validated_data: dict) -> UserExpirationRule: 122 with transaction.atomic(): 123 return super().update(instance, validated_data) 124 125 126class UserExpirationRulePendingPreviewSerializer(PassiveSerializer): 127 id = UUIDField(read_only=True) 128 user = UserExpirationRuleUserSerializer(read_only=True) 129 previous_action = ChoiceField(choices=OffboardingAction.choices, read_only=True) 130 action = ChoiceField(choices=OffboardingAction.choices, allow_null=True, read_only=True) 131 previous_scheduled_at = DateTimeField(read_only=True) 132 scheduled_at = DateTimeField(allow_null=True, read_only=True) 133 previous_revoke_sessions = BooleanField(read_only=True) 134 revoke_sessions = BooleanField(allow_null=True, read_only=True) 135 previous_revoke_tokens = BooleanField(read_only=True) 136 revoke_tokens = BooleanField(allow_null=True, read_only=True) 137 138 139class UserExpirationRulePendingPreviewGroupSerializer(PassiveSerializer): 140 count = IntegerField(read_only=True) 141 offboardings = UserExpirationRulePendingPreviewSerializer(many=True, read_only=True) 142 143 144class UserExpirationRulePreviewSerializer(PassiveSerializer): 145 count = IntegerField(read_only=True) 146 users = UserExpirationRuleUserSerializer(many=True, read_only=True) 147 updated = UserExpirationRulePendingPreviewGroupSerializer(read_only=True) 148 taken_over = UserExpirationRulePendingPreviewGroupSerializer(read_only=True) 149 removed = UserExpirationRulePendingPreviewGroupSerializer(read_only=True) 150 151 152class UserExpirationRuleViewSet(UsedByMixin, ModelViewSet): 153 queryset = UserExpirationRule.objects.select_related("group").all() 154 serializer_class = UserExpirationRuleSerializer 155 search_fields = ["name"] 156 ordering = ["name"] 157 ordering_fields = ["name", "enabled", "action"] 158 filterset_fields = ["enabled", "group", "action", "pbm_uuid"] 159 160 @extend_schema( 161 request=UserExpirationRuleSerializer, 162 responses={200: UserExpirationRulePreviewSerializer}, 163 ) 164 @permission_required( 165 "authentik_lifecycle.view_userexpirationrule", ["authentik_core.view_user"] 166 ) 167 @action( 168 detail=True, 169 methods=["GET", "POST"], 170 pagination_class=None, 171 filter_backends=[], 172 permission_classes=[IsAuthenticated], 173 ) 174 def preview(self, request: Request, pk: str) -> Response: 175 """Preview new offboardings and changes to pending rows if this rule is enabled. 176 177 POST accepts unsaved edits to the rule. Neither method saves the rule, changes 178 offboardings, or sends warnings. Existing policy bindings still apply. 179 """ 180 rule: UserExpirationRule = copy(self.get_object()) 181 if request.method == "POST": 182 serializer = self.get_serializer(rule, data=request.data, partial=True) 183 serializer.is_valid(raise_exception=True) 184 for field, value in serializer.validated_data.items(): 185 if field not in ("pk", "id", "pbm_uuid", "notification_transports"): 186 setattr(rule, field, value) 187 rule.enabled = True 188 counts = {change: 0 for change in PendingChange} 189 offboardings: dict[PendingChange, list[dict]] = {change: [] for change in PendingChange} 190 withdrawn: list[UUID] = [] 191 for change, row, due_at in rule.preview_pending(): 192 counts[change] += 1 193 if change == PendingChange.REMOVED: 194 withdrawn.append(row.pk) 195 if len(offboardings[change]) >= PREVIEW_LIMIT: 196 continue 197 offboardings[change].append( 198 { 199 "id": row.pk, 200 "user": row.user, 201 "previous_action": row.action, 202 "action": rule.action if due_at is not None else None, 203 "previous_scheduled_at": row.scheduled_at, 204 "scheduled_at": due_at, 205 "previous_revoke_sessions": row.revoke_sessions, 206 "revoke_sessions": rule.revoke_sessions if due_at is not None else None, 207 "previous_revoke_tokens": row.revoke_tokens, 208 "revoke_tokens": rule.revoke_tokens if due_at is not None else None, 209 } 210 ) 211 # Like the sweep, withdrawn users can be scheduled again. 212 candidates = rule.candidates(withdrawn=withdrawn).order_by("username") 213 data: dict[str, object] = { 214 "count": candidates.count(), 215 "users": UserExpirationRuleUserSerializer(candidates[:PREVIEW_LIMIT], many=True).data, 216 } 217 data.update( 218 { 219 change: {"count": count, "offboardings": offboardings[change]} 220 for change, count in counts.items() 221 } 222 ) 223 return Response(UserExpirationRulePreviewSerializer(data).data)
36class UserExpirationRuleUserSerializer(PassiveSerializer): 37 pk = IntegerField(read_only=True) 38 username = CharField(read_only=True) 39 name = CharField(read_only=True)
Base serializer class which doesn't implement create/update methods
Inherited Members
42class UserExpirationRuleGroupSerializer(PassiveSerializer): 43 pk = UUIDField(read_only=True) 44 name = CharField(read_only=True)
Base serializer class which doesn't implement create/update methods
Inherited Members
47class UserExpirationRuleSerializer(EnterpriseRequiredMixin, ModelSerializer): 48 group_obj = UserExpirationRuleGroupSerializer(source="group", read_only=True) 49 50 class Meta: 51 model = UserExpirationRule 52 fields = [ 53 "pk", 54 "pbm_uuid", 55 "name", 56 "enabled", 57 "activity_basis", 58 "group", 59 "group_obj", 60 "user_types", 61 "inactivity_duration", 62 "action", 63 "revoke_sessions", 64 "revoke_tokens", 65 "warn_before", 66 "notification_transports", 67 "exclude_superusers", 68 "policy_engine_mode", 69 ] 70 71 def validate_user_types(self, value: list[str]) -> list[str]: 72 if not value: 73 raise ValidationError(_("Select at least one user type.")) 74 if UserTypes.INTERNAL_SERVICE_ACCOUNT in value: 75 raise ValidationError(_("Internal service accounts cannot be expired.")) 76 return value 77 78 def validate_inactivity_duration(self, value: str) -> str: 79 if timedelta_from_string(value) <= timedelta(): 80 raise ValidationError(_("Inactivity duration must be positive.")) 81 return value 82 83 def validate_warn_before(self, value: str | None) -> str | None: 84 if value and timedelta_from_string(value) <= timedelta(): 85 raise ValidationError(_("Warning period must be positive.")) 86 return value or None 87 88 def validate(self, attrs: dict) -> dict: 89 attrs = super().validate(attrs) 90 duration = attrs.get( 91 "inactivity_duration", 92 getattr( 93 self.instance, 94 "inactivity_duration", 95 UserExpirationRule._meta.get_field("inactivity_duration").get_default(), 96 ), 97 ) 98 warn_before = attrs.get("warn_before", getattr(self.instance, "warn_before", None)) 99 transports = attrs.get("notification_transports") 100 if transports is None and self.instance is not None: 101 transports = self.instance.notification_transports.exists() 102 if not warn_before and transports: 103 raise ValidationError( 104 {"notification_transports": _("A warning period is required for notifications.")} 105 ) 106 if ( 107 duration 108 and warn_before 109 and timedelta_from_string(warn_before) >= timedelta_from_string(duration) 110 ): 111 raise ValidationError( 112 {"warn_before": _("Warning period must be shorter than the inactivity duration.")} 113 ) 114 return attrs 115 116 # Save the rule and its transports in one transaction, so the sweep queued on 117 # commit sees both. 118 def create(self, validated_data: dict) -> UserExpirationRule: 119 with transaction.atomic(): 120 return super().create(validated_data) 121 122 def update(self, instance: UserExpirationRule, validated_data: dict) -> UserExpirationRule: 123 with transaction.atomic(): 124 return super().update(instance, validated_data)
Mixin to validate that a valid enterprise license exists before allowing to save the object
88 def validate(self, attrs: dict) -> dict: 89 attrs = super().validate(attrs) 90 duration = attrs.get( 91 "inactivity_duration", 92 getattr( 93 self.instance, 94 "inactivity_duration", 95 UserExpirationRule._meta.get_field("inactivity_duration").get_default(), 96 ), 97 ) 98 warn_before = attrs.get("warn_before", getattr(self.instance, "warn_before", None)) 99 transports = attrs.get("notification_transports") 100 if transports is None and self.instance is not None: 101 transports = self.instance.notification_transports.exists() 102 if not warn_before and transports: 103 raise ValidationError( 104 {"notification_transports": _("A warning period is required for notifications.")} 105 ) 106 if ( 107 duration 108 and warn_before 109 and timedelta_from_string(warn_before) >= timedelta_from_string(duration) 110 ): 111 raise ValidationError( 112 {"warn_before": _("Warning period must be shorter than the inactivity duration.")} 113 ) 114 return attrs
Check that a valid license exists
118 def create(self, validated_data: dict) -> UserExpirationRule: 119 with transaction.atomic(): 120 return super().create(validated_data)
We have a bit of extra checking around this in order to provide descriptive messages when something goes wrong, but this method is essentially just:
return ExampleModel.objects.create(**validated_data)
If there are many to many fields present on the instance then they cannot be set until the model is instantiated, in which case the implementation is like so:
example_relationship = validated_data.pop('example_relationship')
instance = ExampleModel.objects.create(**validated_data)
instance.example_relationship = example_relationship
return instance
The default implementation also does not handle nested relationships.
If you want to support writable nested relationships you'll need
to write an explicit .create() method.
50 class Meta: 51 model = UserExpirationRule 52 fields = [ 53 "pk", 54 "pbm_uuid", 55 "name", 56 "enabled", 57 "activity_basis", 58 "group", 59 "group_obj", 60 "user_types", 61 "inactivity_duration", 62 "action", 63 "revoke_sessions", 64 "revoke_tokens", 65 "warn_before", 66 "notification_transports", 67 "exclude_superusers", 68 "policy_engine_mode", 69 ]
127class UserExpirationRulePendingPreviewSerializer(PassiveSerializer): 128 id = UUIDField(read_only=True) 129 user = UserExpirationRuleUserSerializer(read_only=True) 130 previous_action = ChoiceField(choices=OffboardingAction.choices, read_only=True) 131 action = ChoiceField(choices=OffboardingAction.choices, allow_null=True, read_only=True) 132 previous_scheduled_at = DateTimeField(read_only=True) 133 scheduled_at = DateTimeField(allow_null=True, read_only=True) 134 previous_revoke_sessions = BooleanField(read_only=True) 135 revoke_sessions = BooleanField(allow_null=True, read_only=True) 136 previous_revoke_tokens = BooleanField(read_only=True) 137 revoke_tokens = BooleanField(allow_null=True, read_only=True)
Base serializer class which doesn't implement create/update methods
Inherited Members
140class UserExpirationRulePendingPreviewGroupSerializer(PassiveSerializer): 141 count = IntegerField(read_only=True) 142 offboardings = UserExpirationRulePendingPreviewSerializer(many=True, read_only=True)
Base serializer class which doesn't implement create/update methods
Inherited Members
145class UserExpirationRulePreviewSerializer(PassiveSerializer): 146 count = IntegerField(read_only=True) 147 users = UserExpirationRuleUserSerializer(many=True, read_only=True) 148 updated = UserExpirationRulePendingPreviewGroupSerializer(read_only=True) 149 taken_over = UserExpirationRulePendingPreviewGroupSerializer(read_only=True) 150 removed = UserExpirationRulePendingPreviewGroupSerializer(read_only=True)
Base serializer class which doesn't implement create/update methods
Inherited Members
153class UserExpirationRuleViewSet(UsedByMixin, ModelViewSet): 154 queryset = UserExpirationRule.objects.select_related("group").all() 155 serializer_class = UserExpirationRuleSerializer 156 search_fields = ["name"] 157 ordering = ["name"] 158 ordering_fields = ["name", "enabled", "action"] 159 filterset_fields = ["enabled", "group", "action", "pbm_uuid"] 160 161 @extend_schema( 162 request=UserExpirationRuleSerializer, 163 responses={200: UserExpirationRulePreviewSerializer}, 164 ) 165 @permission_required( 166 "authentik_lifecycle.view_userexpirationrule", ["authentik_core.view_user"] 167 ) 168 @action( 169 detail=True, 170 methods=["GET", "POST"], 171 pagination_class=None, 172 filter_backends=[], 173 permission_classes=[IsAuthenticated], 174 ) 175 def preview(self, request: Request, pk: str) -> Response: 176 """Preview new offboardings and changes to pending rows if this rule is enabled. 177 178 POST accepts unsaved edits to the rule. Neither method saves the rule, changes 179 offboardings, or sends warnings. Existing policy bindings still apply. 180 """ 181 rule: UserExpirationRule = copy(self.get_object()) 182 if request.method == "POST": 183 serializer = self.get_serializer(rule, data=request.data, partial=True) 184 serializer.is_valid(raise_exception=True) 185 for field, value in serializer.validated_data.items(): 186 if field not in ("pk", "id", "pbm_uuid", "notification_transports"): 187 setattr(rule, field, value) 188 rule.enabled = True 189 counts = {change: 0 for change in PendingChange} 190 offboardings: dict[PendingChange, list[dict]] = {change: [] for change in PendingChange} 191 withdrawn: list[UUID] = [] 192 for change, row, due_at in rule.preview_pending(): 193 counts[change] += 1 194 if change == PendingChange.REMOVED: 195 withdrawn.append(row.pk) 196 if len(offboardings[change]) >= PREVIEW_LIMIT: 197 continue 198 offboardings[change].append( 199 { 200 "id": row.pk, 201 "user": row.user, 202 "previous_action": row.action, 203 "action": rule.action if due_at is not None else None, 204 "previous_scheduled_at": row.scheduled_at, 205 "scheduled_at": due_at, 206 "previous_revoke_sessions": row.revoke_sessions, 207 "revoke_sessions": rule.revoke_sessions if due_at is not None else None, 208 "previous_revoke_tokens": row.revoke_tokens, 209 "revoke_tokens": rule.revoke_tokens if due_at is not None else None, 210 } 211 ) 212 # Like the sweep, withdrawn users can be scheduled again. 213 candidates = rule.candidates(withdrawn=withdrawn).order_by("username") 214 data: dict[str, object] = { 215 "count": candidates.count(), 216 "users": UserExpirationRuleUserSerializer(candidates[:PREVIEW_LIMIT], many=True).data, 217 } 218 data.update( 219 { 220 change: {"count": count, "offboardings": offboardings[change]} 221 for change, count in counts.items() 222 } 223 ) 224 return Response(UserExpirationRulePreviewSerializer(data).data)
Mixin to add a used_by endpoint to return a list of all objects using this object
161 @extend_schema( 162 request=UserExpirationRuleSerializer, 163 responses={200: UserExpirationRulePreviewSerializer}, 164 ) 165 @permission_required( 166 "authentik_lifecycle.view_userexpirationrule", ["authentik_core.view_user"] 167 ) 168 @action( 169 detail=True, 170 methods=["GET", "POST"], 171 pagination_class=None, 172 filter_backends=[], 173 permission_classes=[IsAuthenticated], 174 ) 175 def preview(self, request: Request, pk: str) -> Response: 176 """Preview new offboardings and changes to pending rows if this rule is enabled. 177 178 POST accepts unsaved edits to the rule. Neither method saves the rule, changes 179 offboardings, or sends warnings. Existing policy bindings still apply. 180 """ 181 rule: UserExpirationRule = copy(self.get_object()) 182 if request.method == "POST": 183 serializer = self.get_serializer(rule, data=request.data, partial=True) 184 serializer.is_valid(raise_exception=True) 185 for field, value in serializer.validated_data.items(): 186 if field not in ("pk", "id", "pbm_uuid", "notification_transports"): 187 setattr(rule, field, value) 188 rule.enabled = True 189 counts = {change: 0 for change in PendingChange} 190 offboardings: dict[PendingChange, list[dict]] = {change: [] for change in PendingChange} 191 withdrawn: list[UUID] = [] 192 for change, row, due_at in rule.preview_pending(): 193 counts[change] += 1 194 if change == PendingChange.REMOVED: 195 withdrawn.append(row.pk) 196 if len(offboardings[change]) >= PREVIEW_LIMIT: 197 continue 198 offboardings[change].append( 199 { 200 "id": row.pk, 201 "user": row.user, 202 "previous_action": row.action, 203 "action": rule.action if due_at is not None else None, 204 "previous_scheduled_at": row.scheduled_at, 205 "scheduled_at": due_at, 206 "previous_revoke_sessions": row.revoke_sessions, 207 "revoke_sessions": rule.revoke_sessions if due_at is not None else None, 208 "previous_revoke_tokens": row.revoke_tokens, 209 "revoke_tokens": rule.revoke_tokens if due_at is not None else None, 210 } 211 ) 212 # Like the sweep, withdrawn users can be scheduled again. 213 candidates = rule.candidates(withdrawn=withdrawn).order_by("username") 214 data: dict[str, object] = { 215 "count": candidates.count(), 216 "users": UserExpirationRuleUserSerializer(candidates[:PREVIEW_LIMIT], many=True).data, 217 } 218 data.update( 219 { 220 change: {"count": count, "offboardings": offboardings[change]} 221 for change, count in counts.items() 222 } 223 ) 224 return Response(UserExpirationRulePreviewSerializer(data).data)
Preview new offboardings and changes to pending rows if this rule is enabled.
POST accepts unsaved edits to the rule. Neither method saves the rule, changes offboardings, or sends warnings. Existing policy bindings still apply.