authentik.enterprise.required_actions.middleware
Hold sessions to their required actions
1"""Hold sessions to their required actions""" 2 3from django.contrib import messages 4from django.http import HttpRequest, HttpResponse, JsonResponse, QueryDict 5from django.shortcuts import redirect 6from django.urls import reverse 7from django.utils.deprecation import MiddlewareMixin 8from django.utils.translation import gettext as _ 9from structlog.stdlib import get_logger 10 11from authentik.core.middleware import SESSION_KEY_IMPERSONATE_USER 12from authentik.enterprise.license import LicenseKey 13from authentik.enterprise.models import LicenseUsageStatus 14from authentik.enterprise.required_actions import USER_ATTRIBUTE_REQUIRED_ACTIONS 15from authentik.enterprise.required_actions.flows import ( 16 get_completion_stage, 17 plan_required_action, 18 resolve_required_actions, 19) 20from authentik.flows.exceptions import FlowNonApplicableException 21from authentik.flows.models import Flow, FlowDesignation, Stage 22from authentik.flows.planner import FlowPlan 23from authentik.flows.views.executor import ( 24 QS_QUERY, 25 SESSION_KEY_PLAN, 26 SESSION_KEY_POST, 27 to_stage_response, 28) 29from authentik.lib.utils.urls import reverse_with_qs 30 31LOGGER = get_logger() 32 33# Routes a session with required actions can always use 34ALLOWED_ROUTES = [ 35 # Read by the flow interface 36 "authentik_api:config", 37 "authentik_api:user-me", 38 "authentik_flows:cancel", 39 "authentik_flows:default-invalidation", 40 # Duo enrollment polls this endpoint while its stage is active 41 "authentik_api:authenticatorduostage-enrollment-status", 42] 43ROUTE_FLOW_INTERFACE = "authentik_core:if-flow" 44ROUTE_FLOW_EXECUTOR = "authentik_api:flow-executor" 45 46 47class RequiredActionsMiddleware(MiddlewareMixin): 48 """Send a user through their required actions before they can do anything else. 49 50 Whatever the user was doing is suspended: a flow in progress is stored with the action 51 and restored once it is complete, any other page is revisited.""" 52 53 def process_view(self, request: HttpRequest, view_func, view_args, view_kwargs): 54 user = request.user 55 route = request.resolver_match.view_name 56 if ( 57 not user.is_authenticated 58 or user.attributes.get(USER_ATTRIBUTE_REQUIRED_ACTIONS, []) == [] 59 or route in ALLOWED_ROUTES 60 # An administrator impersonating the user must not complete actions for them 61 or SESSION_KEY_IMPERSONATE_USER in request.session 62 # An expired license still enforces actions, so expiry cannot release a user 63 or LicenseKey.cached_summary().status == LicenseUsageStatus.UNLICENSED 64 ): 65 return None 66 flow = None 67 if route in (ROUTE_FLOW_INTERFACE, ROUTE_FLOW_EXECUTOR): 68 flow = Flow.objects.filter(slug=view_kwargs["flow_slug"]).first() 69 if flow and flow.designation == FlowDesignation.INVALIDATION: 70 return None 71 try: 72 action = resolve_required_actions(user.attributes[USER_ATTRIBUTE_REQUIRED_ACTIONS])[0] 73 return self.enforce(request, action, flow) 74 except (ValueError, FlowNonApplicableException) as exc: 75 LOGGER.warning("Invalid required action", user=user.username, error=str(exc)) 76 return JsonResponse( 77 {"detail": _("The required actions are invalid. Contact your administrator.")}, 78 status=403, 79 ) 80 81 def enforce(self, request: HttpRequest, action: Flow, flow: Flow | None) -> HttpResponse | None: 82 """Let the request through only if it runs `action`, otherwise start `action`.""" 83 executor = request.resolver_match.view_name == ROUTE_FLOW_EXECUTOR 84 plan: FlowPlan | None = request.session.get(SESSION_KEY_PLAN) 85 completion = get_completion_stage(plan) 86 running = completion is not None and completion.flow_slug == action.slug 87 if flow == action: 88 if executor and not running: 89 self.start(request, action, flow, plan, completion) 90 return None 91 if not executor and "text/html" not in request.headers.get("Accept", ""): 92 return JsonResponse( 93 {"detail": _("Complete the required actions before continuing.")}, status=403 94 ) 95 if not running: 96 self.start(request, action, flow, plan, completion) 97 messages.info(request, _("Complete the required actions before continuing.")) 98 response = redirect(ROUTE_FLOW_INTERFACE, flow_slug=action.slug) 99 return to_stage_response(request, response) if executor else response 100 101 def start( 102 self, 103 request: HttpRequest, 104 action: Flow, 105 flow: Flow | None, 106 plan: FlowPlan | None, 107 completion: Stage | None, 108 ): 109 """Plan `action`, suspending what the user requested.""" 110 if completion: 111 # An earlier action was replaced before it was complete; keep what it suspended 112 resume_url, resume_plan = completion.resume_url, completion.resume_plan 113 elif flow == action: 114 resume_url, resume_plan = reverse("authentik_core:root-redirect"), None 115 else: 116 if request.resolver_match.view_name == ROUTE_FLOW_EXECUTOR: 117 resume_url = reverse_with_qs( 118 ROUTE_FLOW_INTERFACE, 119 QueryDict(request.GET.get(QS_QUERY, "")), 120 kwargs=request.resolver_match.kwargs, 121 ) 122 else: 123 resume_url = request.get_full_path() 124 # The page is opened again with GET, so keep a POST body for it (mostly SAML) 125 if request.method == "POST": 126 request.session[SESSION_KEY_POST] = request.POST 127 in_progress = plan and flow and plan.flow_pk == flow.pk.hex 128 resume_plan = plan if in_progress else None 129 plan_required_action(request, action, resume_url, resume_plan)
LOGGER =
<BoundLoggerLazyProxy(logger=None, wrapper_class=None, processors=None, context_class=None, initial_values={}, logger_factory_args=())>
ALLOWED_ROUTES =
['authentik_api:config', 'authentik_api:user-me', 'authentik_flows:cancel', 'authentik_flows:default-invalidation', 'authentik_api:authenticatorduostage-enrollment-status']
ROUTE_FLOW_INTERFACE =
'authentik_core:if-flow'
ROUTE_FLOW_EXECUTOR =
'authentik_api:flow-executor'
class
RequiredActionsMiddleware(django.utils.deprecation.MiddlewareMixin):
48class RequiredActionsMiddleware(MiddlewareMixin): 49 """Send a user through their required actions before they can do anything else. 50 51 Whatever the user was doing is suspended: a flow in progress is stored with the action 52 and restored once it is complete, any other page is revisited.""" 53 54 def process_view(self, request: HttpRequest, view_func, view_args, view_kwargs): 55 user = request.user 56 route = request.resolver_match.view_name 57 if ( 58 not user.is_authenticated 59 or user.attributes.get(USER_ATTRIBUTE_REQUIRED_ACTIONS, []) == [] 60 or route in ALLOWED_ROUTES 61 # An administrator impersonating the user must not complete actions for them 62 or SESSION_KEY_IMPERSONATE_USER in request.session 63 # An expired license still enforces actions, so expiry cannot release a user 64 or LicenseKey.cached_summary().status == LicenseUsageStatus.UNLICENSED 65 ): 66 return None 67 flow = None 68 if route in (ROUTE_FLOW_INTERFACE, ROUTE_FLOW_EXECUTOR): 69 flow = Flow.objects.filter(slug=view_kwargs["flow_slug"]).first() 70 if flow and flow.designation == FlowDesignation.INVALIDATION: 71 return None 72 try: 73 action = resolve_required_actions(user.attributes[USER_ATTRIBUTE_REQUIRED_ACTIONS])[0] 74 return self.enforce(request, action, flow) 75 except (ValueError, FlowNonApplicableException) as exc: 76 LOGGER.warning("Invalid required action", user=user.username, error=str(exc)) 77 return JsonResponse( 78 {"detail": _("The required actions are invalid. Contact your administrator.")}, 79 status=403, 80 ) 81 82 def enforce(self, request: HttpRequest, action: Flow, flow: Flow | None) -> HttpResponse | None: 83 """Let the request through only if it runs `action`, otherwise start `action`.""" 84 executor = request.resolver_match.view_name == ROUTE_FLOW_EXECUTOR 85 plan: FlowPlan | None = request.session.get(SESSION_KEY_PLAN) 86 completion = get_completion_stage(plan) 87 running = completion is not None and completion.flow_slug == action.slug 88 if flow == action: 89 if executor and not running: 90 self.start(request, action, flow, plan, completion) 91 return None 92 if not executor and "text/html" not in request.headers.get("Accept", ""): 93 return JsonResponse( 94 {"detail": _("Complete the required actions before continuing.")}, status=403 95 ) 96 if not running: 97 self.start(request, action, flow, plan, completion) 98 messages.info(request, _("Complete the required actions before continuing.")) 99 response = redirect(ROUTE_FLOW_INTERFACE, flow_slug=action.slug) 100 return to_stage_response(request, response) if executor else response 101 102 def start( 103 self, 104 request: HttpRequest, 105 action: Flow, 106 flow: Flow | None, 107 plan: FlowPlan | None, 108 completion: Stage | None, 109 ): 110 """Plan `action`, suspending what the user requested.""" 111 if completion: 112 # An earlier action was replaced before it was complete; keep what it suspended 113 resume_url, resume_plan = completion.resume_url, completion.resume_plan 114 elif flow == action: 115 resume_url, resume_plan = reverse("authentik_core:root-redirect"), None 116 else: 117 if request.resolver_match.view_name == ROUTE_FLOW_EXECUTOR: 118 resume_url = reverse_with_qs( 119 ROUTE_FLOW_INTERFACE, 120 QueryDict(request.GET.get(QS_QUERY, "")), 121 kwargs=request.resolver_match.kwargs, 122 ) 123 else: 124 resume_url = request.get_full_path() 125 # The page is opened again with GET, so keep a POST body for it (mostly SAML) 126 if request.method == "POST": 127 request.session[SESSION_KEY_POST] = request.POST 128 in_progress = plan and flow and plan.flow_pk == flow.pk.hex 129 resume_plan = plan if in_progress else None 130 plan_required_action(request, action, resume_url, resume_plan)
Send a user through their required actions before they can do anything else.
Whatever the user was doing is suspended: a flow in progress is stored with the action and restored once it is complete, any other page is revisited.
def
process_view( self, request: django.http.request.HttpRequest, view_func, view_args, view_kwargs):
54 def process_view(self, request: HttpRequest, view_func, view_args, view_kwargs): 55 user = request.user 56 route = request.resolver_match.view_name 57 if ( 58 not user.is_authenticated 59 or user.attributes.get(USER_ATTRIBUTE_REQUIRED_ACTIONS, []) == [] 60 or route in ALLOWED_ROUTES 61 # An administrator impersonating the user must not complete actions for them 62 or SESSION_KEY_IMPERSONATE_USER in request.session 63 # An expired license still enforces actions, so expiry cannot release a user 64 or LicenseKey.cached_summary().status == LicenseUsageStatus.UNLICENSED 65 ): 66 return None 67 flow = None 68 if route in (ROUTE_FLOW_INTERFACE, ROUTE_FLOW_EXECUTOR): 69 flow = Flow.objects.filter(slug=view_kwargs["flow_slug"]).first() 70 if flow and flow.designation == FlowDesignation.INVALIDATION: 71 return None 72 try: 73 action = resolve_required_actions(user.attributes[USER_ATTRIBUTE_REQUIRED_ACTIONS])[0] 74 return self.enforce(request, action, flow) 75 except (ValueError, FlowNonApplicableException) as exc: 76 LOGGER.warning("Invalid required action", user=user.username, error=str(exc)) 77 return JsonResponse( 78 {"detail": _("The required actions are invalid. Contact your administrator.")}, 79 status=403, 80 )
def
enforce( self, request: django.http.request.HttpRequest, action: authentik.flows.models.Flow, flow: authentik.flows.models.Flow | None) -> django.http.response.HttpResponse | None:
82 def enforce(self, request: HttpRequest, action: Flow, flow: Flow | None) -> HttpResponse | None: 83 """Let the request through only if it runs `action`, otherwise start `action`.""" 84 executor = request.resolver_match.view_name == ROUTE_FLOW_EXECUTOR 85 plan: FlowPlan | None = request.session.get(SESSION_KEY_PLAN) 86 completion = get_completion_stage(plan) 87 running = completion is not None and completion.flow_slug == action.slug 88 if flow == action: 89 if executor and not running: 90 self.start(request, action, flow, plan, completion) 91 return None 92 if not executor and "text/html" not in request.headers.get("Accept", ""): 93 return JsonResponse( 94 {"detail": _("Complete the required actions before continuing.")}, status=403 95 ) 96 if not running: 97 self.start(request, action, flow, plan, completion) 98 messages.info(request, _("Complete the required actions before continuing.")) 99 response = redirect(ROUTE_FLOW_INTERFACE, flow_slug=action.slug) 100 return to_stage_response(request, response) if executor else response
Let the request through only if it runs action, otherwise start action.
def
start( self, request: django.http.request.HttpRequest, action: authentik.flows.models.Flow, flow: authentik.flows.models.Flow | None, plan: authentik.flows.planner.FlowPlan | None, completion: authentik.flows.models.Stage | None):
102 def start( 103 self, 104 request: HttpRequest, 105 action: Flow, 106 flow: Flow | None, 107 plan: FlowPlan | None, 108 completion: Stage | None, 109 ): 110 """Plan `action`, suspending what the user requested.""" 111 if completion: 112 # An earlier action was replaced before it was complete; keep what it suspended 113 resume_url, resume_plan = completion.resume_url, completion.resume_plan 114 elif flow == action: 115 resume_url, resume_plan = reverse("authentik_core:root-redirect"), None 116 else: 117 if request.resolver_match.view_name == ROUTE_FLOW_EXECUTOR: 118 resume_url = reverse_with_qs( 119 ROUTE_FLOW_INTERFACE, 120 QueryDict(request.GET.get(QS_QUERY, "")), 121 kwargs=request.resolver_match.kwargs, 122 ) 123 else: 124 resume_url = request.get_full_path() 125 # The page is opened again with GET, so keep a POST body for it (mostly SAML) 126 if request.method == "POST": 127 request.session[SESSION_KEY_POST] = request.POST 128 in_progress = plan and flow and plan.flow_pk == flow.pk.hex 129 resume_plan = plan if in_progress else None 130 plan_required_action(request, action, resume_url, resume_plan)
Plan action, suspending what the user requested.