authentik.stages.authenticator_validate.models

Authenticator Validation Stage

  1"""Authenticator Validation Stage"""
  2
  3from django.contrib.postgres.fields.array import ArrayField
  4from django.db import models
  5from django.utils.translation import gettext_lazy as _
  6from django.views import View
  7from rest_framework.serializers import BaseSerializer
  8
  9from authentik.flows.models import NotConfiguredAction, Stage
 10from authentik.lib.models import SimpleThroughModel
 11from authentik.lib.utils.time import timedelta_string_validator
 12from authentik.stages.authenticator_webauthn.models import UserVerification, WebAuthnHint
 13from authentik.stages.authenticator_webauthn.utils import validate_webauthn_origin
 14
 15
 16class DeviceClasses(models.TextChoices):
 17    """Device classes this stage can validate"""
 18
 19    # device class must match Device's class name so StaticDevice -> static
 20    STATIC = "static", _("Static")
 21    TOTP = "totp", _("TOTP")
 22    WEBAUTHN = "webauthn", _("WebAuthn")
 23    DUO = "duo", _("Duo")
 24    SMS = "sms", _("SMS")
 25    EMAIL = "email", _("Email")
 26
 27    @staticmethod
 28    def from_model_label(model_label: str) -> DeviceClasses:
 29        return getattr(
 30            DeviceClasses, model_label.rsplit(".", maxsplit=1)[-1][: -len("device")].upper()
 31        )
 32
 33
 34def default_device_classes() -> list:
 35    """By default, accept all device classes"""
 36    return [
 37        DeviceClasses.STATIC,
 38        DeviceClasses.TOTP,
 39        DeviceClasses.WEBAUTHN,
 40        DeviceClasses.DUO,
 41        DeviceClasses.SMS,
 42        DeviceClasses.EMAIL,
 43    ]
 44
 45
 46class AuthenticatorValidateStage(Stage):
 47    """Validate user's configured Multi Factor Authentication."""
 48
 49    not_configured_action = models.TextField(
 50        choices=NotConfiguredAction.choices, default=NotConfiguredAction.SKIP
 51    )
 52
 53    configuration_stages = models.ManyToManyField(
 54        Stage,
 55        blank=True,
 56        default=None,
 57        related_name="+",
 58        help_text=_(
 59            "Stages used to configure Authenticator when user doesn't have any compatible "
 60            "devices. After this configuration Stage passes, the user is not prompted again."
 61        ),
 62        through="AuthenticatorValidateStageConfigurationStage",
 63    )
 64
 65    device_classes = ArrayField(
 66        models.TextField(choices=DeviceClasses.choices),
 67        help_text=_("Device classes which can be used to authenticate"),
 68        default=default_device_classes,
 69    )
 70
 71    last_auth_threshold = models.TextField(
 72        default="seconds=0",
 73        validators=[timedelta_string_validator],
 74        help_text=_(
 75            "If any of the user's device has been used within this threshold, this "
 76            "stage will be skipped"
 77        ),
 78    )
 79
 80    webauthn_user_verification = models.TextField(
 81        help_text=_("Enforce user verification for WebAuthn devices."),
 82        choices=UserVerification.choices,
 83        default=UserVerification.PREFERRED,
 84    )
 85    webauthn_hints = ArrayField(
 86        models.TextField(choices=WebAuthnHint.choices),
 87        default=list,
 88        blank=True,
 89    )
 90    webauthn_additional_accepted_origins = ArrayField(
 91        models.TextField(validators=[validate_webauthn_origin]),
 92        default=list,
 93        db_default=[],
 94        blank=True,
 95        help_text=_("Additional trusted origins for WebAuthn authentication. Matched exactly."),
 96    )
 97    webauthn_allowed_device_types = models.ManyToManyField(
 98        "authentik_stages_authenticator_webauthn.WebAuthnDeviceType",
 99        blank=True,
100        through="AuthenticatorValidateStageWebAuthnAllowedDeviceType",
101    )
102
103    email_otp_throttling_factor = models.FloatField(default=1)
104    sms_otp_throttling_factor = models.FloatField(default=1)
105    totp_otp_throttling_factor = models.FloatField(default=1)
106    static_otp_throttling_factor = models.FloatField(default=1)
107
108    @property
109    def serializer(self) -> type[BaseSerializer]:
110        from authentik.stages.authenticator_validate.api import AuthenticatorValidateStageSerializer
111
112        return AuthenticatorValidateStageSerializer
113
114    @property
115    def view(self) -> type[View]:
116        from authentik.stages.authenticator_validate.stage import AuthenticatorValidateStageView
117
118        return AuthenticatorValidateStageView
119
120    @property
121    def component(self) -> str:
122        return "ak-stage-authenticator-validate-form"
123
124    def get_throttling_factor(self, device_class: DeviceClasses) -> float | None:
125        if device_class == DeviceClasses.EMAIL:
126            return self.email_otp_throttling_factor
127        elif device_class == DeviceClasses.SMS:
128            return self.sms_otp_throttling_factor
129        elif device_class == DeviceClasses.TOTP:
130            return self.totp_otp_throttling_factor
131        elif device_class == DeviceClasses.STATIC:
132            return self.static_otp_throttling_factor
133        return None
134
135    class Meta:
136        verbose_name = _("Authenticator Validation Stage")
137        verbose_name_plural = _("Authenticator Validation Stages")
138
139
140class AuthenticatorValidateStageConfigurationStage(SimpleThroughModel):
141    authenticator_validate_stage = models.ForeignKey(
142        AuthenticatorValidateStage,
143        on_delete=models.CASCADE,
144        related_name="configuration_stage_m2m_objects",
145        db_column="authenticatorvalidatestage_id",
146    )
147    configuration_stage = models.ForeignKey(
148        Stage,
149        on_delete=models.CASCADE,
150        related_name="authenticator_validate_stage_m2m_objects",
151        db_column="stage_id",
152    )
153
154    class Meta:
155        db_table = "authentik_stages_authenticator_validate_authenticatorvalida3e25"
156        unique_together = (("authenticator_validate_stage", "configuration_stage"),)
157        verbose_name = _("Authenticator Validate Stage Configuration Stage")
158        verbose_name_plural = _("Authenticator Validate Stage Configuration Stages")
159
160    def __str__(self):
161        return (
162            "AuthenticatorValidateStageConfigurationStage for AuthenticatorValidateStage "
163            f"{self.authenticator_validate_stage_id} "
164            f"and ConfigurationStage {self.configuration_stage_id}."
165        )
166
167
168class AuthenticatorValidateStageWebAuthnAllowedDeviceType(SimpleThroughModel):
169    authenticator_validate_stage = models.ForeignKey(
170        AuthenticatorValidateStage,
171        on_delete=models.CASCADE,
172        related_name="webauthn_allowed_device_types_m2m_objects",
173        db_column="authenticatorvalidatestage_id",
174    )
175    webauthn_allowed_device_type = models.ForeignKey(
176        "authentik_stages_authenticator_webauthn.WebAuthnDeviceType",
177        on_delete=models.CASCADE,
178        related_name="authenticator_validate_stage_m2m_objects",
179        db_column="webauthndevicetype_id",
180    )
181
182    class Meta:
183        db_table = "authentik_stages_authenticator_validate_authenticatorvalida8318"
184        unique_together = (("authenticator_validate_stage", "webauthn_allowed_device_type"),)
185        verbose_name = _("Authenticator Validate Stage WebAuthn Allowed Device Type")
186        verbose_name_plural = _("Authenticator Validate Stage WebAuthn Allowed Device Types")
187
188    def __str__(self):
189        return (
190            "AuthenticatorValidateStageConfigurationStage for AuthenticatorValidateStage "
191            f"{self.authenticator_validate_stage_id} "
192            f"and WebAuthnAllowedDeviceType {self.webauthn_allowed_device_type_id}."
193        )
class DeviceClasses(django.db.models.enums.TextChoices):
17class DeviceClasses(models.TextChoices):
18    """Device classes this stage can validate"""
19
20    # device class must match Device's class name so StaticDevice -> static
21    STATIC = "static", _("Static")
22    TOTP = "totp", _("TOTP")
23    WEBAUTHN = "webauthn", _("WebAuthn")
24    DUO = "duo", _("Duo")
25    SMS = "sms", _("SMS")
26    EMAIL = "email", _("Email")
27
28    @staticmethod
29    def from_model_label(model_label: str) -> DeviceClasses:
30        return getattr(
31            DeviceClasses, model_label.rsplit(".", maxsplit=1)[-1][: -len("device")].upper()
32        )

