authentik.stages.authenticator_static.models

Static Authenticator models

  1"""Static Authenticator models"""
  2
  3from base64 import b32encode
  4from os import urandom
  5from re import compile as re_compile
  6
  7from django.core.validators import MaxValueValidator
  8from django.db import models
  9from django.utils.translation import gettext_lazy as _
 10from django.views import View
 11from rest_framework.serializers import BaseSerializer
 12
 13from authentik.core.types import UserSettingSerializer
 14from authentik.flows.models import ConfigurableStage, FriendlyNamedStage, Stage
 15from authentik.lib.models import SerializerModel
 16from authentik.stages.authenticator.models import Device, ThrottlingMixin
 17
 18# Tokens are displayed in hyphenated groups and are often typed by hand, so separators
 19# are accepted on input. Generated tokens are alphanumeric, so removing these never
 20# changes which token matches.
 21TOKEN_SEPARATORS = re_compile(r"[\s-]")
 22
 23
 24class AuthenticatorStaticStage(ConfigurableStage, FriendlyNamedStage, Stage):
 25    """Setup static token based authentication for the user."""
 26
 27    token_count = models.PositiveIntegerField(default=6)
 28    token_length = models.PositiveIntegerField(default=12, validators=[MaxValueValidator(100)])
 29
 30    @property
 31    def serializer(self) -> type[BaseSerializer]:
 32        from authentik.stages.authenticator_static.api import AuthenticatorStaticStageSerializer
 33
 34        return AuthenticatorStaticStageSerializer
 35
 36    @property
 37    def view(self) -> type[View]:
 38        from authentik.stages.authenticator_static.stage import AuthenticatorStaticStageView
 39
 40        return AuthenticatorStaticStageView
 41
 42    @property
 43    def component(self) -> str:
 44        return "ak-stage-authenticator-static-form"
 45
 46    def ui_user_settings(self) -> UserSettingSerializer | None:
 47        return UserSettingSerializer(
 48            data={
 49                "title": self.friendly_name or str(self._meta.verbose_name),
 50                "component": "ak-user-settings-authenticator-static",
 51            }
 52        )
 53
 54    def __str__(self) -> str:
 55        return f"Static Authenticator Setup Stage {self.name}"
 56
 57    class Meta:
 58        verbose_name = _("Static Authenticator Setup Stage")
 59        verbose_name_plural = _("Static Authenticator Setup Stages")
 60
 61
 62class StaticDevice(SerializerModel, ThrottlingMixin, Device):
 63    """
 64    A static :class:`~authentik.stages.authenticator.models.Device` simply consists of random
 65    tokens shared by the database and the user.
 66
 67    These are frequently used as emergency tokens in case a user's normal
 68    device is lost or unavailable. They can be consumed in any order; each
 69    token will be removed from the database as soon as it is used.
 70
 71    This model has no fields of its own, but serves as a container for
 72    :class:`StaticToken` objects.
 73
 74    .. attribute:: token_set
 75
 76        The RelatedManager for our tokens.
 77
 78    """
 79
 80    @property
 81    def serializer(self) -> type[BaseSerializer]:
 82        from authentik.stages.authenticator_static.api import StaticDeviceSerializer
 83
 84        return StaticDeviceSerializer
 85
 86    def verify_token(self, token):
 87        verify_allowed, _ = self.verify_is_allowed()
 88        if verify_allowed:
 89            candidates = {token, TOKEN_SEPARATORS.sub("", token)} - {""}
 90            match = self.token_set.filter(token__in=candidates).first()
 91            if match is not None:
 92                match.delete()
 93                self.throttle_reset()
 94            else:
 95                self.throttle_increment()
 96        else:
 97            match = None
 98
 99        return match is not None
