authentik.stages.password.models

password stage models

  1"""password stage models"""
  2
  3from datetime import datetime
  4from typing import Any
  5
  6from django.contrib.auth.hashers import check_password, make_password
  7from django.contrib.postgres.fields import ArrayField
  8from django.db import models, transaction
  9from django.http import HttpRequest
 10from django.utils.timezone import now
 11from django.utils.translation import gettext_lazy as _
 12from django.views import View
 13from rest_framework.serializers import BaseSerializer
 14
 15from authentik.core.models import User
 16from authentik.core.signals import password_changed, password_hash_changed
 17from authentik.core.types import UserSettingSerializer
 18from authentik.flows.models import ConfigurableStage, Stage
 19from authentik.stages.authenticator.models import Device
 20from authentik.stages.password import (
 21    BACKEND_APP_PASSWORD,
 22    BACKEND_INBUILT,
 23    BACKEND_KERBEROS,
 24    BACKEND_LDAP,
 25)
 26
 27
 28def get_authentication_backends():
 29    """Return all available authentication backends as tuple set"""
 30    return [
 31        (
 32            BACKEND_INBUILT,
 33            _("User database + standard password"),
 34        ),
 35        (
 36            BACKEND_APP_PASSWORD,
 37            _("User database + app passwords"),
 38        ),
 39        (
 40            BACKEND_LDAP,
 41            _("User database + LDAP password"),
 42        ),
 43        (
 44            BACKEND_KERBEROS,
 45            _("User database + Kerberos password"),
 46        ),
 47    ]
 48
 49
 50class PasswordStage(ConfigurableStage, Stage):
 51    """Prompt the user for their password, and validate it against the configured backends."""
 52
 53    backends = ArrayField(
 54        models.TextField(choices=get_authentication_backends()),
 55        help_text=_("Selection of backends to test the password against."),
 56    )
 57    failed_attempts_before_cancel = models.IntegerField(
 58        default=5,
 59        help_text=_(
 60            "How many attempts a user has before the flow is canceled. "
 61            "This only cancels the flow, it does not lock the user's password."
 62        ),
 63    )
 64    failed_attempts_before_lockout = models.PositiveIntegerField(
 65        default=0,
 66        help_text=_(
 67            "How many consecutive failed attempts lock the user's password until an "
 68            "administrator unlocks it. Set to 0 to never lock."
 69        ),
 70    )
 71    last_attempt_warning_message = models.TextField(
 72        blank=True,
 73        default="",
 74        help_text=_(
 75            "Warning shown when the user has one password attempt remaining. "
 76            "Leave blank to show no warning."
 77        ),
 78    )
 79    lockout_message = models.TextField(
 80        blank=True,
 81        default="",
 82        help_text=_(
 83            "Message shown when the user's password has been locked. "
 84            "Leave blank to show a generic authentication error."
 85        ),
 86    )
 87    allow_show_password = models.BooleanField(
 88        default=False,
 89        help_text=_(
 90            "When enabled, provides a 'show password' button with the password input field."
 91        ),
 92    )
 93
 94    @property
 95    def serializer(self) -> type[BaseSerializer]:
 96        from authentik.stages.password.api import PasswordStageSerializer
 97
 98        return PasswordStageSerializer
 99
