authentik.enterprise.stages.account_lockdown.stage

Account lockdown stage logic

  1"""Account lockdown stage logic"""
  2
  3from django.db.models import QuerySet
  4from django.db.models.query_utils import Q
  5from django.db.transaction import atomic
  6from django.http import HttpRequest, HttpResponse, HttpResponseRedirect
  7from django.urls import reverse
  8from django.utils.translation import gettext_lazy as _
  9from dramatiq.actor import Actor
 10from dramatiq.composition import group
 11from dramatiq.results.errors import ResultTimeout
 12
 13from authentik.core.models import User, UserTypes
 14from authentik.core.signals import deactivation_inhibit_cleanup
 15from authentik.enterprise.core.revocation import revoke_user_access
 16from authentik.enterprise.stages.account_lockdown.models import AccountLockdownStage
 17from authentik.events.models import Event, EventAction
 18from authentik.flows.stage import StageView
 19from authentik.lib.sync.outgoing.models import OutgoingSyncProvider
 20from authentik.lib.sync.outgoing.signals import sync_outgoing_inhibit_dispatch
 21from authentik.lib.utils.reflection import class_to_path
 22from authentik.lib.utils.time import timedelta_from_string
 23from authentik.stages.password.models import PasswordDevice
 24from authentik.stages.prompt.stage import PLAN_CONTEXT_PROMPT
 25
 26PLAN_CONTEXT_LOCKDOWN_REASON = "lockdown_reason"
 27LOCKDOWN_EVENT_ACTION_ID = "account_lockdown"
 28
 29TARGET_REQUIRED_MESSAGE = _("No target user specified for account lockdown")
 30PERMISSION_DENIED_MESSAGE = _("You do not have permission to lock down this account.")
 31ACCOUNT_LOCKDOWN_FAILED_MESSAGE = _("Account lockdown failed for this account.")
 32SELF_SERVICE_COMPLETION_FLOW_REQUIRED_MESSAGE = _(
 33    "Self-service account lockdown requires a completion flow."
 34)
 35
 36
 37def get_lockdown_target_users() -> QuerySet[User]:
 38    """Return users that can be targeted by account lockdown."""
 39    return User.objects.exclude_anonymous().exclude(type=UserTypes.INTERNAL_SERVICE_ACCOUNT)
 40
 41
 42def can_lock_user(actor, user: User) -> bool:
 43    """Check whether the actor may lock the target user."""
 44    if not actor.is_authenticated:
 45        return False
 46    if user.pk == actor.pk:
 47        return True
 48    return actor.has_perm("authentik_core.change_user", user)
 49
 50
 51def get_outgoing_sync_tasks() -> tuple[tuple[type[OutgoingSyncProvider], Actor], ...]:
 52    """Return outgoing sync provider types and their direct sync tasks."""
 53    from authentik.enterprise.providers.google_workspace.models import GoogleWorkspaceProvider
 54    from authentik.enterprise.providers.google_workspace.tasks import google_workspace_sync_direct
 55    from authentik.enterprise.providers.microsoft_entra.models import MicrosoftEntraProvider
 56    from authentik.enterprise.providers.microsoft_entra.tasks import microsoft_entra_sync_direct
 57    from authentik.providers.scim.models import SCIMProvider
 58    from authentik.providers.scim.tasks import scim_sync_direct
 59
 60    return (
 61        (SCIMProvider, scim_sync_direct),
 62        (GoogleWorkspaceProvider, google_workspace_sync_direct),
 63        (MicrosoftEntraProvider, microsoft_entra_sync_direct),
 64    )
 65
 66
 67class AccountLockdownStageView(StageView):
 68    """Execute account lockdown actions on the target user."""
 69
 70    def is_self_service(self, request: HttpRequest, user: User) -> bool:
 71        """Check whether the currently authenticated user is locking their own account."""
 72        return request.user.is_authenticated and user.pk == request.user.pk
 73
 74    def get_reason(self) -> str:
 75        """Get the lockdown reason from the plan context.
 76
 77        Priority:
 78        1. prompt_data[PLAN_CONTEXT_LOCKDOWN_REASON]
 79        2. PLAN_CONTEXT_LOCKDOWN_REASON (explicitly set)
 80        3. Empty string as fallback
 81        """
 82        prompt_data = self.executor.plan.context.get(PLAN_CONTEXT_PROMPT, {})
 83        if PLAN_CONTEXT_LOCKDOWN_REASON in prompt_data:
 84            return prompt_data[PLAN_CONTEXT_LOCKDOWN_REASON]
 85        return self.executor.plan.context.get(PLAN_CONTEXT_LOCKDOWN_REASON, "")
 86
 87    def _apply_lockdown_actions(self, stage: AccountLockdownStage, user: User) -> None:
 88        """Apply the configured account changes to the target user."""
 89        if not stage.deactivate_user:
 90            if stage.set_unusable_password:
 91                PasswordDevice.set_unusable_password(user)
 92            return
 93        # Removing the password saves the user too, so it also needs the inhibitors.
 94        with (
 95            sync_outgoing_inhibit_dispatch(),
 96            deactivation_inhibit_cleanup(
 97                sessions=not stage.delete_sessions, tokens=not stage.revoke_tokens
 98            ),
 99        ):
