authentik.stages.authenticator_email.stage

Email Setup stage

  1"""Email Setup stage"""
  2
  3from django.db.models import Q
  4from django.http import HttpRequest, HttpResponse
  5from django.http.request import QueryDict
  6from django.template.exceptions import TemplateSyntaxError
  7from django.utils.translation import gettext_lazy as _
  8from rest_framework.exceptions import ValidationError
  9from rest_framework.fields import BooleanField, CharField
 10
 11from authentik.events.models import Event, EventAction
 12from authentik.flows.challenge import (
 13    Challenge,
 14    ChallengeResponse,
 15    WithUserInfoChallenge,
 16)
 17from authentik.flows.exceptions import StageInvalidException
 18from authentik.flows.stage import ChallengeStageView
 19from authentik.lib.utils.email import mask_email
 20from authentik.lib.utils.time import timedelta_from_string
 21from authentik.stages.authenticator_email.models import (
 22    AuthenticatorEmailStage,
 23    EmailDevice,
 24)
 25from authentik.stages.email.tasks import send_mails
 26from authentik.stages.email.utils import TemplateEmailMessage
 27from authentik.stages.prompt.stage import PLAN_CONTEXT_PROMPT
 28
 29PLAN_CONTEXT_EMAIL_DEVICE = "goauthentik.io/stages/authenticator_email/email_device"
 30PLAN_CONTEXT_EMAIL = "email"
 31PLAN_CONTEXT_EMAIL_SENT = "email_sent"
 32PLAN_CONTEXT_EMAIL_OVERRIDE = "email"
 33
 34
 35class AuthenticatorEmailChallenge(WithUserInfoChallenge):
 36    """Authenticator Email Setup challenge"""
 37
 38    # Set to true if no previous prompt stage set the email
 39    # this stage will also check prompt_data.email
 40    email = CharField(default=None, allow_blank=True, allow_null=True)
 41    email_required = BooleanField(default=True)
 42    component = CharField(default="ak-stage-authenticator-email")
 43
 44
 45class AuthenticatorEmailChallengeResponse(ChallengeResponse):
 46    """Authenticator Email Challenge response, device is set by get_response_instance"""
 47
 48    device: EmailDevice
 49
 50    code = CharField(required=False)
 51    email = CharField(required=False)
 52
 53    component = CharField(default="ak-stage-authenticator-email")
 54
 55    def validate(self, attrs: dict) -> dict:
 56        """Check"""
 57        if "code" not in attrs:
 58            # If the flow already established a destination address,
 59            # use that address rather than one provided in the request
 60            email = self.stage._has_email()
 61            if email is None:
 62                if "email" not in attrs:
 63                    raise ValidationError("email required")
 64                email = attrs["email"]
 65            self.device.email = email
 66            self.stage.validate_and_send(email)
 67            return super().validate(attrs)
 68        if not self.device.verify_token(str(attrs["code"])):
 69            raise ValidationError(_("Code does not match"))
 70        self.device.confirmed = True
 71        return super().validate(attrs)
 72
 73
 74class AuthenticatorEmailStageView(ChallengeStageView):
 75    """Authenticator Email Setup stage"""
 76
 77    response_class = AuthenticatorEmailChallengeResponse
 78
 79    def validate_and_send(self, email: str):
 80        """Validate email and send message"""
 81        pending_user = self.get_pending_user()
 82
 83        stage: AuthenticatorEmailStage = self.executor.current_stage
 84        if EmailDevice.objects.filter(Q(email=email), stage=stage.pk).exists():
 85            raise ValidationError(_("Invalid email"))
 86
 87        device: EmailDevice = self.executor.plan.context[PLAN_CONTEXT_EMAIL_DEVICE]
 88
 89        try:
 90            message = TemplateEmailMessage(
 91                subject=_(stage.subject),
 92                to=[(pending_user.name, email)],
 93                language=pending_user.locale(self.request),
 94                template_name=stage.template,
 95                template_context={
 96                    "user": pending_user,
 97                    "expires": device.valid_until,
 98                    "token": device.token,
 99                },
100            )
101
102            send_mails(stage, message)
103        except TemplateSyntaxError as exc:
104            Event.new(
105                EventAction.CONFIGURATION_ERROR,
106                message=_("Exception occurred while rendering E-mail template"),
107                template=stage.template,
108            ).with_exception(exc).from_http(self.request)
109            raise StageInvalidException from exc
110
111    def _has_email(self) -> str | None:
112        context = self.executor.plan.context
113
114        # Check user's email attribute
115        user = self.get_pending_user()
116        if user.email:
117            self.logger.debug("got email from user attributes")
118            return user.email
119        # Check plan context for email
120        if PLAN_CONTEXT_EMAIL in context.get(PLAN_CONTEXT_PROMPT, {}):
121            self.logger.debug("got email from plan context")
122            return context.get(PLAN_CONTEXT_PROMPT, {}).get(PLAN_CONTEXT_EMAIL)
123        # Check device for email
124        if PLAN_CONTEXT_EMAIL_DEVICE in self.executor.plan.context:
125            self.logger.debug("got email from device in session")
126            device: EmailDevice = self.executor.plan.context[PLAN_CONTEXT_EMAIL_DEVICE]
127            if device.email == "":
128                return None
129            return device.email
130        return None
131
132    def get_challenge(self, *args, **kwargs) -> Challenge:
133        email = self._has_email()
134        return AuthenticatorEmailChallenge(
135            data={
136                "email": mask_email(email),
137                "email_required": email is None,
138            }
139        )
140
141    def get_response_instance(self, data: QueryDict) -> ChallengeResponse:
142        response = super().get_response_instance(data)
143        response.device = self.executor.plan.context[PLAN_CONTEXT_EMAIL_DEVICE]
144        return response
145
146    def get(self, request: HttpRequest, *args, **kwargs) -> HttpResponse:
147        user = self.get_pending_user()
148
149        stage: AuthenticatorEmailStage = self.executor.current_stage
150        # For the moment we only allow one email device per user
151        if EmailDevice.objects.filter(Q(user=user), stage=stage.pk).exists():
152            return self.executor.stage_invalid(
153                _("The user already has an email address registered for MFA.")
154            )
155        if PLAN_CONTEXT_EMAIL_DEVICE not in self.executor.plan.context:
156            device = EmailDevice(user=user, confirmed=False, stage=stage, name="Email Device")
157            valid_secs: int = timedelta_from_string(stage.token_expiry).total_seconds()
158            device.generate_token(valid_secs=valid_secs, commit=False)
159            self.executor.plan.context[PLAN_CONTEXT_EMAIL_DEVICE] = device
160            if email := self._has_email():
161                device.email = email
162                try:
163                    self.validate_and_send(email)
164                except ValidationError as exc:
165                    # We had an email given already (at this point only possible from flow
166                    # context), but an error occurred while sending (most likely)
167                    # due to a duplicate device, so delete the email we got given, reset the state
168                    # (ish) and retry
169                    device.email = ""
170                    self.executor.plan.context.get(PLAN_CONTEXT_PROMPT, {}).pop(
171                        PLAN_CONTEXT_EMAIL, None
172                    )
173                    self.executor.plan.context.pop(PLAN_CONTEXT_EMAIL_DEVICE, None)
174                    self.logger.warning("failed to send email to pre-set address", exc=exc)
175                    return self.get(request, *args, **kwargs)
176        return super().get(request, *args, **kwargs)
177
178    def challenge_valid(self, response: ChallengeResponse) -> HttpResponse:
179        """Email Token is validated by challenge"""
180        device: EmailDevice = self.executor.plan.context[PLAN_CONTEXT_EMAIL_DEVICE]
181        if not device.confirmed:
182            return self.challenge_invalid(response)
183        device.save()
184        del self.executor.plan.context[PLAN_CONTEXT_EMAIL_DEVICE]
185        return self.executor.stage_ok()
PLAN_CONTEXT_EMAIL_DEVICE = 'goauthentik.io/stages/authenticator_email/email_device'
PLAN_CONTEXT_EMAIL = 'email'
PLAN_CONTEXT_EMAIL_SENT = 'email_sent'
PLAN_CONTEXT_EMAIL_OVERRIDE = 'email'
class AuthenticatorEmailChallenge(authentik.flows.challenge.WithUserInfoChallenge):
36class AuthenticatorEmailChallenge(WithUserInfoChallenge):
37    """Authenticator Email Setup challenge"""
38
39    # Set to true if no previous prompt stage set the email
40    # this stage will also check prompt_data.email
41    email = CharField(default=None, allow_blank=True, allow_null=True)
42    email_required = BooleanField(default=True)
43    component = CharField(default="ak-stage-authenticator-email")

