authentik.core.sources.flow_manager

Source decision helper

  1"""Source decision helper"""
  2
  3from dataclasses import dataclass
  4from typing import Any
  5
  6from django.contrib import messages
  7from django.db import IntegrityError, transaction
  8from django.http import HttpRequest, HttpResponse
  9from django.shortcuts import redirect
 10from django.urls import reverse
 11from django.utils.translation import gettext as _
 12from structlog.stdlib import get_logger
 13
 14from authentik.core.models import (
 15    Group,
 16    GroupSourceConnection,
 17    Source,
 18    User,
 19    UserSourceConnection,
 20)
 21from authentik.core.sources.mapper import SourceMapper
 22from authentik.core.sources.matcher import Action, MatchFailure, MatchFailureReason, SourceMatcher
 23from authentik.core.sources.stage import (
 24    PLAN_CONTEXT_SOURCES_CONNECTION,
 25    PostSourceStage,
 26)
 27from authentik.core.user_switching import SESSION_KEY_ADD_USER
 28from authentik.events.models import Event, EventAction
 29from authentik.flows.exceptions import FlowNonApplicableException
 30from authentik.flows.models import Flow, FlowToken, Stage, in_memory_stage
 31from authentik.flows.planner import (
 32    PLAN_CONTEXT_IS_RESTORED,
 33    PLAN_CONTEXT_PENDING_USER,
 34    PLAN_CONTEXT_REDIRECT,
 35    PLAN_CONTEXT_SOURCE,
 36    PLAN_CONTEXT_SSO,
 37    PLAN_CONTEXT_USER_SWITCH_ADD_USER,
 38    FlowPlanner,
 39)
 40from authentik.flows.stage import StageView
 41from authentik.flows.views.executor import NEXT_ARG_NAME, SESSION_KEY_GET
 42from authentik.lib.tracing import TracingIgnoredException
 43from authentik.lib.views import bad_request_message
 44from authentik.policies.denied import AccessDeniedResponse
 45from authentik.policies.utils import delete_none_values
 46from authentik.stages.password import BACKEND_INBUILT
 47from authentik.stages.password.stage import PLAN_CONTEXT_AUTHENTICATION_BACKEND
 48from authentik.stages.prompt.stage import PLAN_CONTEXT_PROMPT
 49from authentik.stages.user_write.stage import PLAN_CONTEXT_USER_PATH
 50
 51LOGGER = get_logger()
 52
 53PLAN_CONTEXT_SOURCE_GROUPS = "source_groups"
 54PLAN_CONTEXT_SOURCE_MATCH_FAILURE = "goauthentik.io/core/sources/matching_failure"
 55PLAN_CONTEXT_SOURCE_MATCH_FAILURE_CONFIG = "goauthentik.io/core/sources/match_failure_config"
 56SESSION_KEY_SOURCE_FLOW_STAGES = "authentik/flows/source_flow_stages"
 57SESSION_KEY_SOURCE_FLOW_CONTEXT = "authentik/flows/source_flow_context"
 58SESSION_KEY_OVERRIDE_FLOW_TOKEN = "authentik/flows/source_override_flow_token"  # nosec
 59
 60
 61def clear_source_flow_session(request: HttpRequest) -> None:
 62    """Clear state used to return from a source flow."""
 63    for key in (
 64        SESSION_KEY_OVERRIDE_FLOW_TOKEN,
 65        SESSION_KEY_SOURCE_FLOW_CONTEXT,
 66        SESSION_KEY_SOURCE_FLOW_STAGES,
 67    ):
 68        request.session.pop(key, None)
 69
 70
 71@dataclass(frozen=True)
 72class MatchFailureConfig:
 73
 74    reasons: list[MatchFailureReason]
 75    source_pk: str
 76    stage_pk: str | None
 77
 78
 79class MessageStage(StageView):
 80    """Show a pre-configured message after the flow is done"""
 81
 82    def dispatch(self, request: HttpRequest, *args, **kwargs) -> HttpResponse:
 83        """Show a pre-configured message after the flow is done"""
 84        message = getattr(self.executor.current_stage, "message", "")
 85        level = getattr(self.executor.current_stage, "level", messages.SUCCESS)
 86        messages.add_message(
 87            self.request,
 88            level,
 89            message,
 90        )
 91        return self.executor.stage_ok()
 92
 93
 94class SourceFlowManager:
 95    """Help sources decide what they should do after authorization. Based on source settings and
 96    previous connections, authenticate the user, enroll a new user, link to an existing user
 97    or deny the request."""
 98
 99    source: Source