100            if stage.set_unusable_password:
101                PasswordDevice.set_unusable_password(user)
102            user.is_active = False
103            user.save()
104
105    def _sync_deactivated_user_to_outgoing_providers(self, user: User) -> None:
106        """Synchronize a deactivated user to outgoing sync providers."""
107        messages = []
108        wait_timeout = 0
109        model = class_to_path(User)
110        provider_filter = Q(backchannel_application__isnull=False) | Q(application__isnull=False)
111
112        for provider_model, task_sync_direct in get_outgoing_sync_tasks():
113            for provider in provider_model.objects.filter(provider_filter):
114                time_limit = int(
115                    timedelta_from_string(provider.sync_page_timeout).total_seconds() * 1000
116                )
117                messages.append(
118                    task_sync_direct.message_with_options(
119                        args=(model, user.pk, provider.pk),
120                        rel_obj=provider,
121                        time_limit=time_limit,
122                        uid=f"{provider.name}:user:{user.pk}:direct",
123                    )
124                )
125                wait_timeout += time_limit
126
127        if not messages:
128            return
129        try:
130            group(messages).run().wait(timeout=wait_timeout)
131        except ResultTimeout:
132            self.logger.warning(
133                "Timed out waiting for outgoing sync tasks; tasks remain queued",
134                user=user.username,
135                timeout=wait_timeout,
136            )
137
138    def _emit_lockdown_event(self, request: HttpRequest, user: User, reason: str) -> None:
139        """Emit the audit event for a completed lockdown."""
140        # Emit the audit event after the transaction commits. If event creation
141        # fails here, dispatch() would otherwise treat the whole lockdown as
142        # failed even though the account changes have already been committed.
143        try:
144            Event.new(
145                EventAction.USER_WRITE,
146                action_id=LOCKDOWN_EVENT_ACTION_ID,
147                reason=reason,
148                affected_user=user.username,
149            ).from_http(request)
150        except Exception as exc:  # noqa: BLE001
151            # Event emission should not make the lockdown itself fail.
152            self.logger.warning(
153                "Failed to emit account lockdown event",
154                user=user.username,
155                exc=exc,
156            )
157
158    def _lockdown_user(
159        self,
160        request: HttpRequest,
161        stage: AccountLockdownStage,
162        user: User,
163        reason: str,
164    ) -> None:
165        """Execute lockdown actions on a single user."""
166        with atomic():
167            user = User.objects.get(pk=user.pk)
168            self._apply_lockdown_actions(stage, user)
169
170        # Deactivation is committed above before revoking, so the retry loop
171        # inside revoke_user_access closes the timing-attack window where a
172        # credential is minted with a token being deleted.
173        revoke_user_access(user, sessions=stage.delete_sessions, tokens=stage.revoke_tokens)
174
175        if stage.deactivate_user:
176            try:
177                self._sync_deactivated_user_to_outgoing_providers(user)
178            except Exception as exc:  # noqa: BLE001
179                # Local lockdown has already committed. Provider sync failures
180                # must not reopen access or mark the lockdown itself as failed.
181                self.logger.warning(
182                    "Failed to sync account lockdown deactivation to outgoing providers",
183                    user=user.username,
184                    exc=exc,
185                )
186        self._emit_lockdown_event(request, user, reason)
187
188    def dispatch(self, request: HttpRequest) -> HttpResponse:
189        """Execute account lockdown actions."""
190        self.request = request
191        stage: AccountLockdownStage = self.executor.current_stage
192
193        pending_user = self.get_pending_user()
194        if not pending_user.is_authenticated:
195            self.logger.warning("No target user found for account lockdown")
196            return self.executor.stage_invalid(TARGET_REQUIRED_MESSAGE)
197        user = get_lockdown_target_users().filter(pk=pending_user.pk).first()
198        if user is None:
199            self.logger.warning("Target user is not eligible for account lockdown")
200            return self.executor.stage_invalid(TARGET_REQUIRED_MESSAGE)
201        if not can_lock_user(request.user, user):
202            self.logger.warning(
203                "Permission denied for account lockdown",
204                actor=getattr(request.user, "username", None),
205                target=user.username,
206            )
207            return self.executor.stage_invalid(PERMISSION_DENIED_MESSAGE)
208
209        reason = self.get_reason()
210        self_service = self.is_self_service(request, user)
211        if self_service and stage.delete_sessions and not stage.self_service_completion_flow:
212            self.logger.warning("No completion flow configured for self-service account lockdown")
213            return self.executor.stage_invalid(SELF_SERVICE_COMPLETION_FLOW_REQUIRED_MESSAGE)
214
215        self.logger.info(
216            "Executing account lockdown",
217            user=user.username,
218            reason=reason,
219            self_service=self_service,
220            deactivate_user=stage.deactivate_user,
221            set_unusable_password=stage.set_unusable_password,
222            delete_sessions=stage.delete_sessions,
223            revoke_tokens=stage.revoke_tokens,
224        )
225
226        try:
227            self._lockdown_user(request, stage, user, reason)
228            self.logger.info("Account lockdown completed", user=user.username)
229        except Exception as exc:  # noqa: BLE001
230            # Convert unexpected lockdown errors to a flow-stage failure instead
231            # of leaking an exception through the flow executor.
232            self.logger.warning("Account lockdown failed", user=user.username, exc=exc)
233            return self.executor.stage_invalid(ACCOUNT_LOCKDOWN_FAILED_MESSAGE)
234
235        if self_service:
236            if stage.delete_sessions:
237                return self._self_service_completion_response(request)
238            return self.executor.stage_ok()
239
240        return self.executor.stage_ok()
241
242    def _self_service_completion_response(self, request: HttpRequest) -> HttpResponse:
243        """Redirect to completion flow after self-service lockdown.
244
245        Since all sessions are deleted, the user cannot continue in the flow.
246        Redirect them to an unauthenticated completion flow that shows the
247        lockdown message.
248
249        We use a direct HTTP redirect instead of a challenge because the
250        flow executor's challenge handling may try to access the session
251        which we just deleted.
252        """
253        stage: AccountLockdownStage = self.executor.current_stage
254        completion_flow = stage.self_service_completion_flow
255        if completion_flow:
256            # Flush the current request's session to prevent Django's session
257            # middleware from trying to save a deleted session
258            if hasattr(request, "session"):
259                request.session.flush()
260            redirect_to = reverse(
261                "authentik_core:if-flow",
262                kwargs={"flow_slug": completion_flow.slug},
263            )
264            return HttpResponseRedirect(redirect_to)
265        return self.executor.stage_invalid(SELF_SERVICE_COMPLETION_FLOW_REQUIRED_MESSAGE)
PLAN_CONTEXT_LOCKDOWN_REASON = 'lockdown_reason'
LOCKDOWN_EVENT_ACTION_ID = 'account_lockdown'
TARGET_REQUIRED_MESSAGE = 'No target user specified for account lockdown'
PERMISSION_DENIED_MESSAGE = 'You do not have permission to lock down this account.'
ACCOUNT_LOCKDOWN_FAILED_MESSAGE = 'Account lockdown failed for this account.'
SELF_SERVICE_COMPLETION_FLOW_REQUIRED_MESSAGE = 'Self-service account lockdown requires a completion flow.'
def get_lockdown_target_users() -> django.db.models.query.QuerySet:
38def get_lockdown_target_users() -> QuerySet[User]:
39    """Return users that can be targeted by account lockdown."""
40    return User.objects.exclude_anonymous().exclude(type=UserTypes.INTERNAL_SERVICE_ACCOUNT)

