authentik.stages.user_login.stage

Login stage logic

  1"""Login stage logic"""
  2
  3from datetime import datetime, timedelta
  4from hashlib import sha256
  5
  6from django.conf import settings
  7from django.contrib import messages
  8from django.contrib.auth import login
  9from django.http import HttpRequest, HttpResponse
 10from django.utils.translation import gettext as _
 11from jwt import PyJWTError, decode, encode
 12from rest_framework.fields import BooleanField, CharField
 13
 14from authentik.core import user_switching
 15from authentik.core.models import AuthenticatedSession, Session, User, UserTypes
 16from authentik.core.sessions import SessionStore
 17from authentik.events.middleware import audit_ignore
 18from authentik.flows.challenge import ChallengeResponse, WithUserInfoChallenge
 19from authentik.flows.planner import (
 20    PLAN_CONTEXT_PENDING_USER,
 21    PLAN_CONTEXT_USER_SWITCH_ADD_USER,
 22    PLAN_CONTEXT_USER_SWITCH_TARGET_SESSION,
 23)
 24from authentik.flows.stage import ChallengeStageView
 25from authentik.flows.views.executor import SESSION_KEY_GET, SESSION_KEY_PLAN
 26from authentik.lib.tracing import active_tracer
 27from authentik.lib.utils.time import timedelta_from_string
 28from authentik.root.install_id import get_install_id
 29from authentik.root.middleware import ClientIPMiddleware
 30from authentik.stages.password import BACKEND_INBUILT
 31from authentik.stages.password.stage import (
 32    PLAN_CONTEXT_AUTHENTICATION_BACKEND,
 33    PLAN_CONTEXT_METHOD_ARGS,
 34)
 35from authentik.stages.user_login.middleware import (
 36    SESSION_KEY_BINDING_GEO,
 37    SESSION_KEY_BINDING_NET,
 38)
 39from authentik.stages.user_login.models import UserLoginStage
 40
 41COOKIE_NAME_KNOWN_DEVICE = "authentik_device"
 42
 43PLAN_CONTEXT_METHOD_ARGS_KNOWN_DEVICE = "known_device"
 44
 45
 46class UserLoginChallenge(WithUserInfoChallenge):
 47    """Empty challenge"""
 48
 49    component = CharField(default="ak-stage-user-login")
 50
 51
 52class UserLoginChallengeResponse(ChallengeResponse):
 53    """User login challenge"""
 54
 55    component = CharField(default="ak-stage-user-login")
 56
 57    remember_me = BooleanField(required=True)
 58
 59
 60class UserLoginStageView(ChallengeStageView):
 61    """Finalize Authentication flow by logging the user in"""
 62
 63    response_class = UserLoginChallengeResponse
 64
 65    def get_challenge(self, *args, **kwargs) -> UserLoginChallenge:
 66        return UserLoginChallenge(data={})
 67
 68    def dispatch(self, request: HttpRequest) -> HttpResponse:
 69        """Check for remember_me, and do login"""
 70        stage: UserLoginStage = self.executor.current_stage
 71        if timedelta_from_string(stage.remember_me_offset).total_seconds() > 0:
 72            return super().dispatch(request)
 73        return self.do_login(request)
 74
 75    def challenge_valid(self, response: UserLoginChallengeResponse) -> HttpResponse:
 76        return self.do_login(self.request, response.validated_data["remember_me"])
 77
 78    def set_session_duration(self, remember: bool) -> timedelta:
 79        """Update the sessions' expiry"""
 80        delta = timedelta_from_string(self.executor.current_stage.session_duration)
 81        if remember:
 82            offset = timedelta_from_string(self.executor.current_stage.remember_me_offset)
 83            delta = delta + offset
 84        if delta.total_seconds() == 0:
 85            self.request.session.set_expiry(0)
 86        else:
 87            self.request.session.set_expiry(delta)
 88        return delta
 89
 90    def set_session_ip(self):
 91        """Set the sessions' last IP and session bindings"""
 92        stage: UserLoginStage = self.executor.current_stage
 93
 94        self.request.session[self.request.session.model.Keys.LAST_IP] = (
 95            ClientIPMiddleware.get_client_ip(self.request)
 96        )
 97        self.request.session[SESSION_KEY_BINDING_NET] = stage.network_binding
 98        self.request.session[SESSION_KEY_BINDING_GEO] = stage.geoip_binding
 99
