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