Return users that can be targeted by account lockdown.

def can_lock_user(actor, user: authentik.core.models.User) -> bool:
43def can_lock_user(actor, user: User) -> bool:
44    """Check whether the actor may lock the target user."""
45    if not actor.is_authenticated:
46        return False
47    if user.pk == actor.pk:
48        return True
49    return actor.has_perm("authentik_core.change_user", user)

Check whether the actor may lock the target user.

def get_outgoing_sync_tasks() -> tuple[tuple[type[authentik.lib.sync.outgoing.models.OutgoingSyncProvider], dramatiq.actor.Actor], ...]:
52def get_outgoing_sync_tasks() -> tuple[tuple[type[OutgoingSyncProvider], Actor], ...]:
53    """Return outgoing sync provider types and their direct sync tasks."""
54    from authentik.enterprise.providers.google_workspace.models import GoogleWorkspaceProvider
55    from authentik.enterprise.providers.google_workspace.tasks import google_workspace_sync_direct
56    from authentik.enterprise.providers.microsoft_entra.models import MicrosoftEntraProvider
57    from authentik.enterprise.providers.microsoft_entra.tasks import microsoft_entra_sync_direct
58    from authentik.providers.scim.models import SCIMProvider
59    from authentik.providers.scim.tasks import scim_sync_direct
60
61    return (
62        (SCIMProvider, scim_sync_direct),
63        (GoogleWorkspaceProvider, google_workspace_sync_direct),
64        (MicrosoftEntraProvider, microsoft_entra_sync_direct),
65    )

