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()
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.
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.
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
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
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.
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.
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.
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.
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
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
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.
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.
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.
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 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
The requested object does not exist
The query returned multiple objects when only one was expected.
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.
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 @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
The requested object does not exist
The query returned multiple objects when only one was expected.