Authenticator Email Setup challenge

email
email_required
component
class AuthenticatorEmailChallengeResponse(authentik.flows.challenge.ChallengeResponse):
46class AuthenticatorEmailChallengeResponse(ChallengeResponse):
47    """Authenticator Email Challenge response, device is set by get_response_instance"""
48
49    device: EmailDevice
50
51    code = CharField(required=False)
52    email = CharField(required=False)
53
54    component = CharField(default="ak-stage-authenticator-email")
55
56    def validate(self, attrs: dict) -> dict:
57        """Check"""
58        if "code" not in attrs:
59            # If the flow already established a destination address,
60            # use that address rather than one provided in the request
61            email = self.stage._has_email()
62            if email is None:
63                if "email" not in attrs:
64                    raise ValidationError("email required")
65                email = attrs["email"]
66            self.device.email = email
67            self.stage.validate_and_send(email)
68            return super().validate(attrs)
69        if not self.device.verify_token(str(attrs["code"])):
70            raise ValidationError(_("Code does not match"))
71        self.device.confirmed = True
72        return super().validate(attrs)

Authenticator Email Challenge response, device is set by get_response_instance

code
email
component
def validate(self, attrs: dict) -> dict:
56    def validate(self, attrs: dict) -> dict:
57        """Check"""
58        if "code" not in attrs:
59            # If the flow already established a destination address,
60            # use that address rather than one provided in the request
61            email = self.stage._has_email()
62            if email is None:
63                if "email" not in attrs:
64                    raise ValidationError("email required")
65                email = attrs["email"]
66            self.device.email = email
67            self.stage.validate_and_send(email)
68            return super().validate(attrs)
69        if not self.device.verify_token(str(attrs["code"])):
70            raise ValidationError(_("Code does not match"))
71        self.device.confirmed = True
72        return super().validate(attrs)