Device classes this stage can validate

@staticmethod
def from_model_label( model_label: str) -> DeviceClasses:
28    @staticmethod
29    def from_model_label(model_label: str) -> DeviceClasses:
30        return getattr(
31            DeviceClasses, model_label.rsplit(".", maxsplit=1)[-1][: -len("device")].upper()
32        )
def default_device_classes() -> list:
35def default_device_classes() -> list:
36    """By default, accept all device classes"""
37    return [
38        DeviceClasses.STATIC,
39        DeviceClasses.TOTP,
40        DeviceClasses.WEBAUTHN,
41        DeviceClasses.DUO,
42        DeviceClasses.SMS,
43        DeviceClasses.EMAIL,
44    ]

By default, accept all device classes

class AuthenticatorValidateStage(authentik.flows.models.Stage):
 47class AuthenticatorValidateStage(Stage):
 48    """Validate user's configured Multi Factor Authentication."""
 49
 50    not_configured_action = models.TextField(
 51        choices=NotConfiguredAction.choices, default=NotConfiguredAction.SKIP
 52    )
 53
 54    configuration_stages = models.ManyToManyField(
 55        Stage,
 56        blank=True,
 57        default=None,
 58        related_name="+",
 59        help_text=_(
 60            "Stages used to configure Authenticator when user doesn't have any compatible "
 61            "devices. After this configuration Stage passes, the user is not prompted again."
 62        ),
 63        through="AuthenticatorValidateStageConfigurationStage",
 64    )
 65
 66    device_classes = ArrayField(
 67        models.TextField(choices=DeviceClasses.choices),
 68        help_text=_("Device classes which can be used to authenticate"),
 69        default=default_device_classes,
 70    )
 71
 72    last_auth_threshold = models.TextField(
 73        default="seconds=0",
 74        validators=[timedelta_string_validator],
 75        help_text=_(
 76            "If any of the user's device has been used within this threshold, this "
 77            "stage will be skipped"
 78        ),
 79    )
 80
 81    webauthn_user_verification = models.TextField(
 82        help_text=_("Enforce user verification for WebAuthn devices."),
 83        choices=UserVerification.choices,
 84        default=UserVerification.PREFERRED,
 85    )
 86    webauthn_hints = ArrayField(
 87        models.TextField(choices=WebAuthnHint.choices),
 88        default=list,
 89        blank=True,
 90    )
 91    webauthn_additional_accepted_origins = ArrayField(
 92        models.TextField(validators=[validate_webauthn_origin]),
 93        default=list,
 94        db_default=[],
 95        blank=True,
 96        help_text=_("Additional trusted origins for WebAuthn authentication. Matched exactly."),
 97    )
 98    webauthn_allowed_device_types = models.ManyToManyField(
 99        "authentik_stages_authenticator_webauthn.WebAuthnDeviceType",
100        blank=True,
101        through="AuthenticatorValidateStageWebAuthnAllowedDeviceType",
102    )
103
104    email_otp_throttling_factor = models.FloatField(default=1)
105    sms_otp_throttling_factor = models.FloatField(default=1)
106    totp_otp_throttling_factor = models.FloatField(default=1)
107    static_otp_throttling_factor = models.FloatField(default=1)
108
109    @property
110    def serializer(self) -> type[BaseSerializer]:
111        from authentik.stages.authenticator_validate.api import AuthenticatorValidateStageSerializer
112
113        return AuthenticatorValidateStageSerializer
114
115    @property
116    def view(self) -> type[View]:
117        from authentik.stages.authenticator_validate.stage import AuthenticatorValidateStageView
118
119        return AuthenticatorValidateStageView
120
121    @property
122    def component(self) -> str:
123        return "ak-stage-authenticator-validate-form"
124
125    def get_throttling_factor(self, device_class: DeviceClasses) -> float | None:
126        if device_class == DeviceClasses.EMAIL:
127            return self.email_otp_throttling_factor
128        elif device_class == DeviceClasses.SMS:
129            return self.sms_otp_throttling_factor
130        elif device_class == DeviceClasses.TOTP:
131            return self.totp_otp_throttling_factor
132        elif device_class == DeviceClasses.STATIC:
133            return self.static_otp_throttling_factor
134        return None
135
136    class Meta:
137        verbose_name = _("Authenticator Validation Stage")
138        verbose_name_plural = _("Authenticator Validation Stages")

