authentik.stages.password.api

PasswordStage API Views

 1"""PasswordStage API Views"""
 2
 3from django.db import transaction
 4from drf_spectacular.utils import OpenApiResponse, extend_schema
 5from rest_framework.decorators import action
 6from rest_framework.permissions import IsAuthenticated
 7from rest_framework.request import Request
 8from rest_framework.response import Response
 9from rest_framework.viewsets import GenericViewSet, ModelViewSet
10
11from authentik.core.api.used_by import UsedByMixin
12from authentik.core.models import User
13from authentik.events.models import Event, EventAction
14from authentik.flows.api.stages import StageSerializer
15from authentik.lib.utils.reflection import ConditionalInheritance
16from authentik.rbac.filters import ObjectFilter
17from authentik.stages.password.models import PasswordDevice, PasswordStage
18
19
20class PasswordStageSerializer(StageSerializer):
21    """PasswordStage Serializer"""
22
23    class Meta:
24        model = PasswordStage
25        fields = StageSerializer.Meta.fields + [
26            "backends",
27            "configure_flow",
28            "failed_attempts_before_cancel",
29            "failed_attempts_before_lockout",
30            "last_attempt_warning_message",
31            "lockout_message",
32            "allow_show_password",
33        ]
34
35
36class PasswordStageViewSet(UsedByMixin, ModelViewSet):
37    """PasswordStage Viewset"""
38
39    queryset = PasswordStage.objects.all()
40    serializer_class = PasswordStageSerializer
41    filterset_fields = [
42        "name",
43        "configure_flow",
44        "failed_attempts_before_cancel",
45        "failed_attempts_before_lockout",
46        "allow_show_password",
47    ]
48    search_fields = ["name"]
49    ordering = ["name"]
50
51
52class PasswordDeviceViewSet(
53    ConditionalInheritance("authentik.enterprise.stages.password.api.PasswordDeviceLockoutMixin"),
54    GenericViewSet,
55):
56    """Manage password locks with the owning user's password-reset permission."""
57
58    queryset = PasswordDevice.objects.select_related("user")
59    permission_classes = [IsAuthenticated]
60    filter_backends = []
61
62    def get_queryset(self):
63        users = ObjectFilter().filter_queryset(self.request, User.objects.all(), self)
64        return super().get_queryset().filter(user__in=users)
65
66    def get_object(self) -> PasswordDevice:
67        device = super().get_object()
68        permission = "authentik_core.reset_user_password"
69        if not (
70            self.request.user.has_perm(permission)
71            or self.request.user.has_perm(permission, device.user)
72        ):
73            self.permission_denied(self.request)
74        return device
75
76    @extend_schema(
77        request=None,
78        responses={204: OpenApiResponse(description="Successfully unlocked authenticator")},
79    )
80    @action(detail=True, methods=["POST"])
81    @transaction.atomic
82    def unlock(self, request: Request, pk: int) -> Response:
83        """Allow a locked password authenticator to authenticate again."""
84        device = self.get_object()
85        if PasswordDevice.objects.filter(pk=device.pk, locked_at__isnull=False).update(
86            failed_attempts=0, locked_at=None
87        ):
88            Event.new(
89                EventAction.AUTHENTICATOR_UNLOCKED,
90                affected_user=device.user,
91                authenticator=device,
92            ).from_http(request)
93        return Response(status=204)
class PasswordStageSerializer(authentik.flows.api.stages.StageSerializer):
21class PasswordStageSerializer(StageSerializer):
22    """PasswordStage Serializer"""
23
24    class Meta:
25        model = PasswordStage
26        fields = StageSerializer.Meta.fields + [
27            "backends",
28            "configure_flow",
29            "failed_attempts_before_cancel",
30            "failed_attempts_before_lockout",
31            "last_attempt_warning_message",
32            "lockout_message",
33            "allow_show_password",
34        ]

PasswordStage Serializer

class PasswordStageSerializer.Meta:
24    class Meta:
25        model = PasswordStage
26        fields = StageSerializer.Meta.fields + [
27            "backends",
28            "configure_flow",
29            "failed_attempts_before_cancel",
30            "failed_attempts_before_lockout",
31            "last_attempt_warning_message",
32            "lockout_message",
33            "allow_show_password",
34        ]
fields = ['pk', 'name', 'component', 'verbose_name', 'verbose_name_plural', 'meta_model_name', 'flow_set', 'backends', 'configure_flow', 'failed_attempts_before_cancel', 'failed_attempts_before_lockout', 'last_attempt_warning_message', 'lockout_message', 'allow_show_password']
class PasswordStageViewSet(authentik.core.api.used_by.UsedByMixin, rest_framework.viewsets.ModelViewSet):
37class PasswordStageViewSet(UsedByMixin, ModelViewSet):
38    """PasswordStage Viewset"""
39
40    queryset = PasswordStage.objects.all()
41    serializer_class = PasswordStageSerializer
42    filterset_fields = [
43        "name",
44        "configure_flow",
45        "failed_attempts_before_cancel",
46        "failed_attempts_before_lockout",
47        "allow_show_password",
48    ]
49    search_fields = ["name"]
50    ordering = ["name"]

