authentik.stages.email.stage

authentik multi-stage authentication engine

  1"""authentik multi-stage authentication engine"""
  2
  3import math
  4from datetime import UTC, datetime, timedelta
  5from hashlib import sha256
  6from uuid import uuid4
  7
  8from django.contrib import messages
  9from django.core.cache import cache
 10from django.http import HttpRequest, HttpResponse
 11from django.http.request import QueryDict
 12from django.template.exceptions import TemplateSyntaxError
 13from django.urls import reverse
 14from django.utils.text import slugify
 15from django.utils.timezone import now
 16from django.utils.translation import gettext as _
 17from django.utils.translation import override
 18from rest_framework.fields import CharField
 19from rest_framework.serializers import ValidationError
 20
 21from authentik.events.models import Event, EventAction
 22from authentik.flows.challenge import Challenge, ChallengeResponse
 23from authentik.flows.exceptions import StageInvalidException
 24from authentik.flows.models import FlowToken
 25from authentik.flows.planner import PLAN_CONTEXT_IS_RESTORED, PLAN_CONTEXT_PENDING_USER
 26from authentik.flows.stage import ChallengeStageView
 27from authentik.flows.views.executor import QS_KEY_TOKEN, QS_QUERY
 28from authentik.lib.utils.time import timedelta_from_string
 29from authentik.stages.email.flow import pickle_flow_token_for_email
 30from authentik.stages.email.models import EmailStage
 31from authentik.stages.email.tasks import send_mails
 32from authentik.stages.email.utils import TemplateEmailMessage
 33
 34EMAIL_RECOVERY_CACHE_KEY = "goauthentik.io/stages/email/stage/"
 35
 36PLAN_CONTEXT_EMAIL_SENT = "email_sent"
 37PLAN_CONTEXT_EMAIL_OVERRIDE = "email"
 38
 39
 40class EmailChallenge(Challenge):
 41    """Email challenge"""
 42
 43    component = CharField(default="ak-stage-email")
 44
 45
 46class EmailChallengeResponse(ChallengeResponse):
 47    """Email challenge resposen. No fields. This challenge is
 48    always declared invalid to give the user a chance to retry"""
 49
 50    component = CharField(default="ak-stage-email")
 51
 52    def validate(self, attrs):
 53        raise ValidationError(detail="email-sent", code="email-sent")
 54
 55
 56class EmailStageView(ChallengeStageView):
 57    """Email stage which sends Email for verification"""
 58
 59    response_class = EmailChallengeResponse
 60
 61    def get_full_url(self, **kwargs) -> str:
 62        """Get full URL to be used in template"""
 63        base_url = reverse(
 64            "authentik_core:if-flow",
 65            kwargs={"flow_slug": self.executor.flow.slug},
 66        )
 67        # Parse query string from current URL (full query string)
 68        # this view is only run within a flow executor, where we need to get the query string
 69        # from the query= parameter (double encoded); but for the redirect
 70        # we need to expand it since it'll go through the flow interface
 71        query_params = QueryDict(self.request.GET.get(QS_QUERY), mutable=True)
 72        query_params.pop(QS_KEY_TOKEN, None)
 73        query_params.update(kwargs)
 74        full_url = base_url
 75        if len(query_params) > 0:
 76            full_url = f"{full_url}?{query_params.urlencode()}"
 77        return self.request.build_absolute_uri(full_url)
 78
 79    def get_token(self) -> FlowToken:
 80        """Get token"""
 81        pending_user = self.get_pending_user()
 82        current_stage: EmailStage = self.executor.current_stage
 83        valid_delta = timedelta_from_string(current_stage.token_expiry) + timedelta(
 84            minutes=1
 85        )  # + 1 because django timesince always rounds down
 86        identifier = slugify(f"ak-email-stage-{current_stage.name}-{str(uuid4())}")
 87        # Don't check for validity here, we only care if the token exists
 88        tokens = FlowToken.objects.filter(identifier=identifier)
 89        if not tokens.exists():
 90            return FlowToken.objects.create(
 91                expires=now() + valid_delta,
 92                user=pending_user,
 93                identifier=identifier,
 94                flow=self.executor.flow,
 95                _plan=pickle_flow_token_for_email(self.executor.plan),
 96                revoke_on_execution=False,
 97            )
 98        token = tokens.first()
 99        # Check if token is expired and rotate key if so