100    # FIXME: identical function in authenticator_validate
101    @property
102    def cookie_jwt_key(self) -> str:
103        """Signing key for Known-device Cookie for this stage"""
104        return sha256(
105            f"{get_install_id()}:{self.executor.current_stage.pk.hex}".encode("ascii")
106        ).hexdigest()
107
108    def set_known_device_cookie(self, user: User):
109        """Set a cookie, valid longer than the session, which denotes that this user
110        has logged in on this device before."""
111        delta = timedelta_from_string(self.executor.current_stage.remember_device)
112        response = self.executor.stage_ok()
113        if delta.total_seconds() < 1:
114            return response
115        expiry = datetime.now() + delta
116        cookie_payload = {
117            "sub": user.uid,
118            "exp": expiry.timestamp(),
119        }
120        cookie = encode(cookie_payload, self.cookie_jwt_key)
121        response.set_cookie(
122            COOKIE_NAME_KNOWN_DEVICE,
123            cookie,
124            expires=expiry,
125            path=settings.SESSION_COOKIE_PATH,
126            domain=settings.SESSION_COOKIE_DOMAIN,
127            samesite=settings.SESSION_COOKIE_SAMESITE,
128        )
129        return response
130
131    def is_known_device(self, user: User):
132        """Returns `True` if the login happened on a "known" device, by the same user."""
133        client_ip = ClientIPMiddleware.get_client_ip(self.request)
134        if AuthenticatedSession.objects.filter(session__last_ip=client_ip, user=user).exists():
135            return True
136        if COOKIE_NAME_KNOWN_DEVICE not in self.request.COOKIES:
137            return False
138        try:
139            payload = decode(
140                self.request.COOKIES[COOKIE_NAME_KNOWN_DEVICE], self.cookie_jwt_key, ["HS256"]
141            )
142            if payload["sub"] == user.uid:
143                return True
144            return False
145        except (PyJWTError, ValueError, TypeError) as exc:
146            self.logger.info("eh", exc=exc)
147            return False
148
149    def _start_new_session(self) -> None:
150        """Move the flow to a new session while preserving the current login."""
151        old_session = self.request.session
152        flow_query_params = old_session.get(SESSION_KEY_GET)
153        # Move the active plan so audit events keep context and old logins cannot resume it.
154        old_session.pop(SESSION_KEY_PLAN, None)
155        old_session.save()
156        session_keys = old_session.model.Keys
157        self.request.session = SessionStore(
158            last_ip=old_session.get(session_keys.LAST_IP),
159            last_user_agent=old_session.get(session_keys.LAST_USER_AGENT, ""),
160        )
161        self.request.session[SESSION_KEY_PLAN] = self.executor.plan
162        if flow_query_params is not None:
163            self.request.session[SESSION_KEY_GET] = flow_query_params
164
165    def do_login(self, request: HttpRequest, remember: bool | None = None) -> HttpResponse:
166        """Attach the currently pending user to the current session.
167        `remember` Argument should be `None` if not configured, otherwise set to `True`/`False`
168        representative of the user's choice."""
169        if PLAN_CONTEXT_PENDING_USER not in self.executor.plan.context:
170            message = _("No Pending user to login.")
171            messages.error(request, message)
172            self.logger.warning(message)
173            return self.executor.stage_invalid()
174        backend = self.executor.plan.context.get(
175            PLAN_CONTEXT_AUTHENTICATION_BACKEND, BACKEND_INBUILT
176        )
177        user: User = self.executor.plan.context[PLAN_CONTEXT_PENDING_USER]
178        # This should realistically never happen: even though the
179        # identification stage returns a fake user, any kind of authentication
180        # would fail because the user doesn't exist. This is just a fallback
181        # for a misconfiguration to prevent an exception.
182        if user.pk is None:
183            self.logger.debug("pending user is not saved, refusing to log in")
184            return self.executor.stage_invalid()
185        if PLAN_CONTEXT_USER_SWITCH_TARGET_SESSION in self.executor.plan.context:
186            target_session_id = self.executor.plan.context[PLAN_CONTEXT_USER_SWITCH_TARGET_SESSION]
187            target_session = (
188                user_switching.target_sessions(self.request, user.pk, target_session_id)
189                .select_related("session", "user")
190                .first()
191                if target_session_id
192                else None
193            )
194            if not target_session:
195                message = _("The selected session is no longer available. Please try again.")
196                self.logger.warning(message)
197                return self.executor.stage_invalid(message)
198            user = target_session.user
199        if not user.is_active:
200            self.logger.warning("User is not active, login will not work.")
201            return self.executor.stage_invalid()
202        # The account switcher is only available in the User interface, which non-internal
203        # users can't access, so adding them would leave the other logins unreachable.
204        if (
205            PLAN_CONTEXT_USER_SWITCH_ADD_USER in self.executor.plan.context
206            and user.type != UserTypes.INTERNAL
207        ):
208            message = _("Only internal users can be added to user switching.")
209            self.logger.warning(message, user=user.username)
210            return self.executor.stage_invalid(message)
211        is_user_switch_login = (
212            PLAN_CONTEXT_USER_SWITCH_ADD_USER in self.executor.plan.context
213            or PLAN_CONTEXT_USER_SWITCH_TARGET_SESSION in self.executor.plan.context
214        )
215        user_switching_token = getattr(self.request, "user_switching_token", None)
216        if (
217            is_user_switch_login
218            and self.request.user.is_authenticated
219            and self.request.user.pk != user.pk
220        ):
221            self._start_new_session()
222            if user_switching_token:
223                Session.objects.filter(
224                    authenticatedsession__user=user,
225                    authenticatedsession__user_switching_session_id=user_switching_token,
226                ).delete()
227        delta = self.set_session_duration(bool(remember))
228        self.set_session_ip()
229        # Check if the login request is coming from a known device
230        self.executor.plan.context.setdefault(PLAN_CONTEXT_METHOD_ARGS, {})
231        self.executor.plan.context[PLAN_CONTEXT_METHOD_ARGS].setdefault(
232            PLAN_CONTEXT_METHOD_ARGS_KNOWN_DEVICE, self.is_known_device(user)
233        )
234        # the `user_logged_in` signal will update the user to write the `last_login` field
235        # which we don't want to log as we already have a dedicated login event
236        with (
237            audit_ignore(),
238            active_tracer().start_span(
239                op="authentik.stages.user_login.login",
240                name="User login",
241            ),
242        ):
243            login(
244                self.request,
245                user,
246                backend=backend,
247            )
248        self.logger.debug(
249            "Logged in",
250            backend=backend,
251            user=user.username,
252            flow_slug=self.executor.flow.slug,
253            session_duration=delta,
254        )
255        if self.executor.current_stage.terminate_other_sessions:
256            Session.objects.filter(
257                authenticatedsession__user=user,
258            ).exclude(session_key=self.request.session.session_key).delete()
259        if remember is None:
260            return self.set_known_device_cookie(user)
261        return self.executor.stage_ok()
PLAN_CONTEXT_METHOD_ARGS_KNOWN_DEVICE = 'known_device'
class UserLoginChallenge(authentik.flows.challenge.WithUserInfoChallenge):
47class UserLoginChallenge(WithUserInfoChallenge):
48    """Empty challenge"""
49
50    component = CharField(default="ak-stage-user-login")