Validate user's configured Multi Factor Authentication.

def not_configured_action(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

configuration_stages

Accessor to the related objects manager on the forward and reverse sides of a many-to-many relation.

In the example::

class Pizza(Model):
    toppings = ManyToManyField(Topping, related_name='pizzas')

Pizza.toppings and Topping.pizzas are ManyToManyDescriptor instances.

Most of the implementation is delegated to a dynamically defined manager class built by create_forward_many_to_many_manager() defined below.

def device_classes(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

def last_auth_threshold(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

def webauthn_user_verification(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

def webauthn_hints(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

def webauthn_additional_accepted_origins(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

webauthn_allowed_device_types

Accessor to the related objects manager on the forward and reverse sides of a many-to-many relation.

In the example::

class Pizza(Model):
    toppings = ManyToManyField(Topping, related_name='pizzas')

Pizza.toppings and Topping.pizzas are ManyToManyDescriptor instances.

Most of the implementation is delegated to a dynamically defined manager class built by create_forward_many_to_many_manager() defined below.

def email_otp_throttling_factor(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

def sms_otp_throttling_factor(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

def totp_otp_throttling_factor(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

def static_otp_throttling_factor(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

serializer: type[rest_framework.serializers.BaseSerializer]
109    @property
110    def serializer(self) -> type[BaseSerializer]:
111        from authentik.stages.authenticator_validate.api import AuthenticatorValidateStageSerializer
112
113        return AuthenticatorValidateStageSerializer

Get serializer for this model

view: type[django.views.generic.base.View]
115    @property
116    def view(self) -> type[View]:
117        from authentik.stages.authenticator_validate.stage import AuthenticatorValidateStageView
118
119        return AuthenticatorValidateStageView

Return StageView class that implements logic for this stage

component: str
121    @property
122    def component(self) -> str:
123        return "ak-stage-authenticator-validate-form"

Return component used to edit this object

def get_throttling_factor( self, device_class: DeviceClasses) -> float | None:
125    def get_throttling_factor(self, device_class: DeviceClasses) -> float | None:
126        if device_class == DeviceClasses.EMAIL:
127            return self.email_otp_throttling_factor
128        elif device_class == DeviceClasses.SMS:
129            return self.sms_otp_throttling_factor
130        elif device_class == DeviceClasses.TOTP:
131            return self.totp_otp_throttling_factor
132        elif device_class == DeviceClasses.STATIC:
133            return self.static_otp_throttling_factor
134        return None
def get_not_configured_action_display(unknown):

Method descriptor with partial application of the given arguments and keywords.

Supports wrapping existing descriptors and handles non-descriptor callables as instance methods.

def get_webauthn_user_verification_display(unknown):

Method descriptor with partial application of the given arguments and keywords.

Supports wrapping existing descriptors and handles non-descriptor callables as instance methods.

stage_ptr_id
stage_ptr

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.

configuration_stage_m2m_objects

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.

webauthn_allowed_device_types_m2m_objects

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.

identificationstage_set

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.

class AuthenticatorValidateStage.DoesNotExist(authentik.flows.models.Stage.DoesNotExist):

The requested object does not exist

class AuthenticatorValidateStage.MultipleObjectsReturned(authentik.flows.models.Stage.MultipleObjectsReturned):

The query returned multiple objects when only one was expected.

class AuthenticatorValidateStageConfigurationStage(authentik.lib.models.SimpleThroughModel):
141class AuthenticatorValidateStageConfigurationStage(SimpleThroughModel):
142    authenticator_validate_stage = models.ForeignKey(
143        AuthenticatorValidateStage,
144        on_delete=models.CASCADE,
145        related_name="configuration_stage_m2m_objects",
146        db_column="authenticatorvalidatestage_id",
147    )
148    configuration_stage = models.ForeignKey(
149        Stage,
150        on_delete=models.CASCADE,
151        related_name="authenticator_validate_stage_m2m_objects",
152        db_column="stage_id",
153    )
154
155    class Meta:
156        db_table = "authentik_stages_authenticator_validate_authenticatorvalida3e25"
157        unique_together = (("authenticator_validate_stage", "configuration_stage"),)
158        verbose_name = _("Authenticator Validate Stage Configuration Stage")
159        verbose_name_plural = _("Authenticator Validate Stage Configuration Stages")
160
161    def __str__(self):
162        return (
163            "AuthenticatorValidateStageConfigurationStage for AuthenticatorValidateStage "
164            f"{self.authenticator_validate_stage_id} "
165            f"and ConfigurationStage {self.configuration_stage_id}."
166        )

AuthenticatorValidateStageConfigurationStage(id, authenticator_validate_stage, configuration_stage)

authenticator_validate_stage

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.

configuration_stage

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.

authenticator_validate_stage_id
configuration_stage_id
def id(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

def objects(unknown):

The type of the None singleton.

class AuthenticatorValidateStageConfigurationStage.DoesNotExist(django.core.exceptions.ObjectDoesNotExist):

The requested object does not exist

class AuthenticatorValidateStageConfigurationStage.MultipleObjectsReturned(django.core.exceptions.MultipleObjectsReturned):

The query returned multiple objects when only one was expected.

class AuthenticatorValidateStageWebAuthnAllowedDeviceType(authentik.lib.models.SimpleThroughModel):
169class AuthenticatorValidateStageWebAuthnAllowedDeviceType(SimpleThroughModel):
170    authenticator_validate_stage = models.ForeignKey(
171        AuthenticatorValidateStage,
172        on_delete=models.CASCADE,
173        related_name="webauthn_allowed_device_types_m2m_objects",
174        db_column="authenticatorvalidatestage_id",
175    )
176    webauthn_allowed_device_type = models.ForeignKey(
177        "authentik_stages_authenticator_webauthn.WebAuthnDeviceType",
178        on_delete=models.CASCADE,
179        related_name="authenticator_validate_stage_m2m_objects",
180        db_column="webauthndevicetype_id",
181    )
182
183    class Meta:
184        db_table = "authentik_stages_authenticator_validate_authenticatorvalida8318"
185        unique_together = (("authenticator_validate_stage", "webauthn_allowed_device_type"),)
186        verbose_name = _("Authenticator Validate Stage WebAuthn Allowed Device Type")
187        verbose_name_plural = _("Authenticator Validate Stage WebAuthn Allowed Device Types")
188
189    def __str__(self):
190        return (
191            "AuthenticatorValidateStageConfigurationStage for AuthenticatorValidateStage "
192            f"{self.authenticator_validate_stage_id} "
193            f"and WebAuthnAllowedDeviceType {self.webauthn_allowed_device_type_id}."
194        )

AuthenticatorValidateStageWebAuthnAllowedDeviceType(id, authenticator_validate_stage, webauthn_allowed_device_type)

authenticator_validate_stage

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.

webauthn_allowed_device_type

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.

authenticator_validate_stage_id
webauthn_allowed_device_type_id
def id(unknown):

A wrapper for a deferred-loading field. When the value is read from this object the first time, the query is executed.

def objects(unknown):

The type of the None singleton.

class AuthenticatorValidateStageWebAuthnAllowedDeviceType.DoesNotExist(django.core.exceptions.ObjectDoesNotExist):

The requested object does not exist

class AuthenticatorValidateStageWebAuthnAllowedDeviceType.MultipleObjectsReturned(django.core.exceptions.MultipleObjectsReturned):

The query returned multiple objects when only one was expected.