authentik.stages.authenticator_email.models
1from django.contrib.auth import get_user_model 2from django.core.mail.backends.base import BaseEmailBackend 3from django.core.mail.backends.smtp import EmailBackend 4from django.db import models 5from django.http import HttpRequest 6from django.template import TemplateSyntaxError 7from django.utils.translation import gettext_lazy as _ 8from django.utils.translation import gettext_noop 9from django.views import View 10from rest_framework.serializers import BaseSerializer 11 12from authentik.core.types import UserSettingSerializer 13from authentik.events.models import Event, EventAction 14from authentik.flows.exceptions import StageInvalidException 15from authentik.flows.models import ConfigurableStage, FriendlyNamedStage, Stage 16from authentik.lib.config import CONFIG 17from authentik.lib.models import SerializerModel 18from authentik.lib.utils.time import timedelta_string_validator 19from authentik.stages.authenticator.models import SideChannelDevice, ThrottlingMixin 20from authentik.stages.email.models import EmailTemplates 21from authentik.stages.email.utils import TemplateEmailMessage 22 23 24class AuthenticatorEmailStage(ConfigurableStage, FriendlyNamedStage, Stage): 25 """Setup Email-based authentication for the user.""" 26 27 use_global_settings = models.BooleanField( 28 default=False, 29 help_text=_( 30 "When enabled, global Email connection settings will be used and " 31 "connection settings below will be ignored." 32 ), 33 ) 34 35 host = models.TextField(default="localhost") 36 port = models.IntegerField(default=25) 37 username = models.TextField(default="", blank=True) 38 password = models.TextField(default="", blank=True) 39 use_tls = models.BooleanField(default=False) 40 use_ssl = models.BooleanField(default=False) 41 timeout = models.IntegerField(default=10) 42 from_address = models.EmailField(default="system@authentik.local") 43 44 token_expiry = models.TextField( 45 default="minutes=30", 46 validators=[timedelta_string_validator], 47 help_text=_("Time the token sent is valid (Format: hours=3;minutes=17;seconds=300)."), 48 ) 49 subject = models.TextField(default=gettext_noop("authentik Sign-in code")) 50 template = models.TextField(default=EmailTemplates.EMAIL_OTP) 51 52 @property 53 def serializer(self) -> type[BaseSerializer]: 54 from authentik.stages.authenticator_email.api import AuthenticatorEmailStageSerializer 55 56 return AuthenticatorEmailStageSerializer 57 58 @property 59 def view(self) -> type[View]: 60 from authentik.stages.authenticator_email.stage import AuthenticatorEmailStageView 61 62 return AuthenticatorEmailStageView 63 64 @property 65 def component(self) -> str: 66 return "ak-stage-authenticator-email-form" 67 68 def ui_user_settings(self) -> UserSettingSerializer | None: 69 return UserSettingSerializer( 70 data={ 71 "title": self.friendly_name or str(self._meta.verbose_name), 72 "component": "ak-user-settings-authenticator-email", 73 } 74 ) 75 76 @property 77 def backend_class(self) -> type[BaseEmailBackend]: 78 """Get the email backend class to use""" 79 return EmailBackend 80 81 @property 82 def backend(self) -> BaseEmailBackend: 83 """Get fully configured Email Backend instance""" 84 if self.use_global_settings: 85 CONFIG.refresh("email.password") 86 return self.backend_class( 87 host=CONFIG.get("email.host"), 88 port=CONFIG.get_int("email.port"), 89 username=CONFIG.get("email.username"), 90 password=CONFIG.get("email.password"), 91 use_tls=CONFIG.get_bool("email.use_tls", False), 92 use_ssl=CONFIG.get_bool("email.use_ssl", False), 93 timeout=CONFIG.get_int("email.timeout"), 94 ) 95 return self.backend_class( 96 host=self.host, 97 port=self.port, 98 username=self.username, 99 password=self.password, 100 use_tls=self.use_tls, 101 use_ssl=self.use_ssl, 102 timeout=self.timeout, 103 ) 104 105 def send(self, request: HttpRequest, device: EmailDevice): 106 # Lazy import here to avoid circular import 107 from authentik.stages.email.tasks import send_mails 108 109 # Compose the message using templates 110 message = device._compose_email(request) 111 return send_mails(device.stage, message) 112 113 def __str__(self): 114 return f"Email Authenticator Stage {self.name}" 115 116 class Meta: 117 verbose_name = _("Email Authenticator Setup Stage") 118 verbose_name_plural = _("Email Authenticator Setup Stages") 119 120 121class EmailDevice(SerializerModel, ThrottlingMixin, SideChannelDevice): 122 """Email Device""" 123 124 user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) 125 email = models.EmailField() 126 stage = models.ForeignKey(AuthenticatorEmailStage, on_delete=models.PROTECT) 127 last_used = models.DateTimeField(auto_now=True) 128 129 @property 130 def serializer(self) -> type[BaseSerializer]: 131 from authentik.stages.authenticator_email.api import EmailDeviceSerializer 132 133 return EmailDeviceSerializer 134 135 def verify_token(self, token: str) -> bool: 136 verify_allowed, _ = self.verify_is_allowed() 137 if verify_allowed: 138 verified = super().verify_token(token) 139 140 if verified: 141 self.throttle_reset() 142 else: 143 self.throttle_increment() 144 else: 145 verified = False 146 147 return verified 148 149 def _compose_email(self, request: HttpRequest) -> TemplateEmailMessage: 150 try: 151 pending_user = self.user 152 stage = self.stage 153 email = self.email 154 155 message = TemplateEmailMessage( 156 subject=_(stage.subject), 157 to=[(pending_user.name, email)], 158 template_name=stage.template, 159 template_context={ 160 "user": pending_user, 161 "expires": self.valid_until, 162 "token": self.token, 163 }, 164 ) 165 return message 166 except TemplateSyntaxError as exc: 167 Event.new( 168 EventAction.CONFIGURATION_ERROR, 169 message=_("Exception occurred while rendering E-mail template"), 170 template=stage.template, 171 ).with_exception(exc).from_http(request) 172 raise StageInvalidException from exc 173 174 def __str__(self): 175 if not self.pk: 176 return "New Email Device" 177 return f"Email Device for {self.user_id}" 178 179 class Meta: 180 verbose_name = _("Email Device") 181 verbose_name_plural = _("Email Devices") 182 unique_together = (("user", "email"),)
25class AuthenticatorEmailStage(ConfigurableStage, FriendlyNamedStage, Stage): 26 """Setup Email-based authentication for the user.""" 27 28 use_global_settings = models.BooleanField( 29 default=False, 30 help_text=_( 31 "When enabled, global Email connection settings will be used and " 32 "connection settings below will be ignored." 33 ), 34 ) 35 36 host = models.TextField(default="localhost") 37 port = models.IntegerField(default=25) 38 username = models.TextField(default="", blank=True) 39 password = models.TextField(default="", blank=True) 40 use_tls = models.BooleanField(default=False) 41 use_ssl = models.BooleanField(default=False) 42 timeout = models.IntegerField(default=10) 43 from_address = models.EmailField(default="system@authentik.local") 44 45 token_expiry = models.TextField( 46 default="minutes=30", 47 validators=[timedelta_string_validator], 48 help_text=_("Time the token sent is valid (Format: hours=3;minutes=17;seconds=300)."), 49 ) 50 subject = models.TextField(default=gettext_noop("authentik Sign-in code")) 51 template = models.TextField(default=EmailTemplates.EMAIL_OTP) 52 53 @property 54 def serializer(self) -> type[BaseSerializer]: 55 from authentik.stages.authenticator_email.api import AuthenticatorEmailStageSerializer 56 57 return AuthenticatorEmailStageSerializer 58 59 @property 60 def view(self) -> type[View]: 61 from authentik.stages.authenticator_email.stage import AuthenticatorEmailStageView 62 63 return AuthenticatorEmailStageView 64 65 @property 66 def component(self) -> str: 67 return "ak-stage-authenticator-email-form" 68 69 def ui_user_settings(self) -> UserSettingSerializer | None: 70 return UserSettingSerializer( 71 data={ 72 "title": self.friendly_name or str(self._meta.verbose_name), 73 "component": "ak-user-settings-authenticator-email", 74 } 75 ) 76 77 @property 78 def backend_class(self) -> type[BaseEmailBackend]: 79 """Get the email backend class to use""" 80 return EmailBackend 81 82 @property 83 def backend(self) -> BaseEmailBackend: 84 """Get fully configured Email Backend instance""" 85 if self.use_global_settings: 86 CONFIG.refresh("email.password") 87 return self.backend_class( 88 host=CONFIG.get("email.host"), 89 port=CONFIG.get_int("email.port"), 90 username=CONFIG.get("email.username"), 91 password=CONFIG.get("email.password"), 92 use_tls=CONFIG.get_bool("email.use_tls", False), 93 use_ssl=CONFIG.get_bool("email.use_ssl", False), 94 timeout=CONFIG.get_int("email.timeout"), 95 ) 96 return self.backend_class( 97 host=self.host, 98 port=self.port, 99 username=self.username, 100 password=self.password, 101 use_tls=self.use_tls, 102 use_ssl=self.use_ssl, 103 timeout=self.timeout, 104 ) 105 106 def send(self, request: HttpRequest, device: EmailDevice): 107 # Lazy import here to avoid circular import 108 from authentik.stages.email.tasks import send_mails 109 110 # Compose the message using templates 111 message = device._compose_email(request) 112 return send_mails(device.stage, message) 113 114 def __str__(self): 115 return f"Email Authenticator Stage {self.name}" 116 117 class Meta: 118 verbose_name = _("Email Authenticator Setup Stage") 119 verbose_name_plural = _("Email Authenticator Setup Stages")
Setup Email-based authentication for the user.
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
53 @property 54 def serializer(self) -> type[BaseSerializer]: 55 from authentik.stages.authenticator_email.api import AuthenticatorEmailStageSerializer 56 57 return AuthenticatorEmailStageSerializer
Get serializer for this model
59 @property 60 def view(self) -> type[View]: 61 from authentik.stages.authenticator_email.stage import AuthenticatorEmailStageView 62 63 return AuthenticatorEmailStageView
Return StageView class that implements logic for this stage
69 def ui_user_settings(self) -> UserSettingSerializer | None: 70 return UserSettingSerializer( 71 data={ 72 "title": self.friendly_name or str(self._meta.verbose_name), 73 "component": "ak-user-settings-authenticator-email", 74 } 75 )
Entrypoint to integrate with User settings. Can either return None if no user settings are available, or a challenge.
77 @property 78 def backend_class(self) -> type[BaseEmailBackend]: 79 """Get the email backend class to use""" 80 return EmailBackend
Get the email backend class to use
82 @property 83 def backend(self) -> BaseEmailBackend: 84 """Get fully configured Email Backend instance""" 85 if self.use_global_settings: 86 CONFIG.refresh("email.password") 87 return self.backend_class( 88 host=CONFIG.get("email.host"), 89 port=CONFIG.get_int("email.port"), 90 username=CONFIG.get("email.username"), 91 password=CONFIG.get("email.password"), 92 use_tls=CONFIG.get_bool("email.use_tls", False), 93 use_ssl=CONFIG.get_bool("email.use_ssl", False), 94 timeout=CONFIG.get_int("email.timeout"), 95 ) 96 return self.backend_class( 97 host=self.host, 98 port=self.port, 99 username=self.username, 100 password=self.password, 101 use_tls=self.use_tls, 102 use_ssl=self.use_ssl, 103 timeout=self.timeout, 104 )
Get fully configured Email Backend instance
106 def send(self, request: HttpRequest, device: EmailDevice): 107 # Lazy import here to avoid circular import 108 from authentik.stages.email.tasks import send_mails 109 110 # Compose the message using templates 111 message = device._compose_email(request) 112 return send_mails(device.stage, message)
Accessor to the related object on the forward side of a many-to-one or one-to-one (via ForwardOneToOneDescriptor subclass) relation.
In the example::
class Child(Model):
parent = ForeignKey(Parent, related_name='children')
Child.parent is a ForwardManyToOneDescriptor instance.
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
Accessor to the related object on the forward side of a one-to-one relation.
In the example::
class Restaurant(Model):
place = OneToOneField(Place, related_name='restaurant')
Restaurant.place is a ForwardOneToOneDescriptor instance.
Accessor to the related objects manager on the reverse side of a many-to-one relation.
In the example::
class Child(Model):
parent = ForeignKey(Parent, related_name='children')
Parent.children is a ReverseManyToOneDescriptor instance.
Most of the implementation is delegated to a dynamically defined manager
class built by create_forward_many_to_many_manager() defined below.
Inherited Members
- authentik.flows.models.Stage
- stage_uuid
- name
- objects
- is_in_memory
- flow_set
- flowstagebinding_set
- emailstage
- passwordstage
- endpointstage
- invitationstage
- promptstage
- authenticatorstaticstage
- authenticatorduostage
- authenticatoremailstage
- authenticatorsmsstage
- authenticatorwebauthnstage
- authenticatorvalidatestage
- authenticator_validate_stage_m2m_objects
- captchastage
- identificationstage
- authenticatortotpstage
- consentstage
- denystage
- dummystage
- redirectstage
- userdeletestage
- userloginstage
- userlogoutstage
- userwritestage
- accountlockdownstage
- authenticatorendpointgdtcstage
- mutualtlsstage
- sourcestage
The requested object does not exist
The query returned multiple objects when only one was expected.
122class EmailDevice(SerializerModel, ThrottlingMixin, SideChannelDevice): 123 """Email Device""" 124 125 user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) 126 email = models.EmailField() 127 stage = models.ForeignKey(AuthenticatorEmailStage, on_delete=models.PROTECT) 128 last_used = models.DateTimeField(auto_now=True) 129 130 @property 131 def serializer(self) -> type[BaseSerializer]: 132 from authentik.stages.authenticator_email.api import EmailDeviceSerializer 133 134 return EmailDeviceSerializer 135 136 def verify_token(self, token: str) -> bool: 137 verify_allowed, _ = self.verify_is_allowed() 138 if verify_allowed: 139 verified = super().verify_token(token) 140 141 if verified: 142 self.throttle_reset() 143 else: 144 self.throttle_increment() 145 else: 146 verified = False 147 148 return verified 149 150 def _compose_email(self, request: HttpRequest) -> TemplateEmailMessage: 151 try: 152 pending_user = self.user 153 stage = self.stage 154 email = self.email 155 156 message = TemplateEmailMessage( 157 subject=_(stage.subject), 158 to=[(pending_user.name, email)], 159 template_name=stage.template, 160 template_context={ 161 "user": pending_user, 162 "expires": self.valid_until, 163 "token": self.token, 164 }, 165 ) 166 return message 167 except TemplateSyntaxError as exc: 168 Event.new( 169 EventAction.CONFIGURATION_ERROR, 170 message=_("Exception occurred while rendering E-mail template"), 171 template=stage.template, 172 ).with_exception(exc).from_http(request) 173 raise StageInvalidException from exc 174 175 def __str__(self): 176 if not self.pk: 177 return "New Email Device" 178 return f"Email Device for {self.user_id}" 179 180 class Meta: 181 verbose_name = _("Email Device") 182 verbose_name_plural = _("Email Devices") 183 unique_together = (("user", "email"),)
Email Device
Accessor to the related object on the forward side of a many-to-one or one-to-one (via ForwardOneToOneDescriptor subclass) relation.
In the example::
class Child(Model):
parent = ForeignKey(Parent, related_name='children')
Child.parent is a ForwardManyToOneDescriptor instance.
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
Accessor to the related object on the forward side of a many-to-one or one-to-one (via ForwardOneToOneDescriptor subclass) relation.
In the example::
class Child(Model):
parent = ForeignKey(Parent, related_name='children')
Child.parent is a ForwardManyToOneDescriptor instance.
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
130 @property 131 def serializer(self) -> type[BaseSerializer]: 132 from authentik.stages.authenticator_email.api import EmailDeviceSerializer 133 134 return EmailDeviceSerializer
Get serializer for this model
136 def verify_token(self, token: str) -> bool: 137 verify_allowed, _ = self.verify_is_allowed() 138 if verify_allowed: 139 verified = super().verify_token(token) 140 141 if verified: 142 self.throttle_reset() 143 else: 144 self.throttle_increment() 145 else: 146 verified = False 147 148 return verified
Verifies a token by content and expiry.
On success, the token is cleared and the device saved.
:param str token: The OTP token provided by the user. :rtype: bool
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
Method descriptor with partial application of the given arguments and keywords.
Supports wrapping existing descriptors and handles non-descriptor callables as instance methods.
Method descriptor with partial application of the given arguments and keywords.
Supports wrapping existing descriptors and handles non-descriptor callables as instance methods.
Method descriptor with partial application of the given arguments and keywords.
Supports wrapping existing descriptors and handles non-descriptor callables as instance methods.
Method descriptor with partial application of the given arguments and keywords.
Supports wrapping existing descriptors and handles non-descriptor callables as instance methods.
Method descriptor with partial application of the given arguments and keywords.
Supports wrapping existing descriptors and handles non-descriptor callables as instance methods.
Method descriptor with partial application of the given arguments and keywords.
Supports wrapping existing descriptors and handles non-descriptor callables as instance methods.
Method descriptor with partial application of the given arguments and keywords.
Supports wrapping existing descriptors and handles non-descriptor callables as instance methods.
Method descriptor with partial application of the given arguments and keywords.
Supports wrapping existing descriptors and handles non-descriptor callables as instance methods.
A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.
Inherited Members
The requested object does not exist
The query returned multiple objects when only one was expected.