Check

class AuthenticatorEmailStageView(authentik.flows.stage.ChallengeStageView):
 75class AuthenticatorEmailStageView(ChallengeStageView):
 76    """Authenticator Email Setup stage"""
 77
 78    response_class = AuthenticatorEmailChallengeResponse
 79
 80    def validate_and_send(self, email: str):
 81        """Validate email and send message"""
 82        pending_user = self.get_pending_user()
 83
 84        stage: AuthenticatorEmailStage = self.executor.current_stage
 85        if EmailDevice.objects.filter(Q(email=email), stage=stage.pk).exists():
 86            raise ValidationError(_("Invalid email"))
 87
 88        device: EmailDevice = self.executor.plan.context[PLAN_CONTEXT_EMAIL_DEVICE]
 89
 90        try:
 91            message = TemplateEmailMessage(
 92                subject=_(stage.subject),
 93                to=[(pending_user.name, email)],
 94                language=pending_user.locale(self.request),
 95                template_name=stage.template,
 96                template_context={
 97                    "user": pending_user,
 98                    "expires": device.valid_until,
 99                    "token": device.token,
100                },
101            )
102
103            send_mails(stage, message)
104        except TemplateSyntaxError as exc:
105            Event.new(
106                EventAction.CONFIGURATION_ERROR,
107                message=_("Exception occurred while rendering E-mail template"),
108                template=stage.template,
109            ).with_exception(exc).from_http(self.request)
110            raise StageInvalidException from exc
111
112    def _has_email(self) -> str | None:
113        context = self.executor.plan.context
114
115        # Check user's email attribute
116        user = self.get_pending_user()
117        if user.email:
118            self.logger.debug("got email from user attributes")
119            return user.email
120        # Check plan context for email
121        if PLAN_CONTEXT_EMAIL in context.get(PLAN_CONTEXT_PROMPT, {}):
122            self.logger.debug("got email from plan context")
123            return context.get(PLAN_CONTEXT_PROMPT, {}).get(PLAN_CONTEXT_EMAIL)
124        # Check device for email
125        if PLAN_CONTEXT_EMAIL_DEVICE in self.executor.plan.context:
126            self.logger.debug("got email from device in session")
127            device: EmailDevice = self.executor.plan.context[PLAN_CONTEXT_EMAIL_DEVICE]
128            if device.email == "":
129                return None
130            return device.email
131        return None
132
133    def get_challenge(self, *args, **kwargs) -> Challenge:
134        email = self._has_email()
135        return AuthenticatorEmailChallenge(
136            data={
137                "email": mask_email(email),
138                "email_required": email is None,
139            }
140        )
141
142    def get_response_instance(self, data: QueryDict) -> ChallengeResponse:
143        response = super().get_response_instance(data)
144        response.device = self.executor.plan.context[PLAN_CONTEXT_EMAIL_DEVICE]
145        return response
146
147    def get(self, request: HttpRequest, *args, **kwargs) -> HttpResponse:
148        user = self.get_pending_user()
149
150        stage: AuthenticatorEmailStage = self.executor.current_stage
151        # For the moment we only allow one email device per user
152        if EmailDevice.objects.filter(Q(user=user), stage=stage.pk).exists():
153            return self.executor.stage_invalid(
154                _("The user already has an email address registered for MFA.")
155            )
156        if PLAN_CONTEXT_EMAIL_DEVICE not in self.executor.plan.context:
157            device = EmailDevice(user=user, confirmed=False, stage=stage, name="Email Device")
158            valid_secs: int = timedelta_from_string(stage.token_expiry).total_seconds()
159            device.generate_token(valid_secs=valid_secs, commit=False)
160            self.executor.plan.context[PLAN_CONTEXT_EMAIL_DEVICE] = device
161            if email := self._has_email():
162                device.email = email
163                try:
164                    self.validate_and_send(email)
165                except ValidationError as exc:
166                    # We had an email given already (at this point only possible from flow
167                    # context), but an error occurred while sending (most likely)
168                    # due to a duplicate device, so delete the email we got given, reset the state
169                    # (ish) and retry
170                    device.email = ""
171                    self.executor.plan.context.get(PLAN_CONTEXT_PROMPT, {}).pop(
172                        PLAN_CONTEXT_EMAIL, None
173                    )
174                    self.executor.plan.context.pop(PLAN_CONTEXT_EMAIL_DEVICE, None)
175                    self.logger.warning("failed to send email to pre-set address", exc=exc)
176                    return self.get(request, *args, **kwargs)
177        return super().get(request, *args, **kwargs)
178
179    def challenge_valid(self, response: ChallengeResponse) -> HttpResponse:
180        """Email Token is validated by challenge"""
181        device: EmailDevice = self.executor.plan.context[PLAN_CONTEXT_EMAIL_DEVICE]
182        if not device.confirmed:
183            return self.challenge_invalid(response)
184        device.save()
185        del self.executor.plan.context[PLAN_CONTEXT_EMAIL_DEVICE]
186        return self.executor.stage_ok()