100        if token.is_expired:
101            token.expire_action()
102        return token
103
104    def send_email(self):
105        """Helper function that sends the actual email. Implies that you've
106        already checked that there is a pending user."""
107        pending_user = self.get_pending_user()
108        if not pending_user.pk:
109            # Do not create a FlowToken or send email for an unsaved pending user.
110            # This occurs when Identification pretends that an unknown user exists;
111            # persisting a token or conditionally sending mail would either fail or
112            # disclose account existence.
113            return
114        email = self.executor.plan.context.get(PLAN_CONTEXT_EMAIL_OVERRIDE, None)
115        if not email:
116            email = pending_user.email
117        if not email:
118            # Show the same sent-email challenge as for an unknown user, so the response
119            # does not disclose that this account exists without an email address.
120            self.logger.warning("Pending user has no email address", user=pending_user)
121            return
122        current_stage: EmailStage = self.executor.current_stage
123        token = self.get_token()
124        # Send mail to user
125        try:
126            language = pending_user.locale(self.request)
127            with override(language):
128                subject = _(current_stage.subject)
129            message = TemplateEmailMessage(
130                subject=subject,
131                to=[(pending_user.name, email)],
132                language=language,
133                template_name=current_stage.template,
134                template_context={
135                    "url": self.get_full_url(**{QS_KEY_TOKEN: token.key}),
136                    "user": pending_user,
137                    "expires": token.expires,
138                    "token": token.key,
139                },
140            )
141            send_mails(current_stage, message)
142        except TemplateSyntaxError as exc:
143            Event.new(
144                EventAction.CONFIGURATION_ERROR,
145                message=_("Exception occurred while rendering E-mail template"),
146                template=current_stage.template,
147            ).with_exception(exc).from_http(self.request)
148            raise StageInvalidException from exc
149
150    def get(self, request: HttpRequest, *args, **kwargs) -> HttpResponse:
151        # Check if the user came back from the email link to verify
152        restore_token: FlowToken = self.executor.plan.context.get(PLAN_CONTEXT_IS_RESTORED, None)
153        user = self.get_pending_user()
154        # Check if we have an actual pending user (no fallbacks, we only care if
155        # a pending user was set by an identification stage/etc)
156        if restore_token and self.executor.plan.context.get(PLAN_CONTEXT_PENDING_USER):
157            if restore_token.user != user:
158                self.logger.warning("Flow token for non-matching user, denying request")
159                return self.executor.stage_invalid()
160            messages.success(request, _("Successfully verified Email."))
161            if self.executor.current_stage.activate_user_on_success:
162                user.is_active = True
163                user.save(update_fields=["is_active"])
164            return self.executor.stage_ok()
165        if PLAN_CONTEXT_PENDING_USER not in self.executor.plan.context:
166            self.logger.debug("No pending user")
167            messages.error(self.request, _("No pending user."))
168            return self.executor.stage_invalid()
169        # Check if we've already sent the initial e-mail
170        if PLAN_CONTEXT_EMAIL_SENT not in self.executor.plan.context:
171            if minutes_left := self._is_rate_limited():
172                messages.error(self.request, self._rate_limit_error(minutes_left))
173                return super().get(request, *args, **kwargs)
174            try:
175                self.send_email()
176            except StageInvalidException as exc:
177                self.logger.debug("Got StageInvalidException", exc=exc)
178                return self.executor.stage_invalid()
179            self.executor.plan.context[PLAN_CONTEXT_EMAIL_SENT] = True
180        return super().get(request, *args, **kwargs)
181
182    def get_challenge(self) -> Challenge:
183        challenge = EmailChallenge(
184            data={
185                "title": _("Email sent."),
186            }
187        )
188        return challenge
189
190    def challenge_valid(self, response: ChallengeResponse) -> HttpResponse:
191        return super().challenge_invalid(response)
192
193    def _get_cache_key(self) -> str:
194        """Return the cache key used for rate limiting email recovery attempts."""
195        user = self.get_pending_user()
196        user_email_hashed = sha256(user.email.lower().encode("utf-8")).hexdigest()
197        return EMAIL_RECOVERY_CACHE_KEY + user_email_hashed
198
199    def _is_rate_limited(self) -> int | None:
200        """Check whether the email recovery attempt should be rate limited.
201
202        If the request should be rate limited, update the cache and return the
203        remaining time in minutes before the user is allowed to try again.
204        Otherwise, return None."""
205        cache_key = self._get_cache_key()
206        attempts = cache.get(cache_key, [])
207
208        # Fetch a fresh copy for the current rate limit configuration, without
209        # overwriting the rest of the stage config pickled into the flow plan
210        stage = EmailStage.objects.get(pk=self.executor.current_stage.pk)
211        max_attempts = stage.recovery_max_attempts
212        cache_timeout_delta = timedelta_from_string(stage.recovery_cache_timeout)
213
214        _now = now()
215        start_window = _now - cache_timeout_delta
216
217        # Convert unix timestamps to datetime objects for comparison
218        recent_attempts_in_window = [
219            datetime.fromtimestamp(attempt, UTC)
220            for attempt in attempts
221            if datetime.fromtimestamp(attempt, UTC) > start_window
222        ]
223
224        if len(recent_attempts_in_window) >= max_attempts:
225            retry_after = (min(recent_attempts_in_window) + cache_timeout_delta) - _now
226            minutes_left = max(1, math.ceil(retry_after.total_seconds() / 60))
227            return minutes_left
228
229        recent_attempts_in_window.append(_now)
230
231        # Convert datetime objects back to unix timestamps to update cache
232        recent_attempts_in_window = [attempt.timestamp() for attempt in recent_attempts_in_window]
233
234        cache.set(
235            cache_key,
236            recent_attempts_in_window,
237            int(cache_timeout_delta.total_seconds()),
238        )
239
240        return None
241
242    def _rate_limit_error(self, minutes_left: int) -> str:
243        return _(
244            "Too many account verification attempts. Please try again after {minutes} minutes."
245        ).format(minutes=minutes_left)
246
247    def challenge_invalid(self, response: ChallengeResponse) -> HttpResponse:
248        if minutes_left := self._is_rate_limited():
249            messages.error(self.request, self._rate_limit_error(minutes_left))
250            return super().challenge_invalid(response)
251
252        if PLAN_CONTEXT_PENDING_USER not in self.executor.plan.context:
253            messages.error(self.request, _("No pending user."))
254            return super().challenge_invalid(response)
255
256        self.send_email()
257        messages.success(self.request, _("Email Successfully sent."))
258        # We can't call stage_ok yet, as we're still waiting
259        # for the user to click the link in the email
260        return super().challenge_invalid(response)
EMAIL_RECOVERY_CACHE_KEY = 'goauthentik.io/stages/email/stage/'
PLAN_CONTEXT_EMAIL_SENT = 'email_sent'
PLAN_CONTEXT_EMAIL_OVERRIDE = 'email'
class EmailChallenge(authentik.flows.challenge.Challenge):
41class EmailChallenge(Challenge):
42    """Email challenge"""
43
44    component = CharField(default="ak-stage-email")