100    mapper: SourceMapper
101    matcher: SourceMatcher
102    request: HttpRequest
103
104    identifier: str
105
106    user_connection_type: type[UserSourceConnection]
107    group_connection_type: type[GroupSourceConnection]
108
109    user_info: dict[str, Any]
110    policy_context: dict[str, Any]
111    user_properties: dict[str, Any | dict[str, Any]]
112    groups_properties: dict[str, dict[str, Any | dict[str, Any]]]
113
114    def __init__(
115        self,
116        source: Source,
117        request: HttpRequest,
118        identifier: str,
119        user_info: dict[str, Any],
120        policy_context: dict[str, Any],
121    ) -> None:
122        self.source = source
123        self.mapper = SourceMapper(self.source)
124        self.matcher = SourceMatcher(
125            self.source, self.user_connection_type, self.group_connection_type
126        )
127        self.request = request
128        self.identifier = identifier
129        self.user_info = user_info
130        self._logger = get_logger().bind(source=source, identifier=identifier)
131        self.policy_context = policy_context
132        # The source was started from "Add user", so the login must add another user to this
133        # browser instead of linking to or replacing the current user.
134        self.is_user_switch_add_user = bool(request.session.pop(SESSION_KEY_ADD_USER, False))
135
136        self.user_properties = self.mapper.build_object_properties(
137            object_type=User, request=request, user=None, **self.user_info
138        )
139        groups_manager = self.mapper.get_manager(Group, ["group_id", *self.user_info.keys()])
140        self.groups_properties = {
141            group_id: self.mapper.build_object_properties(
142                object_type=Group,
143                manager=groups_manager,
144                request=request,
145                user=None,
146                group_id=group_id,
147                **self.user_info,
148            )
149            for group_id in self._keyable_group_ids(self.user_properties.setdefault("groups", []))
150        }
151        del self.user_properties["groups"]
152
153    def _keyable_group_ids(self, group_ids: list[Any]) -> list[Any]:
154        """Drop group identifiers that cannot be used as a `groups_properties` key.
155
156        An unhashable identifier, such as an object in an IdP's `groups` claim,
157        raised `TypeError` out of the constructor and surfaced as HTTP 500,
158        locking every member of that group out of the source. Skipped entries are
159        recorded so a user arriving with fewer groups than the IdP granted stays
160        visible to an operator.
161        """
162        keyable = []
163        skipped = []
164        for group_id in group_ids:
165            try:
166                hash(group_id)
167            except TypeError:
168                skipped.append(group_id)
169            else:
170                keyable.append(group_id)
171        if skipped:
172            self._logger.warning("Skipping groups with an unusable identifier", groups=skipped)
173            Event.new(
174                EventAction.CONFIGURATION_ERROR,
175                message=(
176                    f"Source '{self.source.name}' returned {len(skipped)} group(s) whose "
177                    "identifier is not a string; they were not applied to the user."
178                ),
179                source=self.source,
180                groups=skipped,
181            ).from_http(self.request)
182        return keyable
183
184    def get_action(self, **kwargs) -> tuple[Action, UserSourceConnection | None]:  # noqa: PLR0911
185        """decide which action should be taken"""
186        # When request is authenticated, always link
187        if self.request.user.is_authenticated and not self.is_user_switch_add_user:
188            new_connection = self.user_connection_type(
189                source=self.source, identifier=self.identifier
190            )
191            new_connection.user = self.request.user
192            new_connection = self.update_user_connection(new_connection, **kwargs)
193            if existing := self.user_connection_type.objects.filter(
194                source=self.source, identifier=self.identifier
195            ).first():
196                existing = self.update_user_connection(existing, **kwargs)
197                return Action.AUTH, existing
198            return Action.LINK, new_connection
199
200        action, connection = self.matcher.get_user_action(self.identifier, self.user_properties)
201        if connection:
202            connection = self.update_user_connection(connection, **kwargs)
203        return action, connection
204
205    def update_user_connection(
206        self, connection: UserSourceConnection, **kwargs
207    ) -> UserSourceConnection:  # pragma: no cover
208        """Optionally make changes to the user connection after it is looked up/created."""
209        return connection
210
211    def get_flow(self, **kwargs) -> HttpResponse:
212        """Get the flow response based on user_matching_mode"""
213        try:
214            action, connection = self.get_action(**kwargs)
215        except IntegrityError as exc:
216            self._logger.warning("failed to get action", exc=exc)
217            return redirect(reverse("authentik_core:root-redirect"))
218        self._logger.debug("get_action", action=action, connection=connection)
219        try:
220            if connection:
221                if action == Action.LINK:
222                    self._logger.debug("Linking existing user")
223                    return self.handle_existing_link(connection)
224                if action == Action.AUTH:
225                    self._logger.debug("Handling auth user")
226                    return self.handle_auth(connection)
227                if action == Action.ENROLL:
228                    if self.is_user_switch_add_user:
229                        return self.error_handler(
230                            TracingIgnoredException(
231                                _("New users can't enroll while adding a user.")
232                            )
233                        )
234                    self._logger.debug("Handling enrollment of new user")
235                    return self.handle_enroll(connection)
236            if action == Action.DENY and self.matcher.failure:
237                response = self.handle_match_failure(self.matcher.failure)
238                if response:
239                    return response
240        except FlowNonApplicableException as exc:
241            self._logger.warning("Flow non applicable", exc=exc)
242            return self.error_handler(exc)
243        # Default case, assume deny
244        error = Exception(
245            _(
246                "Request to authenticate with {source} has been denied. Please authenticate "
247                "with the source you've previously signed up with."
248            ).format(source=self.source.name),
249        )
250        return self.error_handler(error)
251
252    def handle_match_failure(self, failure: MatchFailure) -> HttpResponse | None:
253        """Resume an opted-in Source Stage after a configured matching failure."""
254        session_token: FlowToken = self.request.session.get(SESSION_KEY_OVERRIDE_FLOW_TOKEN)
255        if not session_token:
256            return None
257        try:
258            session_token.refresh_from_db()
259        except FlowToken.DoesNotExist:
260            clear_source_flow_session(self.request)
261            return None
262        if session_token.is_expired:
263            session_token.expire_action()
264            clear_source_flow_session(self.request)
265            return None
266        plan = session_token.plan
267        resume_config: MatchFailureConfig | None = plan.context.get(
268            PLAN_CONTEXT_SOURCE_MATCH_FAILURE_CONFIG
269        )
270        current_stage = plan.bindings[0].stage if plan.bindings else None
271        if not resume_config or not current_stage:
272            return None
273        if (
274            failure.reason not in resume_config.reasons
275            or resume_config.source_pk != str(self.source.pk)
276            or resume_config.stage_pk != str(current_stage.pk)
277            or getattr(current_stage, "source_id", None) != self.source.pk
278        ):
279            return None
280
281        plan.context.pop(PLAN_CONTEXT_SOURCE_MATCH_FAILURE_CONFIG, None)
282        plan.context.update(self.policy_context)
283        plan.context[PLAN_CONTEXT_SOURCE_MATCH_FAILURE] = failure
284        plan.context[PLAN_CONTEXT_IS_RESTORED] = session_token
285        response = plan.to_redirect(self.request, session_token.flow)
286        session_token.delete()
287        return response
288
289    def error_handler(self, error: Exception) -> HttpResponse:
290        """Handle any errors by returning an access denied stage"""
291        response = AccessDeniedResponse(self.request)
292        response.error_message = str(error)
293        if isinstance(error, FlowNonApplicableException):
294            response.policy_result = error.policy_result
295            response.error_message = error.messages
296        return response
297
298    def get_stages_to_append(self, flow: Flow) -> list[Stage]:
299        """Hook to override stages which are appended to the flow"""
300        return [
301            in_memory_stage(PostSourceStage),
302        ]
303
304    def _prepare_flow(
305        self,
306        flow: Flow | None,
307        connection: UserSourceConnection,
308        stages: list[StageView] | None = None,
309        **flow_context,
310    ) -> HttpResponse:
311        """Prepare Authentication Plan, redirect user FlowExecutor"""
312        # Ensure redirect is carried through when user was trying to
313        # authorize application
314        final_redirect = self.request.session.get(SESSION_KEY_GET, {}).get(
315            NEXT_ARG_NAME, "authentik_core:if-user"
316        )
317        flow_context.update(
318            {
319                # Since we authenticate the user by their token, they have no backend set
320                PLAN_CONTEXT_AUTHENTICATION_BACKEND: BACKEND_INBUILT,
321                PLAN_CONTEXT_SSO: True,
322                PLAN_CONTEXT_SOURCE: self.source,
323                PLAN_CONTEXT_SOURCES_CONNECTION: connection,
324                PLAN_CONTEXT_SOURCE_GROUPS: self.groups_properties,
325            }
326        )
327        flow_context.update(self.policy_context)
328        flow_context.setdefault(PLAN_CONTEXT_REDIRECT, final_redirect)
329        if self.is_user_switch_add_user:
330            flow_context[PLAN_CONTEXT_USER_SWITCH_ADD_USER] = True
331
332        if not flow:
333            # We only check for the flow token here if we don't have a flow, otherwise we rely on
334            # SESSION_KEY_SOURCE_FLOW_STAGES to delegate the usage of this token and dynamically add
335            # stages that deal with this token to return to another flow
336            if SESSION_KEY_OVERRIDE_FLOW_TOKEN in self.request.session:
337                token: FlowToken = self.request.session.get(SESSION_KEY_OVERRIDE_FLOW_TOKEN)
338                self._logger.info(
339                    "Replacing source flow with overridden flow", flow=token.flow.slug
340                )
341                plan = token.plan
342                plan.context[PLAN_CONTEXT_IS_RESTORED] = token
343                plan.context.update(flow_context)
344                for stage in self.get_stages_to_append(flow):
345                    plan.append_stage(stage)
346                if stages:
347                    for stage in stages:
348                        plan.append_stage(stage)
349                redirect = plan.to_redirect(self.request, token.flow)
350                token.delete()
351                return redirect
352            return bad_request_message(
353                self.request,
354                _("Configured flow does not exist."),
355            )
356        # We run the Flow planner here so we can pass the Pending user in the context
357        planner = FlowPlanner(flow)
358        # We append some stages so the initial flow we get might be empty
359        planner.allow_empty_flows = True
360        planner.use_cache = False
361        plan = planner.plan(self.request, flow_context)
362        for stage in self.get_stages_to_append(flow):
363            plan.append_stage(stage)
364        plan.append_stage(
365            in_memory_stage(GroupUpdateStage, group_connection_type=self.group_connection_type)
366        )
367        if stages:
368            for stage in stages:
369                plan.append_stage(stage)
370        for stage in self.request.session.get(SESSION_KEY_SOURCE_FLOW_STAGES, []):
371            plan.append_stage(stage)
372        plan.context.update(self.request.session.get(SESSION_KEY_SOURCE_FLOW_CONTEXT, {}))
373        return plan.to_redirect(self.request, flow)
374
375    def handle_auth(
376        self,
377        connection: UserSourceConnection,
378    ) -> HttpResponse:
379        """Login user and redirect."""
380        return self._prepare_flow(
381            self.source.authentication_flow,
382            connection,
383            stages=[
384                in_memory_stage(
385                    MessageStage,
386                    message=_("Successfully authenticated with {source}!").format(
387                        source=self.source.name
388                    ),
389                )
390            ],
391            **{
392                PLAN_CONTEXT_PENDING_USER: connection.user,
393                PLAN_CONTEXT_PROMPT: delete_none_values(self.user_properties),
394                PLAN_CONTEXT_USER_PATH: self.source.get_user_path(),
395            },
396        )
397
398    def handle_existing_link(
399        self,
400        connection: UserSourceConnection,
401    ) -> HttpResponse:
402        """Handler when the user was already authenticated and linked an external source
403        to their account."""
404        # When request isn't authenticated we jump straight to auth
405        if not self.request.user.is_authenticated or self.is_user_switch_add_user:
406            return self.handle_auth(connection)
407        # When an override flow token exists we actually still use a flow for link
408        # to continue the existing flow we came from
409        if SESSION_KEY_OVERRIDE_FLOW_TOKEN in self.request.session:
410            return self._prepare_flow(None, connection)
411        connection.save()
412        Event.new(
413            EventAction.SOURCE_LINKED,
414            message="Linked Source",
415            source=self.source,
416        ).from_http(self.request)
417        messages.success(
418            self.request,
419            _("Successfully linked {source}!").format(source=self.source.name),
420        )
421        return redirect(
422            reverse(
423                "authentik_core:if-user",
424            )
425            + "settings/sources"
426        )
427
428    def handle_enroll(
429        self,
430        connection: UserSourceConnection,
431    ) -> HttpResponse:
432        """User was not authenticated and previous request was not authenticated."""
433        # We run the Flow planner here so we can pass the Pending user in the context
434        if not self.source.enrollment_flow:
435            self._logger.warning("source has no enrollment flow")
436            return bad_request_message(
437                self.request,
438                _("Source is not configured for enrollment."),
439            )
440        return self._prepare_flow(
441            self.source.enrollment_flow,
442            connection,
443            stages=[
444                in_memory_stage(
445                    MessageStage,
446                    message=_("Successfully authenticated with {source}!").format(
447                        source=self.source.name
448                    ),
449                )
450            ],
451            **{
452                PLAN_CONTEXT_PROMPT: delete_none_values(self.user_properties),
453                PLAN_CONTEXT_USER_PATH: self.source.get_user_path(),
454            },
455        )
456
457
458class GroupUpdateStage(StageView):
459    """Dynamically injected stage which updates the user after enrollment/authentication."""
460
461    def handle_group(
462        self, group_id: str, group_properties: dict[str, Any | dict[str, Any]]
463    ) -> Group | None:
464        action, connection = self.matcher.get_group_action(group_id, group_properties)
465        if action == Action.ENROLL:
466            group = Group.objects.create(**group_properties)
467            connection.group = group
468            connection.save()
469            return group
470        elif action in (Action.LINK, Action.AUTH):
471            group = connection.group
472            group.update_attributes(group_properties)
473            connection.save()
474            return group
475
476        return None
477
478    def handle_groups(self) -> bool:
479        self.source: Source = self.executor.plan.context[PLAN_CONTEXT_SOURCE]
480        self.user: User = self.executor.plan.context[PLAN_CONTEXT_PENDING_USER]
481        self.group_connection_type: GroupSourceConnection = (
482            self.executor.current_stage.group_connection_type
483        )
484        self.matcher = SourceMatcher(self.source, None, self.group_connection_type)
485
486        raw_groups: dict[str, dict[str, Any | dict[str, Any]]] = self.executor.plan.context[
487            PLAN_CONTEXT_SOURCE_GROUPS
488        ]
489        groups: list[Group] = []
490
491        for group_id, group_properties in raw_groups.items():
492            group = self.handle_group(group_id, group_properties)
493            if not group:
494                return False
495            groups.append(group)
496
497        with transaction.atomic():
498            self.user.groups.remove(
499                *self.user.groups.filter(groupsourceconnection__source=self.source)
500            )
501            self.user.groups.add(*groups)
502
503        return True
504
505    def get(self, request: HttpRequest, *args, **kwargs) -> HttpResponse:
506        """Stage used after the user has been enrolled to sync their groups from source data"""
507        if self.handle_groups():
508            return self.executor.stage_ok()
509        else:
510            return self.executor.stage_invalid("Failed to update groups. Please try again later.")
511
512    def post(self, request: HttpRequest) -> HttpResponse:
513        """Wrapper for post requests"""
514        return self.get(request)
LOGGER = <BoundLoggerLazyProxy(logger=None, wrapper_class=None, processors=None, context_class=None, initial_values={}, logger_factory_args=())>
PLAN_CONTEXT_SOURCE_GROUPS = 'source_groups'
PLAN_CONTEXT_SOURCE_MATCH_FAILURE = 'goauthentik.io/core/sources/matching_failure'
PLAN_CONTEXT_SOURCE_MATCH_FAILURE_CONFIG = 'goauthentik.io/core/sources/match_failure_config'
SESSION_KEY_SOURCE_FLOW_STAGES = 'authentik/flows/source_flow_stages'
SESSION_KEY_SOURCE_FLOW_CONTEXT = 'authentik/flows/source_flow_context'
SESSION_KEY_OVERRIDE_FLOW_TOKEN = 'authentik/flows/source_override_flow_token'
def clear_source_flow_session(request: django.http.request.HttpRequest) -> None:
62def clear_source_flow_session(request: HttpRequest) -> None:
63    """Clear state used to return from a source flow."""
64    for key in (
65        SESSION_KEY_OVERRIDE_FLOW_TOKEN,
66        SESSION_KEY_SOURCE_FLOW_CONTEXT,
67        SESSION_KEY_SOURCE_FLOW_STAGES,
68    ):
69        request.session.pop(key, None)