100    @property
101    def view(self) -> type[View]:
102        from authentik.stages.password.stage import PasswordStageView
103
104        return PasswordStageView
105
106    @property
107    def component(self) -> str:
108        return "ak-stage-password-form"
109
110    def ui_user_settings(self) -> UserSettingSerializer | None:
111        if not self.configure_flow:
112            return None
113        return UserSettingSerializer(
114            data={
115                "title": str(self._meta.verbose_name),
116                "component": "ak-user-settings-password",
117            }
118        )
119
120    class Meta:
121        verbose_name = _("Password Stage")
122        verbose_name_plural = _("Password Stages")
123
124
125class PasswordDevice(Device):
126    """A user's password, excluded from MFA discovery and validation."""
127
128    user = models.OneToOneField(User, on_delete=models.CASCADE, related_name="password_device")
129    password = models.CharField(max_length=128)
130    password_change_date = models.DateTimeField(default=now)
131    failed_attempts = models.PositiveIntegerField(default=0)
132    locked_at = models.DateTimeField(default=None, null=True)
133
134    @classmethod
135    def set_password(
136        cls,
137        user: User,
138        raw_password: str | None,
139        *,
140        signal: bool = True,
141        sender: Any = None,
142        request: HttpRequest | None = None,
143    ):
144        """Hash and store a password. `None` revokes the password."""
145        if signal:
146            password_changed.send(
147                sender=sender or user, user=user, password=raw_password, request=request
148            )
149        cls._store(user, make_password(raw_password))
150
151    @classmethod
152    def set_password_from_hash(
153        cls,
154        user: User,
155        password_hash: str,
156        *,
157        signal: bool = True,
158        sender: Any = None,
159        request: HttpRequest | None = None,
160        hasher_defaults_overridden: bool = False,
161    ):
162        """Store an already validated password hash as-is.
163
164        Because no raw password is available, downstream password sync integrations
165        such as LDAP and Kerberos cannot be updated from this code path."""
166        if signal:
167            password_hash_changed.send(
168                sender=sender or user,
169                user=user,
170                request=request,
171                hasher_defaults_overridden=hasher_defaults_overridden,
172            )
173        cls._store(user, password_hash)
174
175    @classmethod
176    def set_unusable_password(cls, user: User, *, password_change_date: datetime | None = None):
177        """Refuse password authentication until a new password is set.
178
179        The change date stays unless `password_change_date` gives the time the password
180        changed elsewhere, such as in a source directory.
181        A user without a password device already has no usable password."""
182        with transaction.atomic():
183            device = cls.objects.select_for_update().filter(user=user).first()
184            if device is None:
185                return
186            device.password = make_password(None)
187            update_fields = ["password", "last_updated"]
188            if password_change_date is not None:
189                device.password_change_date = password_change_date
190                update_fields.append("password_change_date")
191            device.save(update_fields=update_fields)
192            user.password_device = device
193            # Saving the user dispatches outgoing sync and invalidates cached policy results.
194            user.save(update_fields=["last_updated"])
195
196    @classmethod
197    def _store(cls, user: User, password_hash: str):
198        """Replace the password, keeping any lock on the device."""
199        defaults = {"password": password_hash, "password_change_date": now(), "failed_attempts": 0}
200        with transaction.atomic():
201            device, _ = cls.objects.update_or_create(
202                user=user, defaults=defaults, create_defaults={"name": "Password", **defaults}
203            )
204            user.password_device = device
205            # Saving the user dispatches outgoing sync and invalidates cached policy results.
206            user.save(update_fields=["last_updated"])
207
208    def check_password(self, raw_password: str) -> bool:
209        """Upgrade outdated hashes without replacing a concurrently changed password."""
210
211        def setter(raw_password):
212            password = make_password(raw_password)
213            if (
214                type(self)
215                .objects.filter(pk=self.pk, password=self.password)
216                .update(password=password)
217            ):
218                self.password = password
219
220        return check_password(raw_password, self.password, setter)
221
222    def __str__(self):
223        return str(self.name) or str(self.user_id)
224
225    class Meta(Device.Meta):
226        verbose_name = _("Password Device")
227        verbose_name_plural = _("Password Devices")
228        indexes = [models.Index(fields=["password_change_date"])]
229
230    @property
231    def locked(self) -> bool:
232        """Whether this password currently refuses authentication."""
233        return self.locked_at is not None
def get_authentication_backends():
29def get_authentication_backends():
30    """Return all available authentication backends as tuple set"""
31    return [
32        (
33            BACKEND_INBUILT,
34            _("User database + standard password"),
35        ),
36        (
37            BACKEND_APP_PASSWORD,
38            _("User database + app passwords"),
39        ),
40        (
41            BACKEND_LDAP,
42            _("User database + LDAP password"),
43        ),
44        (
45            BACKEND_KERBEROS,
46            _("User database + Kerberos password"),
47        ),
48    ]