Email challenge

component
class EmailChallengeResponse(authentik.flows.challenge.ChallengeResponse):
47class EmailChallengeResponse(ChallengeResponse):
48    """Email challenge resposen. No fields. This challenge is
49    always declared invalid to give the user a chance to retry"""
50
51    component = CharField(default="ak-stage-email")
52
53    def validate(self, attrs):
54        raise ValidationError(detail="email-sent", code="email-sent")

Email challenge resposen. No fields. This challenge is always declared invalid to give the user a chance to retry

component
def validate(self, attrs):
53    def validate(self, attrs):
54        raise ValidationError(detail="email-sent", code="email-sent")
class EmailStageView(authentik.flows.stage.ChallengeStageView):
 57class EmailStageView(ChallengeStageView):
 58    """Email stage which sends Email for verification"""
 59
 60    response_class = EmailChallengeResponse
 61
 62    def get_full_url(self, **kwargs) -> str:
 63        """Get full URL to be used in template"""
 64        base_url = reverse(
 65            "authentik_core:if-flow",
 66            kwargs={"flow_slug": self.executor.flow.slug},
 67        )
 68        # Parse query string from current URL (full query string)
 69        # this view is only run within a flow executor, where we need to get the query string
 70        # from the query= parameter (double encoded); but for the redirect
 71        # we need to expand it since it'll go through the flow interface
 72        query_params = QueryDict(self.request.GET.get(QS_QUERY), mutable=True)
 73        query_params.pop(QS_KEY_TOKEN, None)
 74        query_params.update(kwargs)
 75        full_url = base_url
 76        if len(query_params) > 0:
 77            full_url = f"{full_url}?{query_params.urlencode()}"
 78        return self.request.build_absolute_uri(full_url)
 79
 80    def get_token(self) -> FlowToken:
 81        """Get token"""
 82        pending_user = self.get_pending_user()
 83        current_stage: EmailStage = self.executor.current_stage
 84        valid_delta = timedelta_from_string(current_stage.token_expiry) + timedelta(
 85            minutes=1
 86        )  # + 1 because django timesince always rounds down
 87        identifier = slugify(f"ak-email-stage-{current_stage.name}-{str(uuid4())}")
 88        # Don't check for validity here, we only care if the token exists
 89        tokens = FlowToken.objects.filter(identifier=identifier)
 90        if not tokens.exists():
 91            return FlowToken.objects.create(
 92                expires=now() + valid_delta,
 93                user=pending_user,
 94                identifier=identifier,
 95                flow=self.executor.flow,
 96                _plan=pickle_flow_token_for_email(self.executor.plan),
 97                revoke_on_execution=False,
 98            )
 99        token = tokens.first()