Authenticator Email Setup stage

response_class = <class 'AuthenticatorEmailChallengeResponse'>
def validate_and_send(self, email: str):
 80    def validate_and_send(self, email: str):
 81        """Validate email and send message"""
 82        pending_user = self.get_pending_user()
 83
 84        stage: AuthenticatorEmailStage = self.executor.current_stage
 85        if EmailDevice.objects.filter(Q(email=email), stage=stage.pk).exists():
 86            raise ValidationError(_("Invalid email"))
 87
 88        device: EmailDevice = self.executor.plan.context[PLAN_CONTEXT_EMAIL_DEVICE]
 89
 90        try:
 91            message = TemplateEmailMessage(
 92                subject=_(stage.subject),
 93                to=[(pending_user.name, email)],
 94                language=pending_user.locale(self.request),
 95                template_name=stage.template,
 96                template_context={
 97                    "user": pending_user,
 98                    "expires": device.valid_until,
 99                    "token": device.token,
100                },
101            )
102
103            send_mails(stage, message)
104        except TemplateSyntaxError as exc:
105            Event.new(
106                EventAction.CONFIGURATION_ERROR,
107                message=_("Exception occurred while rendering E-mail template"),
108                template=stage.template,
109            ).with_exception(exc).from_http(self.request)
110            raise StageInvalidException from exc