100
101    class Meta(Device.Meta):
102        verbose_name = _("Static Device")
103        verbose_name_plural = _("Static Devices")
104
105
106class StaticToken(models.Model):
107    """
108    A single token belonging to a :class:`StaticDevice`.
109
110    .. attribute:: device
111
112        *ForeignKey*: A foreign key to :class:`StaticDevice`.
113
114    .. attribute:: token
115
116        *CharField*: A random string up to 100 characters.
117    """
118
119    device = models.ForeignKey(StaticDevice, related_name="token_set", on_delete=models.CASCADE)
120    token = models.CharField(max_length=100, db_index=True)
121
122    class Meta:
123        verbose_name = _("Static Token")
124        verbose_name_plural = _("Static Tokens")
125
126    def __str__(self) -> str:
127        return "Static Token"
128
129    @staticmethod
130    def random_token():
131        """
132        Returns a new random string that can be used as a static token.
133
134        :rtype: bytes
135
136        """
137        return b32encode(urandom(5)).decode("utf-8").lower()
TOKEN_SEPARATORS = re.compile('[\\s-]')
25class AuthenticatorStaticStage(ConfigurableStage, FriendlyNamedStage, Stage):
26    """Setup static token based authentication for the user."""
27
28    token_count = models.PositiveIntegerField(default=6)
29    token_length = models.PositiveIntegerField(default=12, validators=[MaxValueValidator(100)])
30
31    @property
32    def serializer(self) -> type[BaseSerializer]:
33        from authentik.stages.authenticator_static.api import AuthenticatorStaticStageSerializer
34
35        return AuthenticatorStaticStageSerializer
36
37    @property
38    def view(self) -> type[View]:
39        from authentik.stages.authenticator_static.stage import AuthenticatorStaticStageView
40
41        return AuthenticatorStaticStageView
42
43    @property
44    def component(self) -> str:
45        return "ak-stage-authenticator-static-form"
46
47    def ui_user_settings(self) -> UserSettingSerializer | None:
48        return UserSettingSerializer(
49            data={
50                "title": self.friendly_name or str(self._meta.verbose_name),
51                "component": "ak-user-settings-authenticator-static",
52            }
53        )
54
55    def __str__(self) -> str:
56        return f"Static Authenticator Setup Stage {self.name}"
57
58    class Meta:
59        verbose_name = _("Static Authenticator Setup Stage")
60        verbose_name_plural = _("Static Authenticator Setup Stages")

Setup static token based authentication for the user.

def token_count(unknown):

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

def token_length(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]
31    @property
32    def serializer(self) -> type[BaseSerializer]:
33        from authentik.stages.authenticator_static.api import AuthenticatorStaticStageSerializer
34
35        return AuthenticatorStaticStageSerializer

Get serializer for this model

view: type[django.views.generic.base.View]
37    @property
38    def view(self) -> type[View]:
39        from authentik.stages.authenticator_static.stage import AuthenticatorStaticStageView
40
41        return AuthenticatorStaticStageView

Return StageView class that implements logic for this stage

component: str
43    @property
44    def component(self) -> str:
45        return "ak-stage-authenticator-static-form"

Return component used to edit this object

def ui_user_settings(self) -> authentik.core.types.UserSettingSerializer | None:
47    def ui_user_settings(self) -> UserSettingSerializer | None:
48        return UserSettingSerializer(
49            data={
50                "title": self.friendly_name or str(self._meta.verbose_name),
51                "component": "ak-user-settings-authenticator-static",
52            }
53        )

Entrypoint to integrate with User settings. Can either return None if no user settings are available, or a challenge.

configure_flow

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.

def friendly_name(unknown):

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

configure_flow_id
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.

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

The requested object does not exist

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

The query returned multiple objects when only one was expected.

 63class StaticDevice(SerializerModel, ThrottlingMixin, Device):
 64    """
 65    A static :class:`~authentik.stages.authenticator.models.Device` simply consists of random
 66    tokens shared by the database and the user.
 67
 68    These are frequently used as emergency tokens in case a user's normal
 69    device is lost or unavailable. They can be consumed in any order; each
 70    token will be removed from the database as soon as it is used.
 71
 72    This model has no fields of its own, but serves as a container for
 73    :class:`StaticToken` objects.
 74
 75    .. attribute:: token_set
 76
 77        The RelatedManager for our tokens.
 78
 79    """
 80
 81    @property
 82    def serializer(self) -> type[BaseSerializer]:
 83        from authentik.stages.authenticator_static.api import StaticDeviceSerializer
 84
 85        return StaticDeviceSerializer
 86
 87    def verify_token(self, token):
 88        verify_allowed, _ = self.verify_is_allowed()
 89        if verify_allowed:
 90            candidates = {token, TOKEN_SEPARATORS.sub("", token)} - {""}
 91            match = self.token_set.filter(token__in=candidates).first()
 92            if match is not None:
 93                match.delete()
 94                self.throttle_reset()
 95            else:
 96                self.throttle_increment()
 97        else:
 98            match = None
 99