Empty challenge

component
class UserLoginChallengeResponse(authentik.flows.challenge.ChallengeResponse):
53class UserLoginChallengeResponse(ChallengeResponse):
54    """User login challenge"""
55
56    component = CharField(default="ak-stage-user-login")
57
58    remember_me = BooleanField(required=True)

User login challenge

component
remember_me
class UserLoginStageView(authentik.flows.stage.ChallengeStageView):
 61class UserLoginStageView(ChallengeStageView):
 62    """Finalize Authentication flow by logging the user in"""
 63
 64    response_class = UserLoginChallengeResponse
 65
 66    def get_challenge(self, *args, **kwargs) -> UserLoginChallenge:
 67        return UserLoginChallenge(data={})
 68
 69    def dispatch(self, request: HttpRequest) -> HttpResponse:
 70        """Check for remember_me, and do login"""
 71        stage: UserLoginStage = self.executor.current_stage
 72        if timedelta_from_string(stage.remember_me_offset).total_seconds() > 0:
 73            return super().dispatch(request)
 74        return self.do_login(request)
 75
 76    def challenge_valid(self, response: UserLoginChallengeResponse) -> HttpResponse:
 77        return self.do_login(self.request, response.validated_data["remember_me"])
 78
 79    def set_session_duration(self, remember: bool) -> timedelta:
 80        """Update the sessions' expiry"""
 81        delta = timedelta_from_string(self.executor.current_stage.session_duration)
 82        if remember:
 83            offset = timedelta_from_string(self.executor.current_stage.remember_me_offset)
 84            delta = delta + offset
 85        if delta.total_seconds() == 0:
 86            self.request.session.set_expiry(0)
 87        else:
 88            self.request.session.set_expiry(delta)
 89        return delta
 90
 91    def set_session_ip(self):
 92        """Set the sessions' last IP and session bindings"""
 93        stage: UserLoginStage = self.executor.current_stage
 94
 95        self.request.session[self.request.session.model.Keys.LAST_IP] = (
 96            ClientIPMiddleware.get_client_ip(self.request)
 97        )
 98        self.request.session[SESSION_KEY_BINDING_NET] = stage.network_binding
 99        self.request.session[SESSION_KEY_BINDING_GEO] = stage.geoip_binding