Validate email and send message

def get_challenge(self, *args, **kwargs) -> authentik.flows.challenge.Challenge:
133    def get_challenge(self, *args, **kwargs) -> Challenge:
134        email = self._has_email()
135        return AuthenticatorEmailChallenge(
136            data={
137                "email": mask_email(email),
138                "email_required": email is None,
139            }
140        )

Return the challenge that the client should solve

def get_response_instance( self, data: django.http.request.QueryDict) -> authentik.flows.challenge.ChallengeResponse:
142    def get_response_instance(self, data: QueryDict) -> ChallengeResponse:
143        response = super().get_response_instance(data)
144        response.device = self.executor.plan.context[PLAN_CONTEXT_EMAIL_DEVICE]
145        return response

Return the response class type

def get( self, request: django.http.request.HttpRequest, *args, **kwargs) -> django.http.response.HttpResponse:
147    def get(self, request: HttpRequest, *args, **kwargs) -> HttpResponse:
148        user = self.get_pending_user()
149
150        stage: AuthenticatorEmailStage = self.executor.current_stage
151        # For the moment we only allow one email device per user
152        if EmailDevice.objects.filter(Q(user=user), stage=stage.pk).exists():
153            return self.executor.stage_invalid(
154                _("The user already has an email address registered for MFA.")
155            )
156        if PLAN_CONTEXT_EMAIL_DEVICE not in self.executor.plan.context:
157            device = EmailDevice(user=user, confirmed=False, stage=stage, name="Email Device")
158            valid_secs: int = timedelta_from_string(stage.token_expiry).total_seconds()
159            device.generate_token(valid_secs=valid_secs, commit=False)
160            self.executor.plan.context[PLAN_CONTEXT_EMAIL_DEVICE] = device
161            if email := self._has_email():
162                device.email = email
163                try:
164                    self.validate_and_send(email)
165                except ValidationError as exc:
166                    # We had an email given already (at this point only possible from flow
167                    # context), but an error occurred while sending (most likely)
168                    # due to a duplicate device, so delete the email we got given, reset the state
169                    # (ish) and retry
170                    device.email = ""
171                    self.executor.plan.context.get(PLAN_CONTEXT_PROMPT, {}).pop(
172                        PLAN_CONTEXT_EMAIL, None
173                    )
174                    self.executor.plan.context.pop(PLAN_CONTEXT_EMAIL_DEVICE, None)
175                    self.logger.warning("failed to send email to pre-set address", exc=exc)
176                    return self.get(request, *args, **kwargs)
177        return super().get(request, *args, **kwargs)

Return a challenge for the frontend to solve

def challenge_valid( self, response: authentik.flows.challenge.ChallengeResponse) -> django.http.response.HttpResponse:
179    def challenge_valid(self, response: ChallengeResponse) -> HttpResponse:
180        """Email Token is validated by challenge"""
181        device: EmailDevice = self.executor.plan.context[PLAN_CONTEXT_EMAIL_DEVICE]
182        if not device.confirmed:
183            return self.challenge_invalid(response)
184        device.save()
185        del self.executor.plan.context[PLAN_CONTEXT_EMAIL_DEVICE]
186        return self.executor.stage_ok()

Email Token is validated by challenge