Return all available authentication backends as tuple set

 51class PasswordStage(ConfigurableStage, Stage):
 52    """Prompt the user for their password, and validate it against the configured backends."""
 53
 54    backends = ArrayField(
 55        models.TextField(choices=get_authentication_backends()),
 56        help_text=_("Selection of backends to test the password against."),
 57    )
 58    failed_attempts_before_cancel = models.IntegerField(
 59        default=5,
 60        help_text=_(
 61            "How many attempts a user has before the flow is canceled. "
 62            "This only cancels the flow, it does not lock the user's password."
 63        ),
 64    )
 65    failed_attempts_before_lockout = models.PositiveIntegerField(
 66        default=0,
 67        help_text=_(
 68            "How many consecutive failed attempts lock the user's password until an "
 69            "administrator unlocks it. Set to 0 to never lock."
 70        ),
 71    )
 72    last_attempt_warning_message = models.TextField(
 73        blank=True,
 74        default="",
 75        help_text=_(
 76            "Warning shown when the user has one password attempt remaining. "
 77            "Leave blank to show no warning."
 78        ),
 79    )
 80    lockout_message = models.TextField(
 81        blank=True,
 82        default="",
 83        help_text=_(
 84            "Message shown when the user's password has been locked. "
 85            "Leave blank to show a generic authentication error."
 86        ),
 87    )
 88    allow_show_password = models.BooleanField(
 89        default=False,
 90        help_text=_(
 91            "When enabled, provides a 'show password' button with the password input field."
 92        ),
 93    )
 94
 95    @property
 96    def serializer(self) -> type[BaseSerializer]:
 97        from authentik.stages.password.api import PasswordStageSerializer
 98
 99        return PasswordStageSerializer
100
101    @property
102    def view(self) -> type[View]:
103        from authentik.stages.password.stage import PasswordStageView
104
105        return PasswordStageView
106
107    @property
108    def component(self) -> str:
109        return "ak-stage-password-form"
110
111    def ui_user_settings(self) -> UserSettingSerializer | None:
112        if not self.configure_flow:
113            return None
114        return UserSettingSerializer(
115            data={
116                "title": str(self._meta.verbose_name),
117                "component": "ak-user-settings-password",
118            }
119        )
120
121    class Meta:
122        verbose_name = _("Password Stage")
123        verbose_name_plural = _("Password Stages")

Prompt the user for their password, and validate it against the configured backends.

def backends(unknown):

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

def failed_attempts_before_cancel(unknown):

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