100
101    # FIXME: identical function in authenticator_validate
102    @property
103    def cookie_jwt_key(self) -> str:
104        """Signing key for Known-device Cookie for this stage"""
105        return sha256(
106            f"{get_install_id()}:{self.executor.current_stage.pk.hex}".encode("ascii")
107        ).hexdigest()
108
109    def set_known_device_cookie(self, user: User):
110        """Set a cookie, valid longer than the session, which denotes that this user
111        has logged in on this device before."""
112        delta = timedelta_from_string(self.executor.current_stage.remember_device)
113        response = self.executor.stage_ok()
114        if delta.total_seconds() < 1:
115            return response
116        expiry = datetime.now() + delta
117        cookie_payload = {
118            "sub": user.uid,
119            "exp": expiry.timestamp(),
120        }
121        cookie = encode(cookie_payload, self.cookie_jwt_key)
122        response.set_cookie(
123            COOKIE_NAME_KNOWN_DEVICE,
124            cookie,
125            expires=expiry,
126            path=settings.SESSION_COOKIE_PATH,
127            domain=settings.SESSION_COOKIE_DOMAIN,
128            samesite=settings.SESSION_COOKIE_SAMESITE,
129        )
130        return response
131
132    def is_known_device(self, user: User):
133        """Returns `True` if the login happened on a "known" device, by the same user."""
134        client_ip = ClientIPMiddleware.get_client_ip(self.request)
135        if AuthenticatedSession.objects.filter(session__last_ip=client_ip, user=user).exists():
136            return True
137        if COOKIE_NAME_KNOWN_DEVICE not in self.request.COOKIES:
138            return False
139        try:
140            payload = decode(
141                self.request.COOKIES[COOKIE_NAME_KNOWN_DEVICE], self.cookie_jwt_key, ["HS256"]
142            )
143            if payload["sub"] == user.uid:
144                return True
145            return False
146        except (PyJWTError, ValueError, TypeError) as exc:
147            self.logger.info("eh", exc=exc)
148            return False
149
150    def _start_new_session(self) -> None:
151        """Move the flow to a new session while preserving the current login."""
152        old_session = self.request.session
153        flow_query_params = old_session.get(SESSION_KEY_GET)
154        # Move the active plan so audit events keep context and old logins cannot resume it.
155        old_session.pop(SESSION_KEY_PLAN, None)
156        old_session.save()
157        session_keys = old_session.model.Keys
158        self.request.session = SessionStore(
159            last_ip=old_session.get(session_keys.LAST_IP),
160            last_user_agent=old_session.get(session_keys.LAST_USER_AGENT, ""),
161        )
162        self.request.session[SESSION_KEY_PLAN] = self.executor.plan
163        if flow_query_params is not None:
164            self.request.session[SESSION_KEY_GET] = flow_query_params
165
166    def do_login(self, request: HttpRequest, remember: bool | None = None) -> HttpResponse:
167        """Attach the currently pending user to the current session.
168        `remember` Argument should be `None` if not configured, otherwise set to `True`/`False`
169        representative of the user's choice."""
170        if PLAN_CONTEXT_PENDING_USER not in self.executor.plan.context:
171            message = _("No Pending user to login.")
172            messages.error(request, message)
173            self.logger.warning(message)
174            return self.executor.stage_invalid()
175        backend = self.executor.plan.context.get(
176            PLAN_CONTEXT_AUTHENTICATION_BACKEND, BACKEND_INBUILT
177        )
178        user: User = self.executor.plan.context[PLAN_CONTEXT_PENDING_USER]
179        # This should realistically never happen: even though the
180        # identification stage returns a fake user, any kind of authentication
181        # would fail because the user doesn't exist. This is just a fallback
182        # for a misconfiguration to prevent an exception.
183        if user.pk is None:
184            self.logger.debug("pending user is not saved, refusing to log in")
185            return self.executor.stage_invalid()
186        if PLAN_CONTEXT_USER_SWITCH_TARGET_SESSION in self.executor.plan.context:
187            target_session_id = self.executor.plan.context[PLAN_CONTEXT_USER_SWITCH_TARGET_SESSION]
188            target_session = (
189                user_switching.target_sessions(self.request, user.pk, target_session_id)
190                .select_related("session", "user")
191                .first()
192                if target_session_id
193                else None
194            )
195            if not target_session:
196                message = _("The selected session is no longer available. Please try again.")
197                self.logger.warning(message)
198                return self.executor.stage_invalid(message)
199            user = target_session.user
200        if not user.is_active:
201            self.logger.warning("User is not active, login will not work.")
202            return self.executor.stage_invalid()
203        # The account switcher is only available in the User interface, which non-internal
204        # users can't access, so adding them would leave the other logins unreachable.
205        if (
206            PLAN_CONTEXT_USER_SWITCH_ADD_USER in self.executor.plan.context
207            and user.type != UserTypes.INTERNAL
208        ):
209            message = _("Only internal users can be added to user switching.")
210            self.logger.warning(message, user=user.username)
211            return self.executor.stage_invalid(message)
212        is_user_switch_login = (
213            PLAN_CONTEXT_USER_SWITCH_ADD_USER in self.executor.plan.context
214            or PLAN_CONTEXT_USER_SWITCH_TARGET_SESSION in self.executor.plan.context
215        )
216        user_switching_token = getattr(self.request, "user_switching_token", None)
217        if (
218            is_user_switch_login
219            and self.request.user.is_authenticated
220            and self.request.user.pk != user.pk
221        ):
222            self._start_new_session()
223            if user_switching_token:
224                Session.objects.filter(
225                    authenticatedsession__user=user,
226                    authenticatedsession__user_switching_session_id=user_switching_token,
227                ).delete()
228        delta = self.set_session_duration(bool(remember))
229        self.set_session_ip()
230        # Check if the login request is coming from a known device
231        self.executor.plan.context.setdefault(PLAN_CONTEXT_METHOD_ARGS, {})
232        self.executor.plan.context[PLAN_CONTEXT_METHOD_ARGS].setdefault(
233            PLAN_CONTEXT_METHOD_ARGS_KNOWN_DEVICE, self.is_known_device(user)
234        )
235        # the `user_logged_in` signal will update the user to write the `last_login` field
236        # which we don't want to log as we already have a dedicated login event
237        with (
238            audit_ignore(),
239            active_tracer().start_span(
240                op="authentik.stages.user_login.login",
241                name="User login",
242            ),
243        ):
244            login(
245                self.request,
246                user,
247                backend=backend,
248            )
249        self.logger.debug(
250            "Logged in",
251            backend=backend,
252            user=user.username,
253            flow_slug=self.executor.flow.slug,
254            session_duration=delta,
255        )
256        if self.executor.current_stage.terminate_other_sessions:
257            Session.objects.filter(
258                authenticatedsession__user=user,
259            ).exclude(session_key=self.request.session.session_key).delete()
260        if remember is None:
261            return self.set_known_device_cookie(user)
262        return self.executor.stage_ok()