Clear state used to return from a source flow.

@dataclass(frozen=True)
class MatchFailureConfig:
72@dataclass(frozen=True)
73class MatchFailureConfig:
74
75    reasons: list[MatchFailureReason]
76    source_pk: str
77    stage_pk: str | None
MatchFailureConfig( reasons: list[authentik.core.sources.matcher.MatchFailureReason], source_pk: str, stage_pk: str | None)
source_pk: str
stage_pk: str | None
class MessageStage(authentik.flows.stage.StageView):
80class MessageStage(StageView):
81    """Show a pre-configured message after the flow is done"""
82
83    def dispatch(self, request: HttpRequest, *args, **kwargs) -> HttpResponse:
84        """Show a pre-configured message after the flow is done"""
85        message = getattr(self.executor.current_stage, "message", "")
86        level = getattr(self.executor.current_stage, "level", messages.SUCCESS)
87        messages.add_message(
88            self.request,
89            level,
90            message,
91        )
92        return self.executor.stage_ok()

Show a pre-configured message after the flow is done

def dispatch( self, request: django.http.request.HttpRequest, *args, **kwargs) -> django.http.response.HttpResponse:
83    def dispatch(self, request: HttpRequest, *args, **kwargs) -> HttpResponse:
84        """Show a pre-configured message after the flow is done"""
85        message = getattr(self.executor.current_stage, "message", "")
86        level = getattr(self.executor.current_stage, "level", messages.SUCCESS)
87        messages.add_message(
88            self.request,
89            level,
90            message,
91        )
92        return self.executor.stage_ok()