def failed_attempts_before_lockout(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_attempt_warning_message(unknown):

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

def lockout_message(unknown):

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

def allow_show_password(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]
95    @property
96    def serializer(self) -> type[BaseSerializer]:
97        from authentik.stages.password.api import PasswordStageSerializer
98
99        return PasswordStageSerializer

Get serializer for this model

view: type[django.views.generic.base.View]
101    @property
102    def view(self) -> type[View]:
103        from authentik.stages.password.stage import PasswordStageView
104
105        return PasswordStageView

Return StageView class that implements logic for this stage

component: str
107    @property
108    def component(self) -> str:
109        return "ak-stage-password-form"

Return component used to edit this object

def ui_user_settings(self) -> authentik.core.types.UserSettingSerializer | None:
111    def ui_user_settings(self) -> UserSettingSerializer | None:
112        if not self.configure_flow:
113            return None
114        return UserSettingSerializer(
115            data={
116                "title": str(self._meta.verbose_name),
117                "component": "ak-user-settings-password",
118            }
119        )

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.

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.

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 PasswordStage.DoesNotExist(authentik.flows.models.Stage.DoesNotExist):

The requested object does not exist

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

The query returned multiple objects when only one was expected.

class PasswordDevice(authentik.stages.authenticator.models.Device):
126class PasswordDevice(Device):
127    """A user's password, excluded from MFA discovery and validation."""
128
129    user = models.OneToOneField(User, on_delete=models.CASCADE, related_name="password_device")
130    password = models.CharField(max_length=128)
131    password_change_date = models.DateTimeField(default=now)
132    failed_attempts = models.PositiveIntegerField(default=0)
133    locked_at = models.DateTimeField(default=None, null=True)
134
135    @classmethod
136    def set_password(
137        cls,
138        user: User,
139        raw_password: str | None,
140        *,
141        signal: bool = True,
142        sender: Any = None,
143        request: HttpRequest | None = None,
144    ):
145        """Hash and store a password. `None` revokes the password."""
146        if signal:
147            password_changed.send(
148                sender=sender or user, user=user, password=raw_password, request=request
149            )
150        cls._store(user, make_password(raw_password))
151
152    @classmethod
153    def set_password_from_hash(
154        cls,
155        user: User,
156        password_hash: str,
157        *,
158        signal: bool = True,
159        sender: Any = None,
160        request: HttpRequest | None = None,
161        hasher_defaults_overridden: bool = False,
162    ):
163        """Store an already validated password hash as-is.
164
165        Because no raw password is available, downstream password sync integrations
166        such as LDAP and Kerberos cannot be updated from this code path."""
167        if signal:
168            password_hash_changed.send(
169                sender=sender or user,
170                user=user,
171                request=request,
172                hasher_defaults_overridden=hasher_defaults_overridden,
173            )
174        cls._store(user, password_hash)
175
176    @classmethod
177    def set_unusable_password(cls, user: User, *, password_change_date: datetime | None = None):
178        """Refuse password authentication until a new password is set.
179
180        The change date stays unless `password_change_date` gives the time the password
181        changed elsewhere, such as in a source directory.
182        A user without a password device already has no usable password."""
183        with transaction.atomic():
184            device = cls.objects.select_for_update().filter(user=user).first()
185            if device is None:
186                return
187            device.password = make_password(None)
188            update_fields = ["password", "last_updated"]
189            if password_change_date is not None:
190                device.password_change_date = password_change_date
191                update_fields.append("password_change_date")
192            device.save(update_fields=update_fields)
193            user.password_device = device
194            # Saving the user dispatches outgoing sync and invalidates cached policy results.
195            user.save(update_fields=["last_updated"])
196
197    @classmethod
198    def _store(cls, user: User, password_hash: str):
199        """Replace the password, keeping any lock on the device."""
200        defaults = {"password": password_hash, "password_change_date": now(), "failed_attempts": 0}
201        with transaction.atomic():
202            device, _ = cls.objects.update_or_create(
203                user=user, defaults=defaults, create_defaults={"name": "Password", **defaults}
204            )
205            user.password_device = device
206            # Saving the user dispatches outgoing sync and invalidates cached policy results.
207            user.save(update_fields=["last_updated"])
208
209    def check_password(self, raw_password: str) -> bool:
210        """Upgrade outdated hashes without replacing a concurrently changed password."""
211
212        def setter(raw_password):
213            password = make_password(raw_password)
214            if (
215                type(self)
216                .objects.filter(pk=self.pk, password=self.password)
217                .update(password=password)
218            ):
219                self.password = password
220
221        return check_password(raw_password, self.password, setter)
222
223    def __str__(self):
224        return str(self.name) or str(self.user_id)
225
226    class Meta(Device.Meta):
227        verbose_name = _("Password Device")
228        verbose_name_plural = _("Password Devices")
229        indexes = [models.Index(fields=["password_change_date"])]
230
231    @property
232    def locked(self) -> bool:
233        """Whether this password currently refuses authentication."""
234        return self.locked_at is not None

A user's password, excluded from MFA discovery and validation.

user

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.

def password(unknown):

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

def password_change_date(unknown):

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

def failed_attempts(unknown):

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

def locked_at(unknown):

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

@classmethod
def set_password( cls, user: authentik.core.models.User, raw_password: str | None, *, signal: bool = True, sender: Any = None, request: django.http.request.HttpRequest | None = None):
135    @classmethod
136    def set_password(
137        cls,
138        user: User,
139        raw_password: str | None,
140        *,
141        signal: bool = True,
142        sender: Any = None,
143        request: HttpRequest | None = None,
144    ):
145        """Hash and store a password. `None` revokes the password."""
146        if signal:
147            password_changed.send(
148                sender=sender or user, user=user, password=raw_password, request=request
149            )
150        cls._store(user, make_password(raw_password))

Hash and store a password. None revokes the password.

@classmethod
def set_password_from_hash( cls, user: authentik.core.models.User, password_hash: str, *, signal: bool = True, sender: Any = None, request: django.http.request.HttpRequest | None = None, hasher_defaults_overridden: bool = False):
152    @classmethod
153    def set_password_from_hash(
154        cls,
155        user: User,
156        password_hash: str,
157        *,
158        signal: bool = True,
159        sender: Any = None,
160        request: HttpRequest | None = None,
161        hasher_defaults_overridden: bool = False,
162    ):
163        """Store an already validated password hash as-is.
164
165        Because no raw password is available, downstream password sync integrations
166        such as LDAP and Kerberos cannot be updated from this code path."""
167        if signal:
168            password_hash_changed.send(
169                sender=sender or user,
170                user=user,
171                request=request,
172                hasher_defaults_overridden=hasher_defaults_overridden,
173            )
174        cls._store(user, password_hash)

Store an already validated password hash as-is.

Because no raw password is available, downstream password sync integrations such as LDAP and Kerberos cannot be updated from this code path.

@classmethod
def set_unusable_password( cls, user: authentik.core.models.User, *, password_change_date: datetime.datetime | None = None):
176    @classmethod
177    def set_unusable_password(cls, user: User, *, password_change_date: datetime | None = None):
178        """Refuse password authentication until a new password is set.
179
180        The change date stays unless `password_change_date` gives the time the password
181        changed elsewhere, such as in a source directory.
182        A user without a password device already has no usable password."""
183        with transaction.atomic():
184            device = cls.objects.select_for_update().filter(user=user).first()
185            if device is None:
186                return
187            device.password = make_password(None)
188            update_fields = ["password", "last_updated"]
189            if password_change_date is not None:
190                device.password_change_date = password_change_date
191                update_fields.append("password_change_date")
192            device.save(update_fields=update_fields)
193            user.password_device = device
194            # Saving the user dispatches outgoing sync and invalidates cached policy results.
195            user.save(update_fields=["last_updated"])

Refuse password authentication until a new password is set.

The change date stays unless password_change_date gives the time the password changed elsewhere, such as in a source directory. A user without a password device already has no usable password.

def check_password(self, raw_password: str) -> bool:
209    def check_password(self, raw_password: str) -> bool:
210        """Upgrade outdated hashes without replacing a concurrently changed password."""
211
212        def setter(raw_password):
213            password = make_password(raw_password)
214            if (
215                type(self)
216                .objects.filter(pk=self.pk, password=self.password)
217                .update(password=password)
218            ):
219                self.password = password
220
221        return check_password(raw_password, self.password, setter)

Upgrade outdated hashes without replacing a concurrently changed password.

locked: bool
231    @property
232    def locked(self) -> bool:
233        """Whether this password currently refuses authentication."""
234        return self.locked_at is not None

Whether this password currently refuses authentication.

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.

user_id
def get_next_by_password_change_date(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_password_change_date(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_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.

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.

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

The requested object does not exist

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

The query returned multiple objects when only one was expected.