Finalize Authentication flow by logging the user in

response_class = <class 'UserLoginChallengeResponse'>
def get_challenge( self, *args, **kwargs) -> UserLoginChallenge:
66    def get_challenge(self, *args, **kwargs) -> UserLoginChallenge:
67        return UserLoginChallenge(data={})

Return the challenge that the client should solve

def dispatch( self, request: django.http.request.HttpRequest) -> django.http.response.HttpResponse:
69    def dispatch(self, request: HttpRequest) -> HttpResponse:
70        """Check for remember_me, and do login"""
71        stage: UserLoginStage = self.executor.current_stage
72        if timedelta_from_string(stage.remember_me_offset).total_seconds() > 0:
73            return super().dispatch(request)
74        return self.do_login(request)

Check for remember_me, and do login

def challenge_valid( self, response: UserLoginChallengeResponse) -> django.http.response.HttpResponse:
76    def challenge_valid(self, response: UserLoginChallengeResponse) -> HttpResponse:
77        return self.do_login(self.request, response.validated_data["remember_me"])

Callback when the challenge has the correct format

def set_session_duration(self, remember: bool) -> datetime.timedelta:
79    def set_session_duration(self, remember: bool) -> timedelta:
80        """Update the sessions' expiry"""
81        delta = timedelta_from_string(self.executor.current_stage.session_duration)
82        if remember:
83            offset = timedelta_from_string(self.executor.current_stage.remember_me_offset)
84            delta = delta + offset
85        if delta.total_seconds() == 0:
86            self.request.session.set_expiry(0)
87        else:
88            self.request.session.set_expiry(delta)
89        return delta

