authentik.stages.password.lockout

Password-lock enforcement shared by standalone and embedded password stages.

 1"""Password-lock enforcement shared by standalone and embedded password stages."""
 2
 3from dataclasses import dataclass
 4from typing import Any
 5
 6from django.db import transaction
 7from django.http import HttpRequest
 8
 9from authentik.core.models import SERVICE_ACCOUNT_TYPES, User
10from authentik.core.signals import login_failed
11from authentik.lib.utils.reflection import ConditionalInheritance
12from authentik.stages.password.models import PasswordDevice, PasswordStage
13
14PLAN_CONTEXT_LOCKED_ATTEMPTS = "goauthentik.io/stages/password/locked_attempts"
15
16
17@dataclass(frozen=True)
18class PasswordLockoutResult:
19    """Authentication result and optional messages for the current flow."""
20
21    user: User | None = None
22    last_attempt: bool = False
23    lockout_reached: bool = False
24
25
26class PasswordLockoutBase:
27    """Enforce existing locks even without Enterprise or a valid license."""
28
29    def __init__(self, password_stage: PasswordStage, request: HttpRequest):
30        self.password_stage = password_stage
31        self.request = request
32
33    def apply(
34        self, pending_user: User, user: User | None, context: dict[str, Any]
35    ) -> PasswordLockoutResult:
36        if pending_user.pk is None or pending_user.type in SERVICE_ACCOUNT_TYPES:
37            return PasswordLockoutResult(user)
38        with transaction.atomic():
39            device = PasswordDevice.objects.select_for_update().filter(user=pending_user).first()
40            if device is None:
41                return PasswordLockoutResult(user)
42            if device.locked:
43                # A lock may have been set while a backend was authenticating.
44                if user is not None:
45                    login_failed.send(
46                        sender=__name__,
47                        credentials={"username": pending_user.username},
48                        request=self.request,
49                        stage=self.password_stage,
50                    )
51                return PasswordLockoutResult(lockout_reached=self._count_locked(context))
52            if user is not None:
53                if device.failed_attempts:
54                    PasswordDevice.objects.filter(pk=device.pk).update(failed_attempts=0)
55                return PasswordLockoutResult(user)
56            return self.record_failure(device)
57
58    def record_failure(self, device: PasswordDevice) -> PasswordLockoutResult:
59        """Without Enterprise, authentication does not create new locks."""
60        return PasswordLockoutResult()
61
62    def _count_locked(self, context: dict[str, Any]) -> bool:
63        """Show the lockout message only after this flow reaches its attempt limit."""
64        key = f"{PLAN_CONTEXT_LOCKED_ATTEMPTS}/{self.password_stage.pk}"
65        attempts = context.get(key, 0) + 1
66        context[key] = attempts
67        threshold = (
68            self.password_stage.failed_attempts_before_lockout
69            or self.password_stage.failed_attempts_before_cancel
70        )
71        return threshold > 0 and attempts >= threshold
72
73
74class PasswordLockout(
75    ConditionalInheritance("authentik.enterprise.stages.password.lockout.PasswordLockoutMixin"),
76    PasswordLockoutBase,
77):
78    """Enforce password locks, with optional licensed failure counting."""
PLAN_CONTEXT_LOCKED_ATTEMPTS = 'goauthentik.io/stages/password/locked_attempts'
@dataclass(frozen=True)
class PasswordLockoutResult:
18@dataclass(frozen=True)
19class PasswordLockoutResult:
20    """Authentication result and optional messages for the current flow."""
21
22    user: User | None = None
23    last_attempt: bool = False
24    lockout_reached: bool = False

Authentication result and optional messages for the current flow.

