authentik.stages.authenticator.models
Base authenticator models
1"""Base authenticator models""" 2 3from datetime import timedelta 4 5from django.apps import apps 6from django.core.exceptions import ObjectDoesNotExist 7from django.db import models 8from django.utils import timezone 9from django.utils.functional import cached_property 10 11from authentik.core.models import User 12from authentik.lib.models import CreatedUpdatedModel 13from authentik.stages.authenticator.util import random_number_token 14 15 16class DeviceManager(models.Manager): 17 """ 18 The :class:`~django.db.models.Manager` object installed as 19 ``Device.objects``. 20 """ 21 22 def devices_for_user(self, user: User, confirmed: bool | None = None): 23 """ 24 Returns a queryset for all devices of this class that belong to the 25 given user. 26 27 :param user: The user. 28 :type user: :class:`~django.contrib.auth.models.User` 29 30 :param confirmed: If ``None``, all matching devices are returned. 31 Otherwise, this can be any true or false value to limit the query 32 to confirmed or unconfirmed devices, respectively. 33 """ 34 devices = self.model.objects.filter(user=user) 35 if confirmed is not None: 36 devices = devices.filter(confirmed=bool(confirmed)) 37 38 return devices 39 40 41class Device(CreatedUpdatedModel): 42 """ 43 Abstract base model for a :term:`device` attached to a user. Plugins must 44 subclass this to define their OTP models. 45 46 .. _unsaved_device_warning: 47 48 .. warning:: 49 50 OTP devices are inherently stateful. For example, verifying a token is 51 logically a mutating operation on the device, which may involve 52 incrementing a counter or otherwise consuming a token. A device must be 53 committed to the database before it can be used in any way. 54 55 .. attribute:: user 56 57 *ForeignKey*: Foreign key to your user model, as configured by 58 :setting:`AUTH_USER_MODEL` (:class:`~django.contrib.auth.models.User` 59 by default). 60 61 .. attribute:: name 62 63 *CharField*: A human-readable name to help the user identify their 64 devices. 65 66 .. attribute:: confirmed 67 68 *BooleanField*: A boolean value that tells us whether this device has 69 been confirmed as valid. It defaults to ``True``, but subclasses or 70 individual deployments can force it to ``False`` if they wish to create 71 a device and then ask the user for confirmation. As a rule, built-in 72 APIs that enumerate devices will only include those that are confirmed. 73 74 .. attribute:: objects 75 76 A :class:`~authentik.stages.authenticator.models.DeviceManager`. 77 """ 78 79 user = models.ForeignKey( 80 User, 81 help_text="The user that this device belongs to.", 82 on_delete=models.CASCADE, 83 ) 84 85 name = models.CharField(max_length=64, help_text="The human-readable name of this device.") 86 87 confirmed = models.BooleanField(default=True, help_text="Is this device ready for use?") 88 89 last_used = models.DateTimeField(null=True) 90 91 objects = DeviceManager() 92 93 class Meta: 94 abstract = True 95 96 def __str__(self): 97 try: 98 user = self.user 99 except ObjectDoesNotExist: 100 user = None 101 102 return f"{self.name} ({user})" 103 104 @property 105 def persistent_id(self): 106 """ 107 A stable device identifier for forms and APIs. 108 """ 109 return f"{self.model_label()}/{self.id}" 110 111 @classmethod 112 def model_label(cls): 113 """ 114 Returns an identifier for this Django model class. 115 116 This is just the standard "<app_label>.<model_name>" form. 117 118 """ 119 return f"{cls._meta.app_label}.{cls._meta.model_name}" 120 121 @classmethod 122 def from_persistent_id(cls, persistent_id, for_verify=False): 123 """ 124 Loads a device from its persistent id:: 125 126 device == Device.from_persistent_id(device.persistent_id) 127 128 :param bool for_verify: If ``True``, we'll load the device with 129 :meth:`~django.db.models.query.QuerySet.select_for_update` to 130 prevent concurrent verifications from succeeding. In which case, 131 this must be called inside a transaction. 132 133 """ 134 from authentik.stages.password.models import PasswordDevice 135 136 device = None 137 138 try: 139 model_label, device_id = persistent_id.rsplit("/", 1) 140 app_label, model_name = model_label.split(".") 141 142 device_cls = apps.get_model(app_label, model_name) 143 if issubclass(device_cls, Device) and not issubclass(device_cls, PasswordDevice): 144 device_set = device_cls.objects.filter(id=int(device_id)) 145 if for_verify: 146 device_set = device_set.select_for_update() 147 device = device_set.first() 148 except ValueError, LookupError: 149 pass 150 151 return device 152 153 def is_interactive(self): 154 """ 155 Returns ``True`` if this is an interactive device. The default 156 implementation returns ``True`` if 157 :meth:`~authentik.stages.authenticator.models.Device.generate_challenge` has been 158 overridden, but subclasses are welcome to provide smarter 159 implementations. 160 161 :rtype: bool 162 """ 163 return not hasattr(self.generate_challenge, "stub") 164 165 def generate_challenge(self): 166 """ 167 Generates a challenge value that the user will need to produce a token. 168 This method is permitted to have side effects, such as transmitting 169 information to the user through some other channel (email or SMS, 170 perhaps). And, of course, some devices may need to commit the 171 challenge to the database. 172 173 :returns: A message to the user. This should be a string that fits 174 comfortably in the template ``'OTP Challenge: {0}'``. This may 175 return ``None`` if this device is not interactive. 176 :rtype: string or ``None`` 177 178 :raises: Any :exc:`~exceptions.Exception` is permitted. Callers should 179 trap ``Exception`` and report it to the user. 180 """ 181 return None 182 183 generate_challenge.stub = True 184 185 def verify_is_allowed(self): 186 """ 187 Checks whether it is permissible to call :meth:`verify_token`. If it is 188 allowed, returns ``(True, None)``. Otherwise returns ``(False, 189 data_dict)``, where ``data_dict`` contains extra information, defined 190 by the implementation. 191 192 This method can be used to implement throttling or locking, for 193 example. Client code should check this method before calling 194 :meth:`verify_token` and report problems to the user. 195 196 To report specific problems, the data dictionary can return include a 197 ``'reason'`` member with a value from the constants in 198 :class:`VerifyNotAllowed`. Otherwise, an ``'error_message'`` member 199 should be provided with an error message. 200 201 :meth:`verify_token` should also call this method and return False if 202 verification is not allowed. 203 204 :rtype: (bool, dict or ``None``) 205 206 """ 207 return (True, None) 208 209 def verify_token(self, token): 210 """ 211 Verifies a token. As a rule, the token should no longer be valid if 212 this returns ``True``. 213 214 :param str token: The OTP token provided by the user. 215 :rtype: bool 216 """ 217 return False 218 219 220class SideChannelDevice(Device): 221 """ 222 Abstract base model for a side-channel :term:`device` attached to a user. 223 224 This model implements token generation, verification and expiration, so the 225 concrete devices only have to implement delivery. 226 227 """ 228 229 token = models.CharField(max_length=16, blank=True, null=True) 230 231 valid_until = models.DateTimeField( 232 default=timezone.now, 233 help_text="The timestamp of the moment of expiry of the saved token.", 234 ) 235 236 class Meta: 237 abstract = True 238 239 def generate_token(self, length=6, valid_secs=300, commit=True): 240 """ 241 Generates a token of the specified length, then sets it on the model 242 and sets the expiration of the token on the model. 243 244 Pass 'commit=False' to avoid calling self.save(). 245 246 :param int length: Number of decimal digits in the generated token. 247 :param int valid_secs: Amount of seconds the token should be valid. 248 :param bool commit: Whether to autosave the generated token. 249 250 """ 251 self.token = random_number_token(length) 252 self.valid_until = timezone.now() + timedelta(seconds=valid_secs) 253 if commit: 254 self.save() 255 256 def verify_token(self, token): 257 """ 258 Verifies a token by content and expiry. 259 260 On success, the token is cleared and the device saved. 261 262 :param str token: The OTP token provided by the user. 263 :rtype: bool 264 265 """ 266 _now = timezone.now() 267 268 if (self.token is not None) and (token == self.token) and (_now < self.valid_until): 269 self.token = None 270 self.valid_until = _now 271 self.save() 272 273 return True 274 return False 275 276 277class VerifyNotAllowed: 278 """ 279 Constants that may be returned in the ``reason`` member of the extra 280 information dictionary returned by 281 :meth:`~authentik.stages.authenticator.models.Device.verify_is_allowed` 282 283 .. data:: N_FAILED_ATTEMPTS 284 285 Indicates that verification is disallowed because of ``n`` successive 286 failed attempts. The data dictionary should include the value of ``n`` 287 in member ``failure_count`` 288 289 """ 290 291 N_FAILED_ATTEMPTS = "N_FAILED_ATTEMPTS" 292 293 294class ThrottlingMixin(models.Model): 295 """ 296 Mixin class for models that want throttling behavior. 297 298 This implements exponential back-off for verifying tokens. Subclasses must 299 implement :meth:`get_throttle_factor`, and must use the 300 :meth:`verify_is_allowed`, :meth:`throttle_reset` and 301 :meth:`throttle_increment` methods from within their verify_token() method. 302 303 See the implementation of 304 :class:`~authentik.stages.authenticator.plugins.otp_email.models.EmailDevice` for an example. 305 306 """ 307 308 throttling_failure_timestamp = models.DateTimeField( 309 null=True, 310 blank=True, 311 default=None, 312 help_text=( 313 "A timestamp of the last failed verification attempt. " 314 "Null if last attempt succeeded." 315 ), 316 ) 317 318 throttling_failure_count = models.PositiveIntegerField( 319 default=0, help_text="Number of successive failed attempts." 320 ) 321 322 class Meta: 323 abstract = True 324 325 def verify_is_allowed(self): 326 """ 327 If verification is allowed, returns ``(True, None)``. 328 Otherwise, returns ``(False, data_dict)``. 329 330 ``data_dict`` contains further information. Currently it can be:: 331 332 { 333 'reason': VerifyNotAllowed.N_FAILED_ATTEMPTS, 334 'failure_count': n 335 } 336 337 where ``n`` is the number of successive failures. See 338 :class:`~authentik.stages.authenticator.models.VerifyNotAllowed`. 339 340 """ 341 if ( 342 self.throttling_enabled 343 and self.throttling_failure_count > 0 344 and self.throttling_failure_timestamp is not None 345 ): 346 now = timezone.now() 347 delay = (now - self.throttling_failure_timestamp).total_seconds() 348 # Required delays should be 1, 2, 4, 8 ... 349 delay_required = self.get_throttle_factor() * (2 ** (self.throttling_failure_count - 1)) 350 if delay < delay_required: 351 return ( 352 False, 353 { 354 "reason": VerifyNotAllowed.N_FAILED_ATTEMPTS, 355 "failure_count": self.throttling_failure_count, 356 "locked_until": self.throttling_failure_timestamp 357 + timedelta(seconds=delay_required), 358 }, 359 ) 360 361 return super().verify_is_allowed() 362 363 def throttle_reset(self, commit=True): 364 """ 365 Call this method to reset throttling (normally when a verify attempt 366 succeeded). 367 368 Pass 'commit=False' to avoid calling self.save(). 369 370 """ 371 self.throttling_failure_timestamp = None 372 self.throttling_failure_count = 0 373 if commit: 374 self.save() 375 376 def throttle_increment(self, commit=True): 377 """ 378 Call this method to increase throttling (normally when a verify attempt 379 failed). 380 381 Pass 'commit=False' to avoid calling self.save(). 382 383 """ 384 self.throttling_failure_timestamp = timezone.now() 385 self.throttling_failure_count += 1 386 if commit: 387 self.save() 388 389 @cached_property 390 def throttling_enabled(self) -> bool: 391 """Check if throttling is enabled""" 392 return self.get_throttle_factor() > 0 393 394 def get_throttle_factor(self) -> float: # pragma: no cover 395 """ 396 Returns the throttling factor. 397 """ 398 return getattr(self, "_throttle_factor", 1.0) 399 400 def set_throttle_factor(self, throttle_factor: float) -> None: 401 """ 402 Sets the throttle factor to use. Call this to override the default value of 1. 403 404 The number of seconds required between verification attempts will be 405 :math:`c2^{n-1}` where `c` is this factor and `n` is the number of 406 previous failures. A factor of 1 translates to delays of 1, 2, 4, 8, 407 etc. seconds. A factor of 0 disables the throttling. 408 """ 409 self._throttle_factor = throttle_factor
17class DeviceManager(models.Manager): 18 """ 19 The :class:`~django.db.models.Manager` object installed as 20 ``Device.objects``. 21 """ 22 23 def devices_for_user(self, user: User, confirmed: bool | None = None): 24 """ 25 Returns a queryset for all devices of this class that belong to the 26 given user. 27 28 :param user: The user. 29 :type user: :class:`~django.contrib.auth.models.User` 30 31 :param confirmed: If ``None``, all matching devices are returned. 32 Otherwise, this can be any true or false value to limit the query 33 to confirmed or unconfirmed devices, respectively. 34 """ 35 devices = self.model.objects.filter(user=user) 36 if confirmed is not None: 37 devices = devices.filter(confirmed=bool(confirmed)) 38 39 return devices
The :class:~django.db.models.Manager object installed as
Device.objects.
23 def devices_for_user(self, user: User, confirmed: bool | None = None): 24 """ 25 Returns a queryset for all devices of this class that belong to the 26 given user. 27 28 :param user: The user. 29 :type user: :class:`~django.contrib.auth.models.User` 30 31 :param confirmed: If ``None``, all matching devices are returned. 32 Otherwise, this can be any true or false value to limit the query 33 to confirmed or unconfirmed devices, respectively. 34 """ 35 devices = self.model.objects.filter(user=user) 36 if confirmed is not None: 37 devices = devices.filter(confirmed=bool(confirmed)) 38 39 return devices
Returns a queryset for all devices of this class that belong to the given user.
:param user: The user.
:type user: :class:~django.contrib.auth.models.User
:param confirmed: If None, all matching devices are returned.
Otherwise, this can be any true or false value to limit the query
to confirmed or unconfirmed devices, respectively.
42class Device(CreatedUpdatedModel): 43 """ 44 Abstract base model for a :term:`device` attached to a user. Plugins must 45 subclass this to define their OTP models. 46 47 .. _unsaved_device_warning: 48 49 .. warning:: 50 51 OTP devices are inherently stateful. For example, verifying a token is 52 logically a mutating operation on the device, which may involve 53 incrementing a counter or otherwise consuming a token. A device must be 54 committed to the database before it can be used in any way. 55 56 .. attribute:: user 57 58 *ForeignKey*: Foreign key to your user model, as configured by 59 :setting:`AUTH_USER_MODEL` (:class:`~django.contrib.auth.models.User` 60 by default). 61 62 .. attribute:: name 63 64 *CharField*: A human-readable name to help the user identify their 65 devices. 66 67 .. attribute:: confirmed 68 69 *BooleanField*: A boolean value that tells us whether this device has 70 been confirmed as valid. It defaults to ``True``, but subclasses or 71 individual deployments can force it to ``False`` if they wish to create 72 a device and then ask the user for confirmation. As a rule, built-in 73 APIs that enumerate devices will only include those that are confirmed. 74 75 .. attribute:: objects 76 77 A :class:`~authentik.stages.authenticator.models.DeviceManager`. 78 """ 79 80 user = models.ForeignKey( 81 User, 82 help_text="The user that this device belongs to.", 83 on_delete=models.CASCADE, 84 ) 85 86 name = models.CharField(max_length=64, help_text="The human-readable name of this device.") 87 88 confirmed = models.BooleanField(default=True, help_text="Is this device ready for use?") 89 90 last_used = models.DateTimeField(null=True) 91 92 objects = DeviceManager() 93 94 class Meta: 95 abstract = True 96 97 def __str__(self): 98 try: 99 user = self.user 100 except ObjectDoesNotExist: 101 user = None 102 103 return f"{self.name} ({user})" 104 105 @property 106 def persistent_id(self): 107 """ 108 A stable device identifier for forms and APIs. 109 """ 110 return f"{self.model_label()}/{self.id}" 111 112 @classmethod 113 def model_label(cls): 114 """ 115 Returns an identifier for this Django model class. 116 117 This is just the standard "<app_label>.<model_name>" form. 118 119 """ 120 return f"{cls._meta.app_label}.{cls._meta.model_name}" 121 122 @classmethod 123 def from_persistent_id(cls, persistent_id, for_verify=False): 124 """ 125 Loads a device from its persistent id:: 126 127 device == Device.from_persistent_id(device.persistent_id) 128 129 :param bool for_verify: If ``True``, we'll load the device with 130 :meth:`~django.db.models.query.QuerySet.select_for_update` to 131 prevent concurrent verifications from succeeding. In which case, 132 this must be called inside a transaction. 133 134 """ 135 from authentik.stages.password.models import PasswordDevice 136 137 device = None 138 139 try: 140 model_label, device_id = persistent_id.rsplit("/", 1) 141 app_label, model_name = model_label.split(".") 142 143 device_cls = apps.get_model(app_label, model_name) 144 if issubclass(device_cls, Device) and not issubclass(device_cls, PasswordDevice): 145 device_set = device_cls.objects.filter(id=int(device_id)) 146 if for_verify: 147 device_set = device_set.select_for_update() 148 device = device_set.first() 149 except ValueError, LookupError: 150 pass 151 152 return device 153 154 def is_interactive(self): 155 """ 156 Returns ``True`` if this is an interactive device. The default 157 implementation returns ``True`` if 158 :meth:`~authentik.stages.authenticator.models.Device.generate_challenge` has been 159 overridden, but subclasses are welcome to provide smarter 160 implementations. 161 162 :rtype: bool 163 """ 164 return not hasattr(self.generate_challenge, "stub") 165 166 def generate_challenge(self): 167 """ 168 Generates a challenge value that the user will need to produce a token. 169 This method is permitted to have side effects, such as transmitting 170 information to the user through some other channel (email or SMS, 171 perhaps). And, of course, some devices may need to commit the 172 challenge to the database. 173 174 :returns: A message to the user. This should be a string that fits 175 comfortably in the template ``'OTP Challenge: {0}'``. This may 176 return ``None`` if this device is not interactive. 177 :rtype: string or ``None`` 178 179 :raises: Any :exc:`~exceptions.Exception` is permitted. Callers should 180 trap ``Exception`` and report it to the user. 181 """ 182 return None 183 184 generate_challenge.stub = True 185 186 def verify_is_allowed(self): 187 """ 188 Checks whether it is permissible to call :meth:`verify_token`. If it is 189 allowed, returns ``(True, None)``. Otherwise returns ``(False, 190 data_dict)``, where ``data_dict`` contains extra information, defined 191 by the implementation. 192 193 This method can be used to implement throttling or locking, for 194 example. Client code should check this method before calling 195 :meth:`verify_token` and report problems to the user. 196 197 To report specific problems, the data dictionary can return include a 198 ``'reason'`` member with a value from the constants in 199 :class:`VerifyNotAllowed`. Otherwise, an ``'error_message'`` member 200 should be provided with an error message. 201 202 :meth:`verify_token` should also call this method and return False if 203 verification is not allowed. 204 205 :rtype: (bool, dict or ``None``) 206 207 """ 208 return (True, None) 209 210 def verify_token(self, token): 211 """ 212 Verifies a token. As a rule, the token should no longer be valid if 213 this returns ``True``. 214 215 :param str token: The OTP token provided by the user. 216 :rtype: bool 217 """ 218 return False
Abstract base model for a :term:device attached to a user. Plugins must
subclass this to define their OTP models.
.. _unsaved_device_warning:
.. warning::
OTP devices are inherently stateful. For example, verifying a token is
logically a mutating operation on the device, which may involve
incrementing a counter or otherwise consuming a token. A device must be
committed to the database before it can be used in any way.
.. attribute:: user
*ForeignKey*: Foreign key to your user model, as configured by
:setting:`AUTH_USER_MODEL` (:class:`~django.contrib.auth.models.User`
by default).
.. attribute:: name
*CharField*: A human-readable name to help the user identify their
devices.
.. attribute:: confirmed
*BooleanField*: A boolean value that tells us whether this device has
been confirmed as valid. It defaults to ``True``, but subclasses or
individual deployments can force it to ``False`` if they wish to create
a device and then ask the user for confirmation. As a rule, built-in
APIs that enumerate devices will only include those that are confirmed.
.. attribute:: objects
A :class:`~authentik.stages.authenticator.models.DeviceManager`.
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.
105 @property 106 def persistent_id(self): 107 """ 108 A stable device identifier for forms and APIs. 109 """ 110 return f"{self.model_label()}/{self.id}"
A stable device identifier for forms and APIs.
112 @classmethod 113 def model_label(cls): 114 """ 115 Returns an identifier for this Django model class. 116 117 This is just the standard "<app_label>.<model_name>" form. 118 119 """ 120 return f"{cls._meta.app_label}.{cls._meta.model_name}"
Returns an identifier for this Django model class.
This is just the standard "
122 @classmethod 123 def from_persistent_id(cls, persistent_id, for_verify=False): 124 """ 125 Loads a device from its persistent id:: 126 127 device == Device.from_persistent_id(device.persistent_id) 128 129 :param bool for_verify: If ``True``, we'll load the device with 130 :meth:`~django.db.models.query.QuerySet.select_for_update` to 131 prevent concurrent verifications from succeeding. In which case, 132 this must be called inside a transaction. 133 134 """ 135 from authentik.stages.password.models import PasswordDevice 136 137 device = None 138 139 try: 140 model_label, device_id = persistent_id.rsplit("/", 1) 141 app_label, model_name = model_label.split(".") 142 143 device_cls = apps.get_model(app_label, model_name) 144 if issubclass(device_cls, Device) and not issubclass(device_cls, PasswordDevice): 145 device_set = device_cls.objects.filter(id=int(device_id)) 146 if for_verify: 147 device_set = device_set.select_for_update() 148 device = device_set.first() 149 except ValueError, LookupError: 150 pass 151 152 return device
Loads a device from its persistent id::
device == Device.from_persistent_id(device.persistent_id)
:param bool for_verify: If True, we'll load the device with
:meth:~django.db.models.query.QuerySet.select_for_update to
prevent concurrent verifications from succeeding. In which case,
this must be called inside a transaction.
154 def is_interactive(self): 155 """ 156 Returns ``True`` if this is an interactive device. The default 157 implementation returns ``True`` if 158 :meth:`~authentik.stages.authenticator.models.Device.generate_challenge` has been 159 overridden, but subclasses are welcome to provide smarter 160 implementations. 161 162 :rtype: bool 163 """ 164 return not hasattr(self.generate_challenge, "stub")
Returns True if this is an interactive device. The default
implementation returns True if
:meth:~authentik.stages.authenticator.models.Device.generate_challenge has been
overridden, but subclasses are welcome to provide smarter
implementations.
:rtype: bool
166 def generate_challenge(self): 167 """ 168 Generates a challenge value that the user will need to produce a token. 169 This method is permitted to have side effects, such as transmitting 170 information to the user through some other channel (email or SMS, 171 perhaps). And, of course, some devices may need to commit the 172 challenge to the database. 173 174 :returns: A message to the user. This should be a string that fits 175 comfortably in the template ``'OTP Challenge: {0}'``. This may 176 return ``None`` if this device is not interactive. 177 :rtype: string or ``None`` 178 179 :raises: Any :exc:`~exceptions.Exception` is permitted. Callers should 180 trap ``Exception`` and report it to the user. 181 """ 182 return None
Generates a challenge value that the user will need to produce a token. This method is permitted to have side effects, such as transmitting information to the user through some other channel (email or SMS, perhaps). And, of course, some devices may need to commit the challenge to the database.
:returns: A message to the user. This should be a string that fits
comfortably in the template 'OTP Challenge: {0}'. This may
return None if this device is not interactive.
:rtype: string or None
:raises: Any :exc:~exceptions.Exception is permitted. Callers should
trap Exception and report it to the user.
186 def verify_is_allowed(self): 187 """ 188 Checks whether it is permissible to call :meth:`verify_token`. If it is 189 allowed, returns ``(True, None)``. Otherwise returns ``(False, 190 data_dict)``, where ``data_dict`` contains extra information, defined 191 by the implementation. 192 193 This method can be used to implement throttling or locking, for 194 example. Client code should check this method before calling 195 :meth:`verify_token` and report problems to the user. 196 197 To report specific problems, the data dictionary can return include a 198 ``'reason'`` member with a value from the constants in 199 :class:`VerifyNotAllowed`. Otherwise, an ``'error_message'`` member 200 should be provided with an error message. 201 202 :meth:`verify_token` should also call this method and return False if 203 verification is not allowed. 204 205 :rtype: (bool, dict or ``None``) 206 207 """ 208 return (True, None)
Checks whether it is permissible to call :meth:verify_token. If it is
allowed, returns (True, None). Otherwise returns (False,
data_dict), where data_dict contains extra information, defined
by the implementation.
This method can be used to implement throttling or locking, for
example. Client code should check this method before calling
:meth:verify_token and report problems to the user.
To report specific problems, the data dictionary can return include a
'reason' member with a value from the constants in
:class:VerifyNotAllowed. Otherwise, an 'error_message' member
should be provided with an error message.
:meth:verify_token should also call this method and return False if
verification is not allowed.
:rtype: (bool, dict or None)
210 def verify_token(self, token): 211 """ 212 Verifies a token. As a rule, the token should no longer be valid if 213 this returns ``True``. 214 215 :param str token: The OTP token provided by the user. 216 :rtype: bool 217 """ 218 return False
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.
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.
221class SideChannelDevice(Device): 222 """ 223 Abstract base model for a side-channel :term:`device` attached to a user. 224 225 This model implements token generation, verification and expiration, so the 226 concrete devices only have to implement delivery. 227 228 """ 229 230 token = models.CharField(max_length=16, blank=True, null=True) 231 232 valid_until = models.DateTimeField( 233 default=timezone.now, 234 help_text="The timestamp of the moment of expiry of the saved token.", 235 ) 236 237 class Meta: 238 abstract = True 239 240 def generate_token(self, length=6, valid_secs=300, commit=True): 241 """ 242 Generates a token of the specified length, then sets it on the model 243 and sets the expiration of the token on the model. 244 245 Pass 'commit=False' to avoid calling self.save(). 246 247 :param int length: Number of decimal digits in the generated token. 248 :param int valid_secs: Amount of seconds the token should be valid. 249 :param bool commit: Whether to autosave the generated token. 250 251 """ 252 self.token = random_number_token(length) 253 self.valid_until = timezone.now() + timedelta(seconds=valid_secs) 254 if commit: 255 self.save() 256 257 def verify_token(self, token): 258 """ 259 Verifies a token by content and expiry. 260 261 On success, the token is cleared and the device saved. 262 263 :param str token: The OTP token provided by the user. 264 :rtype: bool 265 266 """ 267 _now = timezone.now() 268 269 if (self.token is not None) and (token == self.token) and (_now < self.valid_until): 270 self.token = None 271 self.valid_until = _now 272 self.save() 273 274 return True 275 return False
Abstract base model for a side-channel :term:device attached to a user.
This model implements token generation, verification and expiration, so the concrete devices only have to implement delivery.
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.
240 def generate_token(self, length=6, valid_secs=300, commit=True): 241 """ 242 Generates a token of the specified length, then sets it on the model 243 and sets the expiration of the token on the model. 244 245 Pass 'commit=False' to avoid calling self.save(). 246 247 :param int length: Number of decimal digits in the generated token. 248 :param int valid_secs: Amount of seconds the token should be valid. 249 :param bool commit: Whether to autosave the generated token. 250 251 """ 252 self.token = random_number_token(length) 253 self.valid_until = timezone.now() + timedelta(seconds=valid_secs) 254 if commit: 255 self.save()
Generates a token of the specified length, then sets it on the model and sets the expiration of the token on the model.
Pass 'commit=False' to avoid calling self.save().
:param int length: Number of decimal digits in the generated token. :param int valid_secs: Amount of seconds the token should be valid. :param bool commit: Whether to autosave the generated token.
257 def verify_token(self, token): 258 """ 259 Verifies a token by content and expiry. 260 261 On success, the token is cleared and the device saved. 262 263 :param str token: The OTP token provided by the user. 264 :rtype: bool 265 266 """ 267 _now = timezone.now() 268 269 if (self.token is not None) and (token == self.token) and (_now < self.valid_until): 270 self.token = None 271 self.valid_until = _now 272 self.save() 273 274 return True 275 return False
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
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.
Method descriptor with partial application of the given arguments and keywords.
Supports wrapping existing descriptors and handles non-descriptor callables as instance methods.
278class VerifyNotAllowed: 279 """ 280 Constants that may be returned in the ``reason`` member of the extra 281 information dictionary returned by 282 :meth:`~authentik.stages.authenticator.models.Device.verify_is_allowed` 283 284 .. data:: N_FAILED_ATTEMPTS 285 286 Indicates that verification is disallowed because of ``n`` successive 287 failed attempts. The data dictionary should include the value of ``n`` 288 in member ``failure_count`` 289 290 """ 291 292 N_FAILED_ATTEMPTS = "N_FAILED_ATTEMPTS"
Constants that may be returned in the reason member of the extra
information dictionary returned by
:meth:~authentik.stages.authenticator.models.Device.verify_is_allowed
.. data:: N_FAILED_ATTEMPTS
Indicates that verification is disallowed because of n successive
failed attempts. The data dictionary should include the value of n
in member failure_count
295class ThrottlingMixin(models.Model): 296 """ 297 Mixin class for models that want throttling behavior. 298 299 This implements exponential back-off for verifying tokens. Subclasses must 300 implement :meth:`get_throttle_factor`, and must use the 301 :meth:`verify_is_allowed`, :meth:`throttle_reset` and 302 :meth:`throttle_increment` methods from within their verify_token() method. 303 304 See the implementation of 305 :class:`~authentik.stages.authenticator.plugins.otp_email.models.EmailDevice` for an example. 306 307 """ 308 309 throttling_failure_timestamp = models.DateTimeField( 310 null=True, 311 blank=True, 312 default=None, 313 help_text=( 314 "A timestamp of the last failed verification attempt. " 315 "Null if last attempt succeeded." 316 ), 317 ) 318 319 throttling_failure_count = models.PositiveIntegerField( 320 default=0, help_text="Number of successive failed attempts." 321 ) 322 323 class Meta: 324 abstract = True 325 326 def verify_is_allowed(self): 327 """ 328 If verification is allowed, returns ``(True, None)``. 329 Otherwise, returns ``(False, data_dict)``. 330 331 ``data_dict`` contains further information. Currently it can be:: 332 333 { 334 'reason': VerifyNotAllowed.N_FAILED_ATTEMPTS, 335 'failure_count': n 336 } 337 338 where ``n`` is the number of successive failures. See 339 :class:`~authentik.stages.authenticator.models.VerifyNotAllowed`. 340 341 """ 342 if ( 343 self.throttling_enabled 344 and self.throttling_failure_count > 0 345 and self.throttling_failure_timestamp is not None 346 ): 347 now = timezone.now() 348 delay = (now - self.throttling_failure_timestamp).total_seconds() 349 # Required delays should be 1, 2, 4, 8 ... 350 delay_required = self.get_throttle_factor() * (2 ** (self.throttling_failure_count - 1)) 351 if delay < delay_required: 352 return ( 353 False, 354 { 355 "reason": VerifyNotAllowed.N_FAILED_ATTEMPTS, 356 "failure_count": self.throttling_failure_count, 357 "locked_until": self.throttling_failure_timestamp 358 + timedelta(seconds=delay_required), 359 }, 360 ) 361 362 return super().verify_is_allowed() 363 364 def throttle_reset(self, commit=True): 365 """ 366 Call this method to reset throttling (normally when a verify attempt 367 succeeded). 368 369 Pass 'commit=False' to avoid calling self.save(). 370 371 """ 372 self.throttling_failure_timestamp = None 373 self.throttling_failure_count = 0 374 if commit: 375 self.save() 376 377 def throttle_increment(self, commit=True): 378 """ 379 Call this method to increase throttling (normally when a verify attempt 380 failed). 381 382 Pass 'commit=False' to avoid calling self.save(). 383 384 """ 385 self.throttling_failure_timestamp = timezone.now() 386 self.throttling_failure_count += 1 387 if commit: 388 self.save() 389 390 @cached_property 391 def throttling_enabled(self) -> bool: 392 """Check if throttling is enabled""" 393 return self.get_throttle_factor() > 0 394 395 def get_throttle_factor(self) -> float: # pragma: no cover 396 """ 397 Returns the throttling factor. 398 """ 399 return getattr(self, "_throttle_factor", 1.0) 400 401 def set_throttle_factor(self, throttle_factor: float) -> None: 402 """ 403 Sets the throttle factor to use. Call this to override the default value of 1. 404 405 The number of seconds required between verification attempts will be 406 :math:`c2^{n-1}` where `c` is this factor and `n` is the number of 407 previous failures. A factor of 1 translates to delays of 1, 2, 4, 8, 408 etc. seconds. A factor of 0 disables the throttling. 409 """ 410 self._throttle_factor = throttle_factor
Mixin class for models that want throttling behavior.
This implements exponential back-off for verifying tokens. Subclasses must
implement :meth:get_throttle_factor, and must use the
:meth:verify_is_allowed, :meth:throttle_reset and
:meth:throttle_increment methods from within their verify_token() method.
See the implementation of
:class:~authentik.stages.authenticator.plugins.otp_email.models.EmailDevice for an example.
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.
326 def verify_is_allowed(self): 327 """ 328 If verification is allowed, returns ``(True, None)``. 329 Otherwise, returns ``(False, data_dict)``. 330 331 ``data_dict`` contains further information. Currently it can be:: 332 333 { 334 'reason': VerifyNotAllowed.N_FAILED_ATTEMPTS, 335 'failure_count': n 336 } 337 338 where ``n`` is the number of successive failures. See 339 :class:`~authentik.stages.authenticator.models.VerifyNotAllowed`. 340 341 """ 342 if ( 343 self.throttling_enabled 344 and self.throttling_failure_count > 0 345 and self.throttling_failure_timestamp is not None 346 ): 347 now = timezone.now() 348 delay = (now - self.throttling_failure_timestamp).total_seconds() 349 # Required delays should be 1, 2, 4, 8 ... 350 delay_required = self.get_throttle_factor() * (2 ** (self.throttling_failure_count - 1)) 351 if delay < delay_required: 352 return ( 353 False, 354 { 355 "reason": VerifyNotAllowed.N_FAILED_ATTEMPTS, 356 "failure_count": self.throttling_failure_count, 357 "locked_until": self.throttling_failure_timestamp 358 + timedelta(seconds=delay_required), 359 }, 360 ) 361 362 return super().verify_is_allowed()
If verification is allowed, returns (True, None).
Otherwise, returns (False, data_dict).
data_dict contains further information. Currently it can be::
{
'reason': VerifyNotAllowed.N_FAILED_ATTEMPTS,
'failure_count': n
}
where n is the number of successive failures. See
:class:~authentik.stages.authenticator.models.VerifyNotAllowed.
364 def throttle_reset(self, commit=True): 365 """ 366 Call this method to reset throttling (normally when a verify attempt 367 succeeded). 368 369 Pass 'commit=False' to avoid calling self.save(). 370 371 """ 372 self.throttling_failure_timestamp = None 373 self.throttling_failure_count = 0 374 if commit: 375 self.save()
Call this method to reset throttling (normally when a verify attempt succeeded).
Pass 'commit=False' to avoid calling self.save().
377 def throttle_increment(self, commit=True): 378 """ 379 Call this method to increase throttling (normally when a verify attempt 380 failed). 381 382 Pass 'commit=False' to avoid calling self.save(). 383 384 """ 385 self.throttling_failure_timestamp = timezone.now() 386 self.throttling_failure_count += 1 387 if commit: 388 self.save()
Call this method to increase throttling (normally when a verify attempt failed).
Pass 'commit=False' to avoid calling self.save().
395 def get_throttle_factor(self) -> float: # pragma: no cover 396 """ 397 Returns the throttling factor. 398 """ 399 return getattr(self, "_throttle_factor", 1.0)
Returns the throttling factor.
401 def set_throttle_factor(self, throttle_factor: float) -> None: 402 """ 403 Sets the throttle factor to use. Call this to override the default value of 1. 404 405 The number of seconds required between verification attempts will be 406 :math:`c2^{n-1}` where `c` is this factor and `n` is the number of 407 previous failures. A factor of 1 translates to delays of 1, 2, 4, 8, 408 etc. seconds. A factor of 0 disables the throttling. 409 """ 410 self._throttle_factor = throttle_factor
Sets the throttle factor to use. Call this to override the default value of 1.
The number of seconds required between verification attempts will be
:math:c2^{n-1} where c is this factor and n is the number of
previous failures. A factor of 1 translates to delays of 1, 2, 4, 8,
etc. seconds. A factor of 0 disables the throttling.