100        return match is not None
101
102    class Meta(Device.Meta):
103        verbose_name = _("Static Device")
104        verbose_name_plural = _("Static Devices")

A static :class:~authentik.stages.authenticator.models.Device simply consists of random tokens shared by the database and the user.

These are frequently used as emergency tokens in case a user's normal device is lost or unavailable. They can be consumed in any order; each token will be removed from the database as soon as it is used.

This model has no fields of its own, but serves as a container for :class:StaticToken objects.

.. attribute:: token_set

The RelatedManager for our tokens.
serializer: type[rest_framework.serializers.BaseSerializer]
81    @property
82    def serializer(self) -> type[BaseSerializer]:
83        from authentik.stages.authenticator_static.api import StaticDeviceSerializer
84
85        return StaticDeviceSerializer

Get serializer for this model

def verify_token(self, token):
 87    def verify_token(self, token):
 88        verify_allowed, _ = self.verify_is_allowed()
 89        if verify_allowed:
 90            candidates = {token, TOKEN_SEPARATORS.sub("", token)} - {""}
 91            match = self.token_set.filter(token__in=candidates).first()
 92            if match is not None:
 93                match.delete()
 94                self.throttle_reset()
 95            else:
 96                self.throttle_increment()
 97        else:
 98            match = None
 99
100        return match is not None

Verifies a token. As a rule, the token should no longer be valid if this returns True.

:param str token: The OTP token provided by the user. :rtype: bool

def throttling_failure_timestamp(unknown):

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

def throttling_failure_count(unknown):

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

user

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.

def name(unknown):

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

def confirmed(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_used(unknown):

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

def created(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_updated(unknown):

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

def get_next_by_created(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_previous_by_created(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_next_by_last_updated(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_previous_by_last_updated(unknown):

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

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

user_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.

token_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 StaticDevice.DoesNotExist(django.core.exceptions.ObjectDoesNotExist):

The requested object does not exist

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

The query returned multiple objects when only one was expected.

class StaticToken(django.db.models.base.Model):
107class StaticToken(models.Model):
108    """
109    A single token belonging to a :class:`StaticDevice`.
110
111    .. attribute:: device
112
113        *ForeignKey*: A foreign key to :class:`StaticDevice`.
114
115    .. attribute:: token
116
117        *CharField*: A random string up to 100 characters.
118    """
119
120    device = models.ForeignKey(StaticDevice, related_name="token_set", on_delete=models.CASCADE)
121    token = models.CharField(max_length=100, db_index=True)
122
123    class Meta:
124        verbose_name = _("Static Token")
125        verbose_name_plural = _("Static Tokens")
126
127    def __str__(self) -> str:
128        return "Static Token"
129
130    @staticmethod
131    def random_token():
132        """
133        Returns a new random string that can be used as a static token.
134
135        :rtype: bytes
136
137        """
138        return b32encode(urandom(5)).decode("utf-8").lower()

A single token belonging to a :class:StaticDevice.

.. attribute:: device

*ForeignKey*: A foreign key to :class:`StaticDevice`.

.. attribute:: token

*CharField*: A random string up to 100 characters.
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.

def token(unknown):

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

@staticmethod
def random_token():
130    @staticmethod
131    def random_token():
132        """
133        Returns a new random string that can be used as a static token.
134
135        :rtype: bytes
136
137        """
138        return b32encode(urandom(5)).decode("utf-8").lower()

Returns a new random string that can be used as a static token.

:rtype: bytes

device_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 StaticToken.DoesNotExist(django.core.exceptions.ObjectDoesNotExist):

The requested object does not exist

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

The query returned multiple objects when only one was expected.