authentik.enterprise.required_actions.flows

Required action flows

  1"""Required action flows"""
  2
  3from typing import Any
  4
  5from django.db import transaction
  6from django.http import HttpRequest, HttpResponse
  7from django.shortcuts import redirect
  8
  9from authentik.core.models import User
 10from authentik.enterprise.required_actions import USER_ATTRIBUTE_REQUIRED_ACTIONS
 11from authentik.events.middleware import audit_ignore
 12from authentik.events.models import Event, EventAction
 13from authentik.flows.models import (
 14    Flow,
 15    FlowAuthenticationRequirement,
 16    FlowDesignation,
 17    Stage,
 18    in_memory_stage,
 19)
 20from authentik.flows.planner import PLAN_CONTEXT_PENDING_USER, FlowPlan, FlowPlanner
 21from authentik.flows.stage import StageView
 22from authentik.flows.views.executor import SESSION_KEY_PLAN
 23
 24# Flows that create or end a session cannot run as a required action
 25DISALLOWED_DESIGNATIONS = [FlowDesignation.AUTHENTICATION, FlowDesignation.INVALIDATION]
 26# Flows that a logged-in user can never plan
 27DISALLOWED_AUTHENTICATION = [
 28    FlowAuthenticationRequirement.REQUIRE_UNAUTHENTICATED,
 29    FlowAuthenticationRequirement.REQUIRE_OUTPOST,
 30    FlowAuthenticationRequirement.REQUIRE_REDIRECT,
 31    FlowAuthenticationRequirement.REQUIRE_TOKEN,
 32]
 33
 34
 35def resolve_required_actions(value: Any) -> list[Flow]:
 36    """Resolve ordered flow slugs, rejecting missing or unusable flows."""
 37    slugs = value if isinstance(value, list) else [value]
 38    if any(not isinstance(slug, str) for slug in slugs):
 39        raise ValueError("Required actions must be flow slugs")
 40    flows = (
 41        Flow.objects.exclude(designation__in=DISALLOWED_DESIGNATIONS)
 42        .exclude(authentication__in=DISALLOWED_AUTHENTICATION)
 43        .in_bulk(slugs, field_name="slug")
 44    )
 45    try:
 46        return [flows[slug] for slug in slugs]
 47    except KeyError as exc:
 48        raise ValueError("Required action flow is missing or cannot run") from exc
 49
 50
 51def plan_required_action(
 52    request: HttpRequest, action: Flow, resume_url: str, resume_plan: FlowPlan | None
 53):
 54    """Start `action`, suspending what the user was doing until it is complete.
 55
 56    `resume_url` is where the user goes afterwards; `resume_plan` is the flow they were
 57    in, if any, and is restored before redirecting there."""
 58    planner = FlowPlanner(action)
 59    planner.use_cache = False
 60    planner.allow_empty_flows = True
 61    plan = planner.plan(request, {PLAN_CONTEXT_PENDING_USER: request.user})
 62    plan.append_stage(
 63        in_memory_stage(
 64            RequiredActionCompleteStageView,
 65            flow_slug=action.slug,
 66            resume_url=resume_url,
 67            resume_plan=resume_plan,
 68        )
 69    )
 70    request.session[SESSION_KEY_PLAN] = plan
 71
 72
 73def get_completion_stage(plan: FlowPlan | None) -> Stage | None:
 74    """Find the completion stage of a required action plan."""
 75    if not plan:
 76        return None
 77    for binding in plan.bindings:
 78        if binding.stage.view is RequiredActionCompleteStageView:
 79            return binding.stage
 80    return None
 81
 82
 83class RequiredActionCompleteStageView(StageView):
 84    """Remove the completed action from the user, then resume what they were doing"""
 85
 86    def dispatch(self, request: HttpRequest) -> HttpResponse:
 87        stage = self.executor.current_stage
 88        # The completion event replaces the user update event
 89        with transaction.atomic(), audit_ignore():
 90            user = User.objects.select_for_update().get(pk=self.get_pending_user().pk)
 91            value = user.attributes.get(USER_ATTRIBUTE_REQUIRED_ACTIONS, [])
 92            actions = value if isinstance(value, list) else [value]
 93            if stage.flow_slug in actions:
 94                actions.remove(stage.flow_slug)
 95                if actions:
 96                    user.attributes[USER_ATTRIBUTE_REQUIRED_ACTIONS] = actions
 97                else:
 98                    del user.attributes[USER_ATTRIBUTE_REQUIRED_ACTIONS]
 99                user.save(update_fields=["attributes"])