Update the sessions' expiry

def set_session_ip(self):
91    def set_session_ip(self):
92        """Set the sessions' last IP and session bindings"""
93        stage: UserLoginStage = self.executor.current_stage
94
95        self.request.session[self.request.session.model.Keys.LAST_IP] = (
96            ClientIPMiddleware.get_client_ip(self.request)
97        )
98        self.request.session[SESSION_KEY_BINDING_NET] = stage.network_binding
99        self.request.session[SESSION_KEY_BINDING_GEO] = stage.geoip_binding

Set the sessions' last IP and session bindings

cookie_jwt_key: str
102    @property
103    def cookie_jwt_key(self) -> str:
104        """Signing key for Known-device Cookie for this stage"""
105        return sha256(
106            f"{get_install_id()}:{self.executor.current_stage.pk.hex}".encode("ascii")
107        ).hexdigest()

Signing key for Known-device Cookie for this stage

def is_known_device(self, user: authentik.core.models.User):
132    def is_known_device(self, user: User):
133        """Returns `True` if the login happened on a "known" device, by the same user."""
134        client_ip = ClientIPMiddleware.get_client_ip(self.request)
135        if AuthenticatedSession.objects.filter(session__last_ip=client_ip, user=user).exists():
136            return True
137        if COOKIE_NAME_KNOWN_DEVICE not in self.request.COOKIES:
138            return False
139        try:
140            payload = decode(
141                self.request.COOKIES[COOKIE_NAME_KNOWN_DEVICE], self.cookie_jwt_key, ["HS256"]
142            )
143            if payload["sub"] == user.uid:
144                return True
145            return False
146        except (PyJWTError, ValueError, TypeError) as exc:
147            self.logger.info("eh", exc=exc)
148            return False

Returns True if the login happened on a "known" device, by the same user.