Show a pre-configured message after the flow is done

class SourceFlowManager:
 95class SourceFlowManager:
 96    """Help sources decide what they should do after authorization. Based on source settings and
 97    previous connections, authenticate the user, enroll a new user, link to an existing user
 98    or deny the request."""
 99
100    source: Source
101    mapper: SourceMapper
102    matcher: SourceMatcher
103    request: HttpRequest
104
105    identifier: str
106
107    user_connection_type: type[UserSourceConnection]
108    group_connection_type: type[GroupSourceConnection]
109
110    user_info: dict[str, Any]
111    policy_context: dict[str, Any]
112    user_properties: dict[str, Any | dict[str, Any]]
113    groups_properties: dict[str, dict[str, Any | dict[str, Any]]]
114
115    def __init__(
116        self,
117        source: Source,
118        request: HttpRequest,
119        identifier: str,
120        user_info: dict[str, Any],
121        policy_context: dict[str, Any],
122    ) -> None:
123        self.source = source
124        self.mapper = SourceMapper(self.source)
125        self.matcher = SourceMatcher(
126            self.source, self.user_connection_type, self.group_connection_type
127        )
128        self.request = request
129        self.identifier = identifier
130        self.user_info = user_info
131        self._logger = get_logger().bind(source=source, identifier=identifier)
132        self.policy_context = policy_context
133        # The source was started from "Add user", so the login must add another user to this
134        # browser instead of linking to or replacing the current user.
135        self.is_user_switch_add_user = bool(request.session.pop(SESSION_KEY_ADD_USER, False))
136
137        self.user_properties = self.mapper.build_object_properties(
138            object_type=User, request=request, user=None, **self.user_info
139        )
140        groups_manager = self.mapper.get_manager(Group, ["group_id", *self.user_info.keys()])
141        self.groups_properties = {
142            group_id: self.mapper.build_object_properties(
143                object_type=Group,
144                manager=groups_manager,
145                request=request,
146                user=None,
147                group_id=group_id,
148                **self.user_info,
149            )
150            for group_id in self._keyable_group_ids(self.user_properties.setdefault("groups", []))
151        }
152        del self.user_properties["groups"]
153
154    def _keyable_group_ids(self, group_ids: list[Any]) -> list[Any]:
155        """Drop group identifiers that cannot be used as a `groups_properties` key.
156
157        An unhashable identifier, such as an object in an IdP's `groups` claim,
158        raised `TypeError` out of the constructor and surfaced as HTTP 500,
159        locking every member of that group out of the source. Skipped entries are
160        recorded so a user arriving with fewer groups than the IdP granted stays
161        visible to an operator.
162        """
163        keyable = []
164        skipped = []
165        for group_id in group_ids:
166            try:
167                hash(group_id)
168            except TypeError:
169                skipped.append(group_id)
170            else:
171                keyable.append(group_id)
172        if skipped:
173            self._logger.warning("Skipping groups with an unusable identifier", groups=skipped)
174            Event.new(
175                EventAction.CONFIGURATION_ERROR,
176                message=(
177                    f"Source '{self.source.name}' returned {len(skipped)} group(s) whose "
178                    "identifier is not a string; they were not applied to the user."
179                ),
180                source=self.source,
181                groups=skipped,
182            ).from_http(self.request)
183        return keyable
184
185    def get_action(self, **kwargs) -> tuple[Action, UserSourceConnection | None]:  # noqa: PLR0911
186        """decide which action should be taken"""
187        # When request is authenticated, always link
188        if self.request.user.is_authenticated and not self.is_user_switch_add_user:
189            new_connection = self.user_connection_type(
190                source=self.source, identifier=self.identifier
191            )
192            new_connection.user = self.request.user
193            new_connection = self.update_user_connection(new_connection, **kwargs)
194            if existing := self.user_connection_type.objects.filter(
195                source=self.source, identifier=self.identifier
196            ).first():
197                existing = self.update_user_connection(existing, **kwargs)
198                return Action.AUTH, existing
199            return Action.LINK, new_connection
200
201        action, connection = self.matcher.get_user_action(self.identifier, self.user_properties)
202        if connection:
203            connection = self.update_user_connection(connection, **kwargs)
204        return action, connection
205
206    def update_user_connection(
207        self, connection: UserSourceConnection, **kwargs
208    ) -> UserSourceConnection:  # pragma: no cover
209        """Optionally make changes to the user connection after it is looked up/created."""
210        return connection
211
212    def get_flow(self, **kwargs) -> HttpResponse:
213        """Get the flow response based on user_matching_mode"""
214        try:
215            action, connection = self.get_action(**kwargs)
216        except IntegrityError as exc:
217            self._logger.warning("failed to get action", exc=exc)
218            return redirect(reverse("authentik_core:root-redirect"))
219        self._logger.debug("get_action", action=action, connection=connection)
220        try:
221            if connection:
222                if action == Action.LINK:
223                    self._logger.debug("Linking existing user")
224                    return self.handle_existing_link(connection)
225                if action == Action.AUTH:
226                    self._logger.debug("Handling auth user")
227                    return self.handle_auth(connection)
228                if action == Action.ENROLL:
229                    if self.is_user_switch_add_user:
230                        return self.error_handler(
231                            TracingIgnoredException(
232                                _("New users can't enroll while adding a user.")
233                            )
234                        )
235                    self._logger.debug("Handling enrollment of new user")
236                    return self.handle_enroll(connection)
237            if action == Action.DENY and self.matcher.failure:
238                response = self.handle_match_failure(self.matcher.failure)
239                if response:
240                    return response
241        except FlowNonApplicableException as exc:
242            self._logger.warning("Flow non applicable", exc=exc)
243            return self.error_handler(exc)
244        # Default case, assume deny
245        error = Exception(
246            _(
247                "Request to authenticate with {source} has been denied. Please authenticate "
248                "with the source you've previously signed up with."
249            ).format(source=self.source.name),
250        )
251        return self.error_handler(error)
252
253    def handle_match_failure(self, failure: MatchFailure) -> HttpResponse | None:
254        """Resume an opted-in Source Stage after a configured matching failure."""
255        session_token: FlowToken = self.request.session.get(SESSION_KEY_OVERRIDE_FLOW_TOKEN)
256        if not session_token:
257            return None
258        try:
259            session_token.refresh_from_db()
260        except FlowToken.DoesNotExist:
261            clear_source_flow_session(self.request)
262            return None
263        if session_token.is_expired:
264            session_token.expire_action()
265            clear_source_flow_session(self.request)
266            return None
267        plan = session_token.plan
268        resume_config: MatchFailureConfig | None = plan.context.get(
269            PLAN_CONTEXT_SOURCE_MATCH_FAILURE_CONFIG
270        )
271        current_stage = plan.bindings[0].stage if plan.bindings else None
272        if not resume_config or not current_stage:
273            return None
274        if (
275            failure.reason not in resume_config.reasons
276            or resume_config.source_pk != str(self.source.pk)
277            or resume_config.stage_pk != str(current_stage.pk)
278            or getattr(current_stage, "source_id", None) != self.source.pk
279        ):
280            return None
281
282        plan.context.pop(PLAN_CONTEXT_SOURCE_MATCH_FAILURE_CONFIG, None)
283        plan.context.update(self.policy_context)
284        plan.context[PLAN_CONTEXT_SOURCE_MATCH_FAILURE] = failure
285        plan.context[PLAN_CONTEXT_IS_RESTORED] = session_token
286        response = plan.to_redirect(self.request, session_token.flow)
287        session_token.delete()
288        return response
289
290    def error_handler(self, error: Exception) -> HttpResponse:
291        """Handle any errors by returning an access denied stage"""
292        response = AccessDeniedResponse(self.request)
293        response.error_message = str(error)
294        if isinstance(error, FlowNonApplicableException):
295            response.policy_result = error.policy_result
296            response.error_message = error.messages
297        return response
298
299    def get_stages_to_append(self, flow: Flow) -> list[Stage]:
300        """Hook to override stages which are appended to the flow"""
301        return [
302            in_memory_stage(PostSourceStage),
303        ]
304
305    def _prepare_flow(
306        self,
307        flow: Flow | None,
308        connection: UserSourceConnection,
309        stages: list[StageView] | None = None,
310        **flow_context,
311    ) -> HttpResponse:
312        """Prepare Authentication Plan, redirect user FlowExecutor"""
313        # Ensure redirect is carried through when user was trying to
314        # authorize application
315        final_redirect = self.request.session.get(SESSION_KEY_GET, {}).get(
316            NEXT_ARG_NAME, "authentik_core:if-user"
317        )
318        flow_context.update(
319            {
320                # Since we authenticate the user by their token, they have no backend set
321                PLAN_CONTEXT_AUTHENTICATION_BACKEND: BACKEND_INBUILT,
322                PLAN_CONTEXT_SSO: True,
323                PLAN_CONTEXT_SOURCE: self.source,
324                PLAN_CONTEXT_SOURCES_CONNECTION: connection,
325                PLAN_CONTEXT_SOURCE_GROUPS: self.groups_properties,
326            }
327        )
328        flow_context.update(self.policy_context)
329        flow_context.setdefault(PLAN_CONTEXT_REDIRECT, final_redirect)
330        if self.is_user_switch_add_user:
331            flow_context[PLAN_CONTEXT_USER_SWITCH_ADD_USER] = True
332
333        if not flow:
334            # We only check for the flow token here if we don't have a flow, otherwise we rely on
335            # SESSION_KEY_SOURCE_FLOW_STAGES to delegate the usage of this token and dynamically add
336            # stages that deal with this token to return to another flow
337            if SESSION_KEY_OVERRIDE_FLOW_TOKEN in self.request.session:
338                token: FlowToken = self.request.session.get(SESSION_KEY_OVERRIDE_FLOW_TOKEN)
339                self._logger.info(
340                    "Replacing source flow with overridden flow", flow=token.flow.slug
341                )
342                plan = token.plan
343                plan.context[PLAN_CONTEXT_IS_RESTORED] = token
344                plan.context.update(flow_context)
345                for stage in self.get_stages_to_append(flow):
346                    plan.append_stage(stage)
347                if stages:
348                    for stage in stages:
349                        plan.append_stage(stage)
350                redirect = plan.to_redirect(self.request, token.flow)
351                token.delete()
352                return redirect
353            return bad_request_message(
354                self.request,
355                _("Configured flow does not exist."),
356            )
357        # We run the Flow planner here so we can pass the Pending user in the context
358        planner = FlowPlanner(flow)
359        # We append some stages so the initial flow we get might be empty
360        planner.allow_empty_flows = True
361        planner.use_cache = False
362        plan = planner.plan(self.request, flow_context)
363        for stage in self.get_stages_to_append(flow):
364            plan.append_stage(stage)
365        plan.append_stage(
366            in_memory_stage(GroupUpdateStage, group_connection_type=self.group_connection_type)
367        )
368        if stages:
369            for stage in stages:
370                plan.append_stage(stage)
371        for stage in self.request.session.get(SESSION_KEY_SOURCE_FLOW_STAGES, []):
372            plan.append_stage(stage)
373        plan.context.update(self.request.session.get(SESSION_KEY_SOURCE_FLOW_CONTEXT, {}))
374        return plan.to_redirect(self.request, flow)
375
376    def handle_auth(
377        self,
378        connection: UserSourceConnection,
379    ) -> HttpResponse:
380        """Login user and redirect."""
381        return self._prepare_flow(
382            self.source.authentication_flow,
383            connection,
384            stages=[
385                in_memory_stage(
386                    MessageStage,
387                    message=_("Successfully authenticated with {source}!").format(
388                        source=self.source.name
389                    ),
390                )
391            ],
392            **{
393                PLAN_CONTEXT_PENDING_USER: connection.user,
394                PLAN_CONTEXT_PROMPT: delete_none_values(self.user_properties),
395                PLAN_CONTEXT_USER_PATH: self.source.get_user_path(),
396            },
397        )
398
399    def handle_existing_link(
400        self,
401        connection: UserSourceConnection,
402    ) -> HttpResponse:
403        """Handler when the user was already authenticated and linked an external source
404        to their account."""
405        # When request isn't authenticated we jump straight to auth
406        if not self.request.user.is_authenticated or self.is_user_switch_add_user:
407            return self.handle_auth(connection)
408        # When an override flow token exists we actually still use a flow for link
409        # to continue the existing flow we came from
410        if SESSION_KEY_OVERRIDE_FLOW_TOKEN in self.request.session:
411            return self._prepare_flow(None, connection)
412        connection.save()
413        Event.new(
414            EventAction.SOURCE_LINKED,
415            message="Linked Source",
416            source=self.source,
417        ).from_http(self.request)
418        messages.success(
419            self.request,
420            _("Successfully linked {source}!").format(source=self.source.name),
421        )
422        return redirect(
423            reverse(
424                "authentik_core:if-user",
425            )
426            + "settings/sources"
427        )
428
429    def handle_enroll(
430        self,
431        connection: UserSourceConnection,
432    ) -> HttpResponse:
433        """User was not authenticated and previous request was not authenticated."""
434        # We run the Flow planner here so we can pass the Pending user in the context
435        if not self.source.enrollment_flow:
436            self._logger.warning("source has no enrollment flow")
437            return bad_request_message(
438                self.request,
439                _("Source is not configured for enrollment."),
440            )
441        return self._prepare_flow(
442            self.source.enrollment_flow,
443            connection,
444            stages=[
445                in_memory_stage(
446                    MessageStage,
447                    message=_("Successfully authenticated with {source}!").format(
448                        source=self.source.name
449                    ),
450                )
451            ],
452            **{
453                PLAN_CONTEXT_PROMPT: delete_none_values(self.user_properties),
454                PLAN_CONTEXT_USER_PATH: self.source.get_user_path(),
455            },
456        )