100                Event.new(
101                    EventAction.REQUIRED_ACTION_COMPLETED, flow_slug=stage.flow_slug
102                ).from_http(request, user=user)
103        self.executor.cancel()
104        if stage.resume_plan:
105            request.session[SESSION_KEY_PLAN] = stage.resume_plan
106        return redirect(stage.resume_url)
DISALLOWED_DESIGNATIONS = [FlowDesignation.AUTHENTICATION, FlowDesignation.INVALIDATION]
DISALLOWED_AUTHENTICATION = [FlowAuthenticationRequirement.REQUIRE_UNAUTHENTICATED, FlowAuthenticationRequirement.REQUIRE_OUTPOST, FlowAuthenticationRequirement.REQUIRE_REDIRECT, FlowAuthenticationRequirement.REQUIRE_TOKEN]
def resolve_required_actions(value: Any) -> list[authentik.flows.models.Flow]:
36def resolve_required_actions(value: Any) -> list[Flow]:
37    """Resolve ordered flow slugs, rejecting missing or unusable flows."""
38    slugs = value if isinstance(value, list) else [value]
39    if any(not isinstance(slug, str) for slug in slugs):
40        raise ValueError("Required actions must be flow slugs")
41    flows = (
42        Flow.objects.exclude(designation__in=DISALLOWED_DESIGNATIONS)
43        .exclude(authentication__in=DISALLOWED_AUTHENTICATION)
44        .in_bulk(slugs, field_name="slug")
45    )
46    try:
47        return [flows[slug] for slug in slugs]
48    except KeyError as exc:
49        raise ValueError("Required action flow is missing or cannot run") from exc

Resolve ordered flow slugs, rejecting missing or unusable flows.

def plan_required_action( request: django.http.request.HttpRequest, action: authentik.flows.models.Flow, resume_url: str, resume_plan: authentik.flows.planner.FlowPlan | None):
52def plan_required_action(
53    request: HttpRequest, action: Flow, resume_url: str, resume_plan: FlowPlan | None
54):
55    """Start `action`, suspending what the user was doing until it is complete.
56
57    `resume_url` is where the user goes afterwards; `resume_plan` is the flow they were
58    in, if any, and is restored before redirecting there."""
59    planner = FlowPlanner(action)
60    planner.use_cache = False
61    planner.allow_empty_flows = True
62    plan = planner.plan(request, {PLAN_CONTEXT_PENDING_USER: request.user})
63    plan.append_stage(
64        in_memory_stage(
65            RequiredActionCompleteStageView,
66            flow_slug=action.slug,
67            resume_url=resume_url,
68            resume_plan=resume_plan,
69        )
70    )
71    request.session[SESSION_KEY_PLAN] = plan

Start action, suspending what the user was doing until it is complete.

resume_url is where the user goes afterwards; resume_plan is the flow they were in, if any, and is restored before redirecting there.

def get_completion_stage( plan: authentik.flows.planner.FlowPlan | None) -> authentik.flows.models.Stage | None:
74def get_completion_stage(plan: FlowPlan | None) -> Stage | None:
75    """Find the completion stage of a required action plan."""
76    if not plan:
77        return None
78    for binding in plan.bindings:
79        if binding.stage.view is RequiredActionCompleteStageView:
80            return binding.stage
81    return None

Find the completion stage of a required action plan.

class RequiredActionCompleteStageView(authentik.flows.stage.StageView):
 84class RequiredActionCompleteStageView(StageView):
 85    """Remove the completed action from the user, then resume what they were doing"""
 86
 87    def dispatch(self, request: HttpRequest) -> HttpResponse:
 88        stage = self.executor.current_stage
 89        # The completion event replaces the user update event
 90        with transaction.atomic(), audit_ignore():
 91            user = User.objects.select_for_update().get(pk=self.get_pending_user().pk)
 92            value = user.attributes.get(USER_ATTRIBUTE_REQUIRED_ACTIONS, [])
 93            actions = value if isinstance(value, list) else [value]
 94            if stage.flow_slug in actions:
 95                actions.remove(stage.flow_slug)
 96                if actions:
 97                    user.attributes[USER_ATTRIBUTE_REQUIRED_ACTIONS] = actions
 98                else:
 99                    del user.attributes[USER_ATTRIBUTE_REQUIRED_ACTIONS]
100                user.save(update_fields=["attributes"])
101                Event.new(
102                    EventAction.REQUIRED_ACTION_COMPLETED, flow_slug=stage.flow_slug
103                ).from_http(request, user=user)
104        self.executor.cancel()
105        if stage.resume_plan:
106            request.session[SESSION_KEY_PLAN] = stage.resume_plan
107        return redirect(stage.resume_url)

Remove the completed action from the user, then resume what they were doing

def dispatch( self, request: django.http.request.HttpRequest) -> django.http.response.HttpResponse:
 87    def dispatch(self, request: HttpRequest) -> HttpResponse:
 88        stage = self.executor.current_stage
 89        # The completion event replaces the user update event
 90        with transaction.atomic(), audit_ignore():
 91            user = User.objects.select_for_update().get(pk=self.get_pending_user().pk)
 92            value = user.attributes.get(USER_ATTRIBUTE_REQUIRED_ACTIONS, [])
 93            actions = value if isinstance(value, list) else [value]
 94            if stage.flow_slug in actions:
 95                actions.remove(stage.flow_slug)
 96                if actions:
 97                    user.attributes[USER_ATTRIBUTE_REQUIRED_ACTIONS] = actions
 98                else:
 99                    del user.attributes[USER_ATTRIBUTE_REQUIRED_ACTIONS]
100                user.save(update_fields=["attributes"])
101                Event.new(
102                    EventAction.REQUIRED_ACTION_COMPLETED, flow_slug=stage.flow_slug
103                ).from_http(request, user=user)
104        self.executor.cancel()
105        if stage.resume_plan:
106            request.session[SESSION_KEY_PLAN] = stage.resume_plan
107        return redirect(stage.resume_url)