def do_login( self, request: django.http.request.HttpRequest, remember: bool | None = None) -> django.http.response.HttpResponse:
166    def do_login(self, request: HttpRequest, remember: bool | None = None) -> HttpResponse:
167        """Attach the currently pending user to the current session.
168        `remember` Argument should be `None` if not configured, otherwise set to `True`/`False`
169        representative of the user's choice."""
170        if PLAN_CONTEXT_PENDING_USER not in self.executor.plan.context:
171            message = _("No Pending user to login.")
172            messages.error(request, message)
173            self.logger.warning(message)
174            return self.executor.stage_invalid()
175        backend = self.executor.plan.context.get(
176            PLAN_CONTEXT_AUTHENTICATION_BACKEND, BACKEND_INBUILT
177        )
178        user: User = self.executor.plan.context[PLAN_CONTEXT_PENDING_USER]
179        # This should realistically never happen: even though the
180        # identification stage returns a fake user, any kind of authentication
181        # would fail because the user doesn't exist. This is just a fallback
182        # for a misconfiguration to prevent an exception.
183        if user.pk is None:
184            self.logger.debug("pending user is not saved, refusing to log in")
185            return self.executor.stage_invalid()
186        if PLAN_CONTEXT_USER_SWITCH_TARGET_SESSION in self.executor.plan.context:
187            target_session_id = self.executor.plan.context[PLAN_CONTEXT_USER_SWITCH_TARGET_SESSION]
188            target_session = (
189                user_switching.target_sessions(self.request, user.pk, target_session_id)
190                .select_related("session", "user")
191                .first()
192                if target_session_id
193                else None
194            )
195            if not target_session:
196                message = _("The selected session is no longer available. Please try again.")
197                self.logger.warning(message)
198                return self.executor.stage_invalid(message)
199            user = target_session.user
200        if not user.is_active:
201            self.logger.warning("User is not active, login will not work.")
202            return self.executor.stage_invalid()
203        # The account switcher is only available in the User interface, which non-internal
204        # users can't access, so adding them would leave the other logins unreachable.
205        if (
206            PLAN_CONTEXT_USER_SWITCH_ADD_USER in self.executor.plan.context
207            and user.type != UserTypes.INTERNAL
208        ):
209            message = _("Only internal users can be added to user switching.")
210            self.logger.warning(message, user=user.username)
211            return self.executor.stage_invalid(message)
212        is_user_switch_login = (
213            PLAN_CONTEXT_USER_SWITCH_ADD_USER in self.executor.plan.context
214            or PLAN_CONTEXT_USER_SWITCH_TARGET_SESSION in self.executor.plan.context
215        )
216        user_switching_token = getattr(self.request, "user_switching_token", None)
217        if (
218            is_user_switch_login
219            and self.request.user.is_authenticated
220            and self.request.user.pk != user.pk
221        ):
222            self._start_new_session()
223            if user_switching_token:
224                Session.objects.filter(
225                    authenticatedsession__user=user,
226                    authenticatedsession__user_switching_session_id=user_switching_token,
227                ).delete()
228        delta = self.set_session_duration(bool(remember))
229        self.set_session_ip()
230        # Check if the login request is coming from a known device
231        self.executor.plan.context.setdefault(PLAN_CONTEXT_METHOD_ARGS, {})
232        self.executor.plan.context[PLAN_CONTEXT_METHOD_ARGS].setdefault(
233            PLAN_CONTEXT_METHOD_ARGS_KNOWN_DEVICE, self.is_known_device(user)
234        )
235        # the `user_logged_in` signal will update the user to write the `last_login` field
236        # which we don't want to log as we already have a dedicated login event
237        with (
238            audit_ignore(),
239            active_tracer().start_span(
240                op="authentik.stages.user_login.login",
241                name="User login",
242            ),
243        ):
244            login(
245                self.request,
246                user,
247                backend=backend,
248            )
249        self.logger.debug(
250            "Logged in",
251            backend=backend,
252            user=user.username,
253            flow_slug=self.executor.flow.slug,
254            session_duration=delta,
255        )
256        if self.executor.current_stage.terminate_other_sessions:
257            Session.objects.filter(
258                authenticatedsession__user=user,
259            ).exclude(session_key=self.request.session.session_key).delete()
260        if remember is None:
261            return self.set_known_device_cookie(user)
262        return self.executor.stage_ok()

Attach the currently pending user to the current session. remember Argument should be None if not configured, otherwise set to True/False representative of the user's choice.