Help sources decide what they should do after authorization. Based on source settings and previous connections, authenticate the user, enroll a new user, link to an existing user or deny the request.

SourceFlowManager( source: authentik.core.models.Source, request: django.http.request.HttpRequest, identifier: str, user_info: dict[str, typing.Any], policy_context: dict[str, typing.Any])
115    def __init__(
116        self,
117        source: Source,
118        request: HttpRequest,
119        identifier: str,
120        user_info: dict[str, Any],
121        policy_context: dict[str, Any],
122    ) -> None:
123        self.source = source
124        self.mapper = SourceMapper(self.source)
125        self.matcher = SourceMatcher(
126            self.source, self.user_connection_type, self.group_connection_type
127        )
128        self.request = request
129        self.identifier = identifier
130        self.user_info = user_info
131        self._logger = get_logger().bind(source=source, identifier=identifier)
132        self.policy_context = policy_context
133        # The source was started from "Add user", so the login must add another user to this
134        # browser instead of linking to or replacing the current user.
135        self.is_user_switch_add_user = bool(request.session.pop(SESSION_KEY_ADD_USER, False))
136
137        self.user_properties = self.mapper.build_object_properties(
138            object_type=User, request=request, user=None, **self.user_info
139        )
140        groups_manager = self.mapper.get_manager(Group, ["group_id", *self.user_info.keys()])
141        self.groups_properties = {
142            group_id: self.mapper.build_object_properties(
143                object_type=Group,
144                manager=groups_manager,
145                request=request,
146                user=None,
147                group_id=group_id,
148                **self.user_info,
149            )
150            for group_id in self._keyable_group_ids(self.user_properties.setdefault("groups", []))
151        }
152        del self.user_properties["groups"]
request: django.http.request.HttpRequest
identifier: str
user_connection_type: type[authentik.core.models.UserSourceConnection]
group_connection_type: type[authentik.core.models.GroupSourceConnection]
user_info: dict[str, typing.Any]
policy_context: dict[str, typing.Any]
user_properties: dict[str, typing.Any | dict[str, typing.Any]]
groups_properties: dict[str, dict[str, typing.Any | dict[str, typing.Any]]]
is_user_switch_add_user
def get_action( self, **kwargs) -> tuple[authentik.core.sources.matcher.Action, authentik.core.models.UserSourceConnection | None]:
185    def get_action(self, **kwargs) -> tuple[Action, UserSourceConnection | None]:  # noqa: PLR0911
186        """decide which action should be taken"""
187        # When request is authenticated, always link
188        if self.request.user.is_authenticated and not self.is_user_switch_add_user:
189            new_connection = self.user_connection_type(
190                source=self.source, identifier=self.identifier
191            )
192            new_connection.user = self.request.user
193            new_connection = self.update_user_connection(new_connection, **kwargs)
194            if existing := self.user_connection_type.objects.filter(
195                source=self.source, identifier=self.identifier
196            ).first():
197                existing = self.update_user_connection(existing, **kwargs)
198                return Action.AUTH, existing
199            return Action.LINK, new_connection
200
201        action, connection = self.matcher.get_user_action(self.identifier, self.user_properties)
202        if connection:
203            connection = self.update_user_connection(connection, **kwargs)
204        return action, connection