100        # Check if token is expired and rotate key if so
101        if token.is_expired:
102            token.expire_action()
103        return token
104
105    def send_email(self):
106        """Helper function that sends the actual email. Implies that you've
107        already checked that there is a pending user."""
108        pending_user = self.get_pending_user()
109        if not pending_user.pk:
110            # Do not create a FlowToken or send email for an unsaved pending user.
111            # This occurs when Identification pretends that an unknown user exists;
112            # persisting a token or conditionally sending mail would either fail or
113            # disclose account existence.
114            return
115        email = self.executor.plan.context.get(PLAN_CONTEXT_EMAIL_OVERRIDE, None)
116        if not email:
117            email = pending_user.email
118        if not email:
119            # Show the same sent-email challenge as for an unknown user, so the response
120            # does not disclose that this account exists without an email address.
121            self.logger.warning("Pending user has no email address", user=pending_user)
122            return
123        current_stage: EmailStage = self.executor.current_stage
124        token = self.get_token()
125        # Send mail to user
126        try:
127            language = pending_user.locale(self.request)
128            with override(language):
129                subject = _(current_stage.subject)
130            message = TemplateEmailMessage(
131                subject=subject,
132                to=[(pending_user.name, email)],
133                language=language,
134                template_name=current_stage.template,
135                template_context={
136                    "url": self.get_full_url(**{QS_KEY_TOKEN: token.key}),
137                    "user": pending_user,
138                    "expires": token.expires,
139                    "token": token.key,
140                },
141            )
142            send_mails(current_stage, message)
143        except TemplateSyntaxError as exc:
144            Event.new(
145                EventAction.CONFIGURATION_ERROR,
146                message=_("Exception occurred while rendering E-mail template"),
147                template=current_stage.template,
148            ).with_exception(exc).from_http(self.request)
149            raise StageInvalidException from exc
150
151    def get(self, request: HttpRequest, *args, **kwargs) -> HttpResponse:
152        # Check if the user came back from the email link to verify
153        restore_token: FlowToken = self.executor.plan.context.get(PLAN_CONTEXT_IS_RESTORED, None)
154        user = self.get_pending_user()
155        # Check if we have an actual pending user (no fallbacks, we only care if
156        # a pending user was set by an identification stage/etc)
157        if restore_token and self.executor.plan.context.get(PLAN_CONTEXT_PENDING_USER):
158            if restore_token.user != user:
159                self.logger.warning("Flow token for non-matching user, denying request")
160                return self.executor.stage_invalid()
161            messages.success(request, _("Successfully verified Email."))
162            if self.executor.current_stage.activate_user_on_success:
163                user.is_active = True
164                user.save(update_fields=["is_active"])
165            return self.executor.stage_ok()
166        if PLAN_CONTEXT_PENDING_USER not in self.executor.plan.context:
167            self.logger.debug("No pending user")
168            messages.error(self.request, _("No pending user."))
169            return self.executor.stage_invalid()
170        # Check if we've already sent the initial e-mail
171        if PLAN_CONTEXT_EMAIL_SENT not in self.executor.plan.context:
172            if minutes_left := self._is_rate_limited():
173                messages.error(self.request, self._rate_limit_error(minutes_left))
174                return super().get(request, *args, **kwargs)
175            try:
176                self.send_email()
177            except StageInvalidException as exc:
178                self.logger.debug("Got StageInvalidException", exc=exc)
179                return self.executor.stage_invalid()
180            self.executor.plan.context[PLAN_CONTEXT_EMAIL_SENT] = True
181        return super().get(request, *args, **kwargs)
182
183    def get_challenge(self) -> Challenge:
184        challenge = EmailChallenge(
185            data={
186                "title": _("Email sent."),
187            }
188        )
189        return challenge
190
191    def challenge_valid(self, response: ChallengeResponse) -> HttpResponse:
192        return super().challenge_invalid(response)
193
194    def _get_cache_key(self) -> str:
195        """Return the cache key used for rate limiting email recovery attempts."""
196        user = self.get_pending_user()
197        user_email_hashed = sha256(user.email.lower().encode("utf-8")).hexdigest()
198        return EMAIL_RECOVERY_CACHE_KEY + user_email_hashed
199
200    def _is_rate_limited(self) -> int | None:
201        """Check whether the email recovery attempt should be rate limited.
202
203        If the request should be rate limited, update the cache and return the
204        remaining time in minutes before the user is allowed to try again.
205        Otherwise, return None."""
206        cache_key = self._get_cache_key()
207        attempts = cache.get(cache_key, [])
208
209        # Fetch a fresh copy for the current rate limit configuration, without
210        # overwriting the rest of the stage config pickled into the flow plan
211        stage = EmailStage.objects.get(pk=self.executor.current_stage.pk)
212        max_attempts = stage.recovery_max_attempts
213        cache_timeout_delta = timedelta_from_string(stage.recovery_cache_timeout)
214
215        _now = now()
216        start_window = _now - cache_timeout_delta
217
218        # Convert unix timestamps to datetime objects for comparison
219        recent_attempts_in_window = [
220            datetime.fromtimestamp(attempt, UTC)
221            for attempt in attempts
222            if datetime.fromtimestamp(attempt, UTC) > start_window
223        ]
224
225        if len(recent_attempts_in_window) >= max_attempts:
226            retry_after = (min(recent_attempts_in_window) + cache_timeout_delta) - _now
227            minutes_left = max(1, math.ceil(retry_after.total_seconds() / 60))
228            return minutes_left
229
230        recent_attempts_in_window.append(_now)
231
232        # Convert datetime objects back to unix timestamps to update cache
233        recent_attempts_in_window = [attempt.timestamp() for attempt in recent_attempts_in_window]
234
235        cache.set(
236            cache_key,
237            recent_attempts_in_window,
238            int(cache_timeout_delta.total_seconds()),
239        )
240
241        return None
242
243    def _rate_limit_error(self, minutes_left: int) -> str:
244        return _(
245            "Too many account verification attempts. Please try again after {minutes} minutes."
246        ).format(minutes=minutes_left)
247
248    def challenge_invalid(self, response: ChallengeResponse) -> HttpResponse:
249        if minutes_left := self._is_rate_limited():
250            messages.error(self.request, self._rate_limit_error(minutes_left))
251            return super().challenge_invalid(response)
252
253        if PLAN_CONTEXT_PENDING_USER not in self.executor.plan.context:
254            messages.error(self.request, _("No pending user."))
255            return super().challenge_invalid(response)
256
257        self.send_email()
258        messages.success(self.request, _("Email Successfully sent."))
259        # We can't call stage_ok yet, as we're still waiting
260        # for the user to click the link in the email
261        return super().challenge_invalid(response)