PasswordStage Viewset

queryset = <InheritanceQuerySet []>
serializer_class = <class 'PasswordStageSerializer'>
filterset_fields = ['name', 'configure_flow', 'failed_attempts_before_cancel', 'failed_attempts_before_lockout', 'allow_show_password']
search_fields = ['name']
ordering = ['name']
name = None
description = None
suffix = None
detail = None
basename = None
class PasswordDeviceViewSet(authentik.enterprise.stages.password.api.PasswordDeviceLockoutMixin, rest_framework.viewsets.GenericViewSet):
53class PasswordDeviceViewSet(
54    ConditionalInheritance("authentik.enterprise.stages.password.api.PasswordDeviceLockoutMixin"),
55    GenericViewSet,
56):
57    """Manage password locks with the owning user's password-reset permission."""
58
59    queryset = PasswordDevice.objects.select_related("user")
60    permission_classes = [IsAuthenticated]
61    filter_backends = []
62
63    def get_queryset(self):
64        users = ObjectFilter().filter_queryset(self.request, User.objects.all(), self)
65        return super().get_queryset().filter(user__in=users)
66
67    def get_object(self) -> PasswordDevice:
68        device = super().get_object()
69        permission = "authentik_core.reset_user_password"
70        if not (
71            self.request.user.has_perm(permission)
72            or self.request.user.has_perm(permission, device.user)
73        ):
74            self.permission_denied(self.request)
75        return device
76
77    @extend_schema(
78        request=None,
79        responses={204: OpenApiResponse(description="Successfully unlocked authenticator")},
80    )
81    @action(detail=True, methods=["POST"])
82    @transaction.atomic
83    def unlock(self, request: Request, pk: int) -> Response:
84        """Allow a locked password authenticator to authenticate again."""
85        device = self.get_object()
86        if PasswordDevice.objects.filter(pk=device.pk, locked_at__isnull=False).update(
87            failed_attempts=0, locked_at=None
88        ):
89            Event.new(
90                EventAction.AUTHENTICATOR_UNLOCKED,
91                affected_user=device.user,
92                authenticator=device,
93            ).from_http(request)
94        return Response(status=204)

Manage password locks with the owning user's password-reset permission.

queryset = <QuerySet []>
permission_classes = [<class 'rest_framework.permissions.IsAuthenticated'>]
filter_backends = []
def get_queryset(self):
63    def get_queryset(self):
64        users = ObjectFilter().filter_queryset(self.request, User.objects.all(), self)
65        return super().get_queryset().filter(user__in=users)

Get the list of items for this view. This must be an iterable, and may be a queryset. Defaults to using self.queryset.

This method should always be used rather than accessing self.queryset directly, as self.queryset gets evaluated only once, and those results are cached for all subsequent requests.

You may want to override this if you need to provide different querysets depending on the incoming request.

(Eg. return a list of items that is specific to the user)

def get_object(self) -> authentik.stages.password.models.PasswordDevice:
67    def get_object(self) -> PasswordDevice:
68        device = super().get_object()
69        permission = "authentik_core.reset_user_password"
70        if not (
71            self.request.user.has_perm(permission)
72            or self.request.user.has_perm(permission, device.user)
73        ):
74            self.permission_denied(self.request)
75        return device

Returns the object the view is displaying.

You may want to override this if you need to provide non-standard queryset lookups. Eg if objects are referenced using multiple keyword arguments in the url conf.

@extend_schema(request=None, responses={204: OpenApiResponse(description='Successfully unlocked authenticator')})
@action(detail=True, methods=['POST'])
@transaction.atomic
def unlock( self, request: rest_framework.request.Request, pk: int) -> rest_framework.response.Response:
77    @extend_schema(
78        request=None,
79        responses={204: OpenApiResponse(description="Successfully unlocked authenticator")},
80    )
81    @action(detail=True, methods=["POST"])
82    @transaction.atomic
83    def unlock(self, request: Request, pk: int) -> Response:
84        """Allow a locked password authenticator to authenticate again."""
85        device = self.get_object()
86        if PasswordDevice.objects.filter(pk=device.pk, locked_at__isnull=False).update(
87            failed_attempts=0, locked_at=None
88        ):
89            Event.new(
90                EventAction.AUTHENTICATOR_UNLOCKED,
91                affected_user=device.user,
92                authenticator=device,
93            ).from_http(request)
94        return Response(status=204)

Allow a locked password authenticator to authenticate again.

name = None
description = None
suffix = None
detail = None
basename = None