Return outgoing sync provider types and their direct sync tasks.

class AccountLockdownStageView(authentik.flows.stage.StageView):
 68class AccountLockdownStageView(StageView):
 69    """Execute account lockdown actions on the target user."""
 70
 71    def is_self_service(self, request: HttpRequest, user: User) -> bool:
 72        """Check whether the currently authenticated user is locking their own account."""
 73        return request.user.is_authenticated and user.pk == request.user.pk
 74
 75    def get_reason(self) -> str:
 76        """Get the lockdown reason from the plan context.
 77
 78        Priority:
 79        1. prompt_data[PLAN_CONTEXT_LOCKDOWN_REASON]
 80        2. PLAN_CONTEXT_LOCKDOWN_REASON (explicitly set)
 81        3. Empty string as fallback
 82        """
 83        prompt_data = self.executor.plan.context.get(PLAN_CONTEXT_PROMPT, {})
 84        if PLAN_CONTEXT_LOCKDOWN_REASON in prompt_data:
 85            return prompt_data[PLAN_CONTEXT_LOCKDOWN_REASON]
 86        return self.executor.plan.context.get(PLAN_CONTEXT_LOCKDOWN_REASON, "")
 87
 88    def _apply_lockdown_actions(self, stage: AccountLockdownStage, user: User) -> None:
 89        """Apply the configured account changes to the target user."""
 90        if not stage.deactivate_user:
 91            if stage.set_unusable_password:
 92                PasswordDevice.set_unusable_password(user)
 93            return
 94        # Removing the password saves the user too, so it also needs the inhibitors.
 95        with (
 96            sync_outgoing_inhibit_dispatch(),
 97            deactivation_inhibit_cleanup(
 98                sessions=not stage.delete_sessions, tokens=not stage.revoke_tokens
 99            ),
100        ):
101            if stage.set_unusable_password:
102                PasswordDevice.set_unusable_password(user)
103            user.is_active = False
104            user.save()
105
106    def _sync_deactivated_user_to_outgoing_providers(self, user: User) -> None:
107        """Synchronize a deactivated user to outgoing sync providers."""
108        messages = []
109        wait_timeout = 0
110        model = class_to_path(User)
111        provider_filter = Q(backchannel_application__isnull=False) | Q(application__isnull=False)
112
113        for provider_model, task_sync_direct in get_outgoing_sync_tasks():
114            for provider in provider_model.objects.filter(provider_filter):
115                time_limit = int(
116                    timedelta_from_string(provider.sync_page_timeout).total_seconds() * 1000
117                )
118                messages.append(
119                    task_sync_direct.message_with_options(
120                        args=(model, user.pk, provider.pk),
121                        rel_obj=provider,
122                        time_limit=time_limit,
123                        uid=f"{provider.name}:user:{user.pk}:direct",
124                    )
125                )
126                wait_timeout += time_limit
127
128        if not messages:
129            return
130        try:
131            group(messages).run().wait(timeout=wait_timeout)
132        except ResultTimeout:
133            self.logger.warning(
134                "Timed out waiting for outgoing sync tasks; tasks remain queued",
135                user=user.username,
136                timeout=wait_timeout,
137            )
138
139    def _emit_lockdown_event(self, request: HttpRequest, user: User, reason: str) -> None:
140        """Emit the audit event for a completed lockdown."""
141        # Emit the audit event after the transaction commits. If event creation
142        # fails here, dispatch() would otherwise treat the whole lockdown as
143        # failed even though the account changes have already been committed.
144        try:
145            Event.new(
146                EventAction.USER_WRITE,
147                action_id=LOCKDOWN_EVENT_ACTION_ID,
148                reason=reason,
149                affected_user=user.username,
150            ).from_http(request)
151        except Exception as exc:  # noqa: BLE001
152            # Event emission should not make the lockdown itself fail.
153            self.logger.warning(
154                "Failed to emit account lockdown event",
155                user=user.username,
156                exc=exc,
157            )
158
159    def _lockdown_user(
160        self,
161        request: HttpRequest,
162        stage: AccountLockdownStage,
163        user: User,
164        reason: str,
165    ) -> None:
166        """Execute lockdown actions on a single user."""
167        with atomic():
168            user = User.objects.get(pk=user.pk)
169            self._apply_lockdown_actions(stage, user)
170
171        # Deactivation is committed above before revoking, so the retry loop
172        # inside revoke_user_access closes the timing-attack window where a
173        # credential is minted with a token being deleted.
174        revoke_user_access(user, sessions=stage.delete_sessions, tokens=stage.revoke_tokens)
175
176        if stage.deactivate_user:
177            try:
178                self._sync_deactivated_user_to_outgoing_providers(user)
179            except Exception as exc:  # noqa: BLE001
180                # Local lockdown has already committed. Provider sync failures
181                # must not reopen access or mark the lockdown itself as failed.
182                self.logger.warning(
183                    "Failed to sync account lockdown deactivation to outgoing providers",
184                    user=user.username,
185                    exc=exc,
186                )
187        self._emit_lockdown_event(request, user, reason)
188
189    def dispatch(self, request: HttpRequest) -> HttpResponse:
190        """Execute account lockdown actions."""
191        self.request = request
192        stage: AccountLockdownStage = self.executor.current_stage
193
194        pending_user = self.get_pending_user()
195        if not pending_user.is_authenticated:
196            self.logger.warning("No target user found for account lockdown")
197            return self.executor.stage_invalid(TARGET_REQUIRED_MESSAGE)
198        user = get_lockdown_target_users().filter(pk=pending_user.pk).first()
199        if user is None:
200            self.logger.warning("Target user is not eligible for account lockdown")
201            return self.executor.stage_invalid(TARGET_REQUIRED_MESSAGE)
202        if not can_lock_user(request.user, user):
203            self.logger.warning(
204                "Permission denied for account lockdown",
205                actor=getattr(request.user, "username", None),
206                target=user.username,
207            )
208            return self.executor.stage_invalid(PERMISSION_DENIED_MESSAGE)
209
210        reason = self.get_reason()
211        self_service = self.is_self_service(request, user)
212        if self_service and stage.delete_sessions and not stage.self_service_completion_flow:
213            self.logger.warning("No completion flow configured for self-service account lockdown")
214            return self.executor.stage_invalid(SELF_SERVICE_COMPLETION_FLOW_REQUIRED_MESSAGE)
215
216        self.logger.info(
217            "Executing account lockdown",
218            user=user.username,
219            reason=reason,
220            self_service=self_service,
221            deactivate_user=stage.deactivate_user,
222            set_unusable_password=stage.set_unusable_password,
223            delete_sessions=stage.delete_sessions,
224            revoke_tokens=stage.revoke_tokens,
225        )
226
227        try:
228            self._lockdown_user(request, stage, user, reason)
229            self.logger.info("Account lockdown completed", user=user.username)
230        except Exception as exc:  # noqa: BLE001
231            # Convert unexpected lockdown errors to a flow-stage failure instead
232            # of leaking an exception through the flow executor.
233            self.logger.warning("Account lockdown failed", user=user.username, exc=exc)
234            return self.executor.stage_invalid(ACCOUNT_LOCKDOWN_FAILED_MESSAGE)
235
236        if self_service:
237            if stage.delete_sessions:
238                return self._self_service_completion_response(request)
239            return self.executor.stage_ok()
240
241        return self.executor.stage_ok()
242
243    def _self_service_completion_response(self, request: HttpRequest) -> HttpResponse:
244        """Redirect to completion flow after self-service lockdown.
245
246        Since all sessions are deleted, the user cannot continue in the flow.
247        Redirect them to an unauthenticated completion flow that shows the
248        lockdown message.
249
250        We use a direct HTTP redirect instead of a challenge because the
251        flow executor's challenge handling may try to access the session
252        which we just deleted.
253        """
254        stage: AccountLockdownStage = self.executor.current_stage
255        completion_flow = stage.self_service_completion_flow
256        if completion_flow:
257            # Flush the current request's session to prevent Django's session
258            # middleware from trying to save a deleted session
259            if hasattr(request, "session"):
260                request.session.flush()
261            redirect_to = reverse(
262                "authentik_core:if-flow",
263                kwargs={"flow_slug": completion_flow.slug},
264            )
265            return HttpResponseRedirect(redirect_to)
266        return self.executor.stage_invalid(SELF_SERVICE_COMPLETION_FLOW_REQUIRED_MESSAGE)