Email stage which sends Email for verification

response_class = <class 'EmailChallengeResponse'>
def get_full_url(self, **kwargs) -> str:
62    def get_full_url(self, **kwargs) -> str:
63        """Get full URL to be used in template"""
64        base_url = reverse(
65            "authentik_core:if-flow",
66            kwargs={"flow_slug": self.executor.flow.slug},
67        )
68        # Parse query string from current URL (full query string)
69        # this view is only run within a flow executor, where we need to get the query string
70        # from the query= parameter (double encoded); but for the redirect
71        # we need to expand it since it'll go through the flow interface
72        query_params = QueryDict(self.request.GET.get(QS_QUERY), mutable=True)
73        query_params.pop(QS_KEY_TOKEN, None)
74        query_params.update(kwargs)
75        full_url = base_url
76        if len(query_params) > 0:
77            full_url = f"{full_url}?{query_params.urlencode()}"
78        return self.request.build_absolute_uri(full_url)

Get full URL to be used in template

def get_token(self) -> authentik.flows.models.FlowToken:
 80    def get_token(self) -> FlowToken:
 81        """Get token"""
 82        pending_user = self.get_pending_user()
 83        current_stage: EmailStage = self.executor.current_stage
 84        valid_delta = timedelta_from_string(current_stage.token_expiry) + timedelta(
 85            minutes=1
 86        )  # + 1 because django timesince always rounds down
 87        identifier = slugify(f"ak-email-stage-{current_stage.name}-{str(uuid4())}")
 88        # Don't check for validity here, we only care if the token exists
 89        tokens = FlowToken.objects.filter(identifier=identifier)
 90        if not tokens.exists():
 91            return FlowToken.objects.create(
 92                expires=now() + valid_delta,
 93                user=pending_user,
 94                identifier=identifier,
 95                flow=self.executor.flow,
 96                _plan=pickle_flow_token_for_email(self.executor.plan),
 97                revoke_on_execution=False,
 98            )
 99        token = tokens.first()