decide which action should be taken

def update_user_connection( self, connection: authentik.core.models.UserSourceConnection, **kwargs) -> authentik.core.models.UserSourceConnection:
206    def update_user_connection(
207        self, connection: UserSourceConnection, **kwargs
208    ) -> UserSourceConnection:  # pragma: no cover
209        """Optionally make changes to the user connection after it is looked up/created."""
210        return connection

Optionally make changes to the user connection after it is looked up/created.

def get_flow(self, **kwargs) -> django.http.response.HttpResponse:
212    def get_flow(self, **kwargs) -> HttpResponse:
213        """Get the flow response based on user_matching_mode"""
214        try:
215            action, connection = self.get_action(**kwargs)
216        except IntegrityError as exc:
217            self._logger.warning("failed to get action", exc=exc)
218            return redirect(reverse("authentik_core:root-redirect"))
219        self._logger.debug("get_action", action=action, connection=connection)
220        try:
221            if connection:
222                if action == Action.LINK:
223                    self._logger.debug("Linking existing user")
224                    return self.handle_existing_link(connection)
225                if action == Action.AUTH:
226                    self._logger.debug("Handling auth user")
227                    return self.handle_auth(connection)
228                if action == Action.ENROLL:
229                    if self.is_user_switch_add_user:
230                        return self.error_handler(
231                            TracingIgnoredException(
232                                _("New users can't enroll while adding a user.")
233                            )
234                        )
235                    self._logger.debug("Handling enrollment of new user")
236                    return self.handle_enroll(connection)
237            if action == Action.DENY and self.matcher.failure:
238                response = self.handle_match_failure(self.matcher.failure)
239                if response:
240                    return response
241        except FlowNonApplicableException as exc:
242            self._logger.warning("Flow non applicable", exc=exc)
243            return self.error_handler(exc)
244        # Default case, assume deny
245        error = Exception(
246            _(
247                "Request to authenticate with {source} has been denied. Please authenticate "
248                "with the source you've previously signed up with."
249            ).format(source=self.source.name),
250        )
251        return self.error_handler(error)