Execute account lockdown actions on the target user.

def is_self_service( self, request: django.http.request.HttpRequest, user: authentik.core.models.User) -> bool:
71    def is_self_service(self, request: HttpRequest, user: User) -> bool:
72        """Check whether the currently authenticated user is locking their own account."""
73        return request.user.is_authenticated and user.pk == request.user.pk

Check whether the currently authenticated user is locking their own account.

def get_reason(self) -> str:
75    def get_reason(self) -> str:
76        """Get the lockdown reason from the plan context.
77
78        Priority:
79        1. prompt_data[PLAN_CONTEXT_LOCKDOWN_REASON]
80        2. PLAN_CONTEXT_LOCKDOWN_REASON (explicitly set)
81        3. Empty string as fallback
82        """
83        prompt_data = self.executor.plan.context.get(PLAN_CONTEXT_PROMPT, {})
84        if PLAN_CONTEXT_LOCKDOWN_REASON in prompt_data:
85            return prompt_data[PLAN_CONTEXT_LOCKDOWN_REASON]
86        return self.executor.plan.context.get(PLAN_CONTEXT_LOCKDOWN_REASON, "")

Get the lockdown reason from the plan context.

Priority:

  1. prompt_data[PLAN_CONTEXT_LOCKDOWN_REASON]
  2. PLAN_CONTEXT_LOCKDOWN_REASON (explicitly set)
  3. Empty string as fallback