100        # Check if token is expired and rotate key if so
101        if token.is_expired:
102            token.expire_action()
103        return token

Get token

def send_email(self):
105    def send_email(self):
106        """Helper function that sends the actual email. Implies that you've
107        already checked that there is a pending user."""
108        pending_user = self.get_pending_user()
109        if not pending_user.pk:
110            # Do not create a FlowToken or send email for an unsaved pending user.
111            # This occurs when Identification pretends that an unknown user exists;
112            # persisting a token or conditionally sending mail would either fail or
113            # disclose account existence.
114            return
115        email = self.executor.plan.context.get(PLAN_CONTEXT_EMAIL_OVERRIDE, None)
116        if not email:
117            email = pending_user.email
118        if not email:
119            # Show the same sent-email challenge as for an unknown user, so the response
120            # does not disclose that this account exists without an email address.
121            self.logger.warning("Pending user has no email address", user=pending_user)
122            return
123        current_stage: EmailStage = self.executor.current_stage
124        token = self.get_token()
125        # Send mail to user
126        try:
127            language = pending_user.locale(self.request)
128            with override(language):
129                subject = _(current_stage.subject)
130            message = TemplateEmailMessage(
131                subject=subject,
132                to=[(pending_user.name, email)],
133                language=language,
134                template_name=current_stage.template,
135                template_context={
136                    "url": self.get_full_url(**{QS_KEY_TOKEN: token.key}),
137                    "user": pending_user,
138                    "expires": token.expires,
139                    "token": token.key,
140                },
141            )
142            send_mails(current_stage, message)
143        except TemplateSyntaxError as exc:
144            Event.new(
145                EventAction.CONFIGURATION_ERROR,
146                message=_("Exception occurred while rendering E-mail template"),
147                template=current_stage.template,
148            ).with_exception(exc).from_http(self.request)
149            raise StageInvalidException from exc