Get the flow response based on user_matching_mode

def handle_match_failure( self, failure: authentik.core.sources.matcher.MatchFailure) -> django.http.response.HttpResponse | None:
253    def handle_match_failure(self, failure: MatchFailure) -> HttpResponse | None:
254        """Resume an opted-in Source Stage after a configured matching failure."""
255        session_token: FlowToken = self.request.session.get(SESSION_KEY_OVERRIDE_FLOW_TOKEN)
256        if not session_token:
257            return None
258        try:
259            session_token.refresh_from_db()
260        except FlowToken.DoesNotExist:
261            clear_source_flow_session(self.request)
262            return None
263        if session_token.is_expired:
264            session_token.expire_action()
265            clear_source_flow_session(self.request)
266            return None
267        plan = session_token.plan
268        resume_config: MatchFailureConfig | None = plan.context.get(
269            PLAN_CONTEXT_SOURCE_MATCH_FAILURE_CONFIG
270        )
271        current_stage = plan.bindings[0].stage if plan.bindings else None
272        if not resume_config or not current_stage:
273            return None
274        if (
275            failure.reason not in resume_config.reasons
276            or resume_config.source_pk != str(self.source.pk)
277            or resume_config.stage_pk != str(current_stage.pk)
278            or getattr(current_stage, "source_id", None) != self.source.pk
279        ):
280            return None
281
282        plan.context.pop(PLAN_CONTEXT_SOURCE_MATCH_FAILURE_CONFIG, None)
283        plan.context.update(self.policy_context)
284        plan.context[PLAN_CONTEXT_SOURCE_MATCH_FAILURE] = failure
285        plan.context[PLAN_CONTEXT_IS_RESTORED] = session_token
286        response = plan.to_redirect(self.request, session_token.flow)
287        session_token.delete()
288        return response

Resume an opted-in Source Stage after a configured matching failure.

def error_handler(self, error: Exception) -> django.http.response.HttpResponse:
290    def error_handler(self, error: Exception) -> HttpResponse:
291        """Handle any errors by returning an access denied stage"""
292        response = AccessDeniedResponse(self.request)
293        response.error_message = str(error)
294        if isinstance(error, FlowNonApplicableException):
295            response.policy_result = error.policy_result
296            response.error_message = error.messages
297        return response

Handle any errors by returning an access denied stage

def get_stages_to_append( self, flow: authentik.flows.models.Flow) -> list[authentik.flows.models.Stage]:
299    def get_stages_to_append(self, flow: Flow) -> list[Stage]:
300        """Hook to override stages which are appended to the flow"""
301        return [
302            in_memory_stage(PostSourceStage),
303        ]

Hook to override stages which are appended to the flow