PasswordLockoutResult( user: authentik.core.models.User | None = None, last_attempt: bool = False, lockout_reached: bool = False)
user: authentik.core.models.User | None = None
last_attempt: bool = False
lockout_reached: bool = False
class PasswordLockoutBase:
27class PasswordLockoutBase:
28    """Enforce existing locks even without Enterprise or a valid license."""
29
30    def __init__(self, password_stage: PasswordStage, request: HttpRequest):
31        self.password_stage = password_stage
32        self.request = request
33
34    def apply(
35        self, pending_user: User, user: User | None, context: dict[str, Any]
36    ) -> PasswordLockoutResult:
37        if pending_user.pk is None or pending_user.type in SERVICE_ACCOUNT_TYPES:
38            return PasswordLockoutResult(user)
39        with transaction.atomic():
40            device = PasswordDevice.objects.select_for_update().filter(user=pending_user).first()
41            if device is None:
42                return PasswordLockoutResult(user)
43            if device.locked:
44                # A lock may have been set while a backend was authenticating.
45                if user is not None:
46                    login_failed.send(
47                        sender=__name__,
48                        credentials={"username": pending_user.username},
49                        request=self.request,
50                        stage=self.password_stage,
51                    )
52                return PasswordLockoutResult(lockout_reached=self._count_locked(context))
53            if user is not None:
54                if device.failed_attempts:
55                    PasswordDevice.objects.filter(pk=device.pk).update(failed_attempts=0)
56                return PasswordLockoutResult(user)
57            return self.record_failure(device)
58
59    def record_failure(self, device: PasswordDevice) -> PasswordLockoutResult:
60        """Without Enterprise, authentication does not create new locks."""
61        return PasswordLockoutResult()
62
63    def _count_locked(self, context: dict[str, Any]) -> bool:
64        """Show the lockout message only after this flow reaches its attempt limit."""
65        key = f"{PLAN_CONTEXT_LOCKED_ATTEMPTS}/{self.password_stage.pk}"
66        attempts = context.get(key, 0) + 1
67        context[key] = attempts
68        threshold = (
69            self.password_stage.failed_attempts_before_lockout
70            or self.password_stage.failed_attempts_before_cancel
71        )
72        return threshold > 0 and attempts >= threshold

Enforce existing locks even without Enterprise or a valid license.

PasswordLockoutBase( password_stage: authentik.stages.password.models.PasswordStage, request: django.http.request.HttpRequest)
30    def __init__(self, password_stage: PasswordStage, request: HttpRequest):
31        self.password_stage = password_stage
32        self.request = request
password_stage
request
def apply( self, pending_user: authentik.core.models.User, user: authentik.core.models.User | None, context: dict[str, typing.Any]) -> PasswordLockoutResult:
34    def apply(
35        self, pending_user: User, user: User | None, context: dict[str, Any]
36    ) -> PasswordLockoutResult:
37        if pending_user.pk is None or pending_user.type in SERVICE_ACCOUNT_TYPES:
38            return PasswordLockoutResult(user)
39        with transaction.atomic():
40            device = PasswordDevice.objects.select_for_update().filter(user=pending_user).first()
41            if device is None:
42                return PasswordLockoutResult(user)
43            if device.locked:
44                # A lock may have been set while a backend was authenticating.
45                if user is not None:
46                    login_failed.send(
47                        sender=__name__,
48                        credentials={"username": pending_user.username},
49                        request=self.request,
50                        stage=self.password_stage,
51                    )
52                return PasswordLockoutResult(lockout_reached=self._count_locked(context))
53            if user is not None:
54                if device.failed_attempts:
55                    PasswordDevice.objects.filter(pk=device.pk).update(failed_attempts=0)
56                return PasswordLockoutResult(user)
57            return self.record_failure(device)
def record_failure( self, device: authentik.stages.password.models.PasswordDevice) -> PasswordLockoutResult:
59    def record_failure(self, device: PasswordDevice) -> PasswordLockoutResult:
60        """Without Enterprise, authentication does not create new locks."""
61        return PasswordLockoutResult()

Without Enterprise, authentication does not create new locks.

75class PasswordLockout(
76    ConditionalInheritance("authentik.enterprise.stages.password.lockout.PasswordLockoutMixin"),
77    PasswordLockoutBase,
78):
79    """Enforce password locks, with optional licensed failure counting."""

Enforce password locks, with optional licensed failure counting.