Helper function that sends the actual email. Implies that you've already checked that there is a pending user.

def get( self, request: django.http.request.HttpRequest, *args, **kwargs) -> django.http.response.HttpResponse:
151    def get(self, request: HttpRequest, *args, **kwargs) -> HttpResponse:
152        # Check if the user came back from the email link to verify
153        restore_token: FlowToken = self.executor.plan.context.get(PLAN_CONTEXT_IS_RESTORED, None)
154        user = self.get_pending_user()
155        # Check if we have an actual pending user (no fallbacks, we only care if
156        # a pending user was set by an identification stage/etc)
157        if restore_token and self.executor.plan.context.get(PLAN_CONTEXT_PENDING_USER):
158            if restore_token.user != user:
159                self.logger.warning("Flow token for non-matching user, denying request")
160                return self.executor.stage_invalid()
161            messages.success(request, _("Successfully verified Email."))
162            if self.executor.current_stage.activate_user_on_success:
163                user.is_active = True
164                user.save(update_fields=["is_active"])
165            return self.executor.stage_ok()
166        if PLAN_CONTEXT_PENDING_USER not in self.executor.plan.context:
167            self.logger.debug("No pending user")
168            messages.error(self.request, _("No pending user."))
169            return self.executor.stage_invalid()
170        # Check if we've already sent the initial e-mail
171        if PLAN_CONTEXT_EMAIL_SENT not in self.executor.plan.context:
172            if minutes_left := self._is_rate_limited():
173                messages.error(self.request, self._rate_limit_error(minutes_left))
174                return super().get(request, *args, **kwargs)
175            try:
176                self.send_email()
177            except StageInvalidException as exc:
178                self.logger.debug("Got StageInvalidException", exc=exc)
179                return self.executor.stage_invalid()
180            self.executor.plan.context[PLAN_CONTEXT_EMAIL_SENT] = True
181        return super().get(request, *args, **kwargs)

Return a challenge for the frontend to solve

def get_challenge(self) -> authentik.flows.challenge.Challenge:
183    def get_challenge(self) -> Challenge:
184        challenge = EmailChallenge(
185            data={
186                "title": _("Email sent."),
187            }
188        )
189        return challenge

Return the challenge that the client should solve

def challenge_valid( self, response: authentik.flows.challenge.ChallengeResponse) -> django.http.response.HttpResponse:
191    def challenge_valid(self, response: ChallengeResponse) -> HttpResponse:
192        return super().challenge_invalid(response)

Callback when the challenge has the correct format

def challenge_invalid( self, response: authentik.flows.challenge.ChallengeResponse) -> django.http.response.HttpResponse:
248    def challenge_invalid(self, response: ChallengeResponse) -> HttpResponse:
249        if minutes_left := self._is_rate_limited():
250            messages.error(self.request, self._rate_limit_error(minutes_left))
251            return super().challenge_invalid(response)
252
253        if PLAN_CONTEXT_PENDING_USER not in self.executor.plan.context:
254            messages.error(self.request, _("No pending user."))
255            return super().challenge_invalid(response)
256
257        self.send_email()
258        messages.success(self.request, _("Email Successfully sent."))
259        # We can't call stage_ok yet, as we're still waiting
260        # for the user to click the link in the email
261        return super().challenge_invalid(response)

Callback when the challenge has the incorrect format