def handle_auth( self, connection: authentik.core.models.UserSourceConnection) -> django.http.response.HttpResponse:
376    def handle_auth(
377        self,
378        connection: UserSourceConnection,
379    ) -> HttpResponse:
380        """Login user and redirect."""
381        return self._prepare_flow(
382            self.source.authentication_flow,
383            connection,
384            stages=[
385                in_memory_stage(
386                    MessageStage,
387                    message=_("Successfully authenticated with {source}!").format(
388                        source=self.source.name
389                    ),
390                )
391            ],
392            **{
393                PLAN_CONTEXT_PENDING_USER: connection.user,
394                PLAN_CONTEXT_PROMPT: delete_none_values(self.user_properties),
395                PLAN_CONTEXT_USER_PATH: self.source.get_user_path(),
396            },
397        )

Login user and redirect.

def handle_enroll( self, connection: authentik.core.models.UserSourceConnection) -> django.http.response.HttpResponse:
429    def handle_enroll(
430        self,
431        connection: UserSourceConnection,
432    ) -> HttpResponse:
433        """User was not authenticated and previous request was not authenticated."""
434        # We run the Flow planner here so we can pass the Pending user in the context
435        if not self.source.enrollment_flow:
436            self._logger.warning("source has no enrollment flow")
437            return bad_request_message(
438                self.request,
439                _("Source is not configured for enrollment."),
440            )
441        return self._prepare_flow(
442            self.source.enrollment_flow,
443            connection,
444            stages=[
445                in_memory_stage(
446                    MessageStage,
447                    message=_("Successfully authenticated with {source}!").format(
448                        source=self.source.name
449                    ),
450                )
451            ],
452            **{
453                PLAN_CONTEXT_PROMPT: delete_none_values(self.user_properties),
454                PLAN_CONTEXT_USER_PATH: self.source.get_user_path(),
455            },
456        )

User was not authenticated and previous request was not authenticated.

class GroupUpdateStage(authentik.flows.stage.StageView):
459class GroupUpdateStage(StageView):
460    """Dynamically injected stage which updates the user after enrollment/authentication."""
461
462    def handle_group(
463        self, group_id: str, group_properties: dict[str, Any | dict[str, Any]]
464    ) -> Group | None:
465        action, connection = self.matcher.get_group_action(group_id, group_properties)
466        if action == Action.ENROLL:
467            group = Group.objects.create(**group_properties)
468            connection.group = group
469            connection.save()
470            return group
471        elif action in (Action.LINK, Action.AUTH):
472            group = connection.group
473            group.update_attributes(group_properties)
474            connection.save()
475            return group
476
477        return None
478
479    def handle_groups(self) -> bool:
480        self.source: Source = self.executor.plan.context[PLAN_CONTEXT_SOURCE]
481        self.user: User = self.executor.plan.context[PLAN_CONTEXT_PENDING_USER]
482        self.group_connection_type: GroupSourceConnection = (
483            self.executor.current_stage.group_connection_type
484        )
485        self.matcher = SourceMatcher(self.source, None, self.group_connection_type)
486
487        raw_groups: dict[str, dict[str, Any | dict[str, Any]]] = self.executor.plan.context[
488            PLAN_CONTEXT_SOURCE_GROUPS
489        ]
490        groups: list[Group] = []
491
492        for group_id, group_properties in raw_groups.items():
493            group = self.handle_group(group_id, group_properties)
494            if not group:
495                return False
496            groups.append(group)
497
498        with transaction.atomic():
499            self.user.groups.remove(
500                *self.user.groups.filter(groupsourceconnection__source=self.source)
501            )
502            self.user.groups.add(*groups)
503
504        return True
505
506    def get(self, request: HttpRequest, *args, **kwargs) -> HttpResponse:
507        """Stage used after the user has been enrolled to sync their groups from source data"""
508        if self.handle_groups():
509            return self.executor.stage_ok()
510        else:
511            return self.executor.stage_invalid("Failed to update groups. Please try again later.")
512
513    def post(self, request: HttpRequest) -> HttpResponse:
514        """Wrapper for post requests"""
515        return self.get(request)

Dynamically injected stage which updates the user after enrollment/authentication.

def handle_group( self, group_id: str, group_properties: dict[str, typing.Any | dict[str, typing.Any]]) -> authentik.core.models.Group | None:
462    def handle_group(
463        self, group_id: str, group_properties: dict[str, Any | dict[str, Any]]
464    ) -> Group | None:
465        action, connection = self.matcher.get_group_action(group_id, group_properties)
466        if action == Action.ENROLL:
467            group = Group.objects.create(**group_properties)
468            connection.group = group
469            connection.save()
470            return group
471        elif action in (Action.LINK, Action.AUTH):
472            group = connection.group
473            group.update_attributes(group_properties)
474            connection.save()
475            return group
476
477        return None
def handle_groups(self) -> bool:
479    def handle_groups(self) -> bool:
480        self.source: Source = self.executor.plan.context[PLAN_CONTEXT_SOURCE]
481        self.user: User = self.executor.plan.context[PLAN_CONTEXT_PENDING_USER]
482        self.group_connection_type: GroupSourceConnection = (
483            self.executor.current_stage.group_connection_type
484        )
485        self.matcher = SourceMatcher(self.source, None, self.group_connection_type)
486
487        raw_groups: dict[str, dict[str, Any | dict[str, Any]]] = self.executor.plan.context[
488            PLAN_CONTEXT_SOURCE_GROUPS
489        ]
490        groups: list[Group] = []
491
492        for group_id, group_properties in raw_groups.items():
493            group = self.handle_group(group_id, group_properties)
494            if not group:
495                return False
496            groups.append(group)
497
498        with transaction.atomic():
499            self.user.groups.remove(
500                *self.user.groups.filter(groupsourceconnection__source=self.source)
501            )
502            self.user.groups.add(*groups)
503
504        return True
def get( self, request: django.http.request.HttpRequest, *args, **kwargs) -> django.http.response.HttpResponse:
506    def get(self, request: HttpRequest, *args, **kwargs) -> HttpResponse:
507        """Stage used after the user has been enrolled to sync their groups from source data"""
508        if self.handle_groups():
509            return self.executor.stage_ok()
510        else:
511            return self.executor.stage_invalid("Failed to update groups. Please try again later.")

Stage used after the user has been enrolled to sync their groups from source data

def post( self, request: django.http.request.HttpRequest) -> django.http.response.HttpResponse:
513    def post(self, request: HttpRequest) -> HttpResponse:
514        """Wrapper for post requests"""
515        return self.get(request)

Wrapper for post requests