def dispatch( self, request: django.http.request.HttpRequest) -> django.http.response.HttpResponse:
189    def dispatch(self, request: HttpRequest) -> HttpResponse:
190        """Execute account lockdown actions."""
191        self.request = request
192        stage: AccountLockdownStage = self.executor.current_stage
193
194        pending_user = self.get_pending_user()
195        if not pending_user.is_authenticated:
196            self.logger.warning("No target user found for account lockdown")
197            return self.executor.stage_invalid(TARGET_REQUIRED_MESSAGE)
198        user = get_lockdown_target_users().filter(pk=pending_user.pk).first()
199        if user is None:
200            self.logger.warning("Target user is not eligible for account lockdown")
201            return self.executor.stage_invalid(TARGET_REQUIRED_MESSAGE)
202        if not can_lock_user(request.user, user):
203            self.logger.warning(
204                "Permission denied for account lockdown",
205                actor=getattr(request.user, "username", None),
206                target=user.username,
207            )
208            return self.executor.stage_invalid(PERMISSION_DENIED_MESSAGE)
209
210        reason = self.get_reason()
211        self_service = self.is_self_service(request, user)
212        if self_service and stage.delete_sessions and not stage.self_service_completion_flow:
213            self.logger.warning("No completion flow configured for self-service account lockdown")
214            return self.executor.stage_invalid(SELF_SERVICE_COMPLETION_FLOW_REQUIRED_MESSAGE)
215
216        self.logger.info(
217            "Executing account lockdown",
218            user=user.username,
219            reason=reason,
220            self_service=self_service,
221            deactivate_user=stage.deactivate_user,
222            set_unusable_password=stage.set_unusable_password,
223            delete_sessions=stage.delete_sessions,
224            revoke_tokens=stage.revoke_tokens,
225        )
226
227        try:
228            self._lockdown_user(request, stage, user, reason)
229            self.logger.info("Account lockdown completed", user=user.username)
230        except Exception as exc:  # noqa: BLE001
231            # Convert unexpected lockdown errors to a flow-stage failure instead
232            # of leaking an exception through the flow executor.
233            self.logger.warning("Account lockdown failed", user=user.username, exc=exc)
234            return self.executor.stage_invalid(ACCOUNT_LOCKDOWN_FAILED_MESSAGE)
235
236        if self_service:
237            if stage.delete_sessions:
238                return self._self_service_completion_response(request)
239            return self.executor.stage_ok()
240
241        return self.executor.stage_ok()

Execute account lockdown actions.