authentik.core.api.object_attributes

 1from typing import Any
 2
 3from django.contrib.contenttypes.models import ContentType
 4from django.db.models import Model
 5from django.utils.translation import gettext_lazy as _
 6from rest_framework.exceptions import ValidationError
 7from rest_framework.fields import CharField, SerializerMethodField
 8from rest_framework.viewsets import ModelViewSet
 9
10from authentik.core.api.utils import ModelSerializer
11from authentik.core.models import AttributesMixin, ObjectAttribute
12from authentik.lib.utils.dict import get_path_from_dict
13
14
15class AttributesMixinSerializer(ModelSerializer):
16    def validate(self, data: dict[str, Any]) -> dict[str, Any]:
17        model = self.Meta.model
18        attrs = data.get("attributes", {})
19        attributes = ObjectAttribute.objects.filter(
20            object_type=ContentType.objects.get_for_model(model),
21            enabled=True,
22        )
23        instance = self.instance if isinstance(self.instance, Model) else None
24        hidden = self.field_rules(instance).hidden
25        for attr in attributes:
26            path = f"attributes.{attr.key}"
27            if any(path == key or path.startswith(f"{key}.") for key in hidden):
28                continue
29            value = get_path_from_dict(attrs, attr.key)
30            attr.run_validation(value, instance)
31        return data
32
33
34class ContentTypeSerializer(ModelSerializer):
35    app_label = CharField(read_only=True)
36    model = CharField(read_only=True)
37    verbose_name_plural = SerializerMethodField()
38    fully_qualified_model = SerializerMethodField()
39
40    def get_fully_qualified_model(self, ct: ContentType) -> str:
41        return f"{ct.app_label}.{ct.model}"
42
43    def get_verbose_name_plural(self, ct: ContentType) -> str:
44        return ct.model_class()._meta.verbose_name_plural
45
46    class Meta:
47        model = ContentType
48        fields = ("id", "app_label", "model", "verbose_name_plural", "fully_qualified_model")
49
50
51class ObjectAttributeSerializer(ModelSerializer):
52    object_type = CharField()
53    object_type_obj = ContentTypeSerializer(read_only=True, source="object_type")
54
55    def validate_object_type(self, fqm: str) -> ContentType:
56        app_label, _, model = fqm.partition(".")
57        ct = ContentType.objects.filter(app_label=app_label, model=model).first()
58        if not ct or not issubclass(ct.model_class(), AttributesMixin):
59            raise ValidationError("Invalid object type")
60        return ct
61
62    def validate(self, attrs: dict[str, Any]) -> dict[str, Any]:
63        if attrs.get("is_unique") and attrs.get("is_array"):
64            raise ValidationError(_("Unique cannot be enabled for arrays."))
65        return super().validate(attrs)
66
67    class Meta:
68        model = ObjectAttribute
69        fields = [
70            "pk",
71            "object_type",
72            "object_type_obj",
73            "enabled",
74            "created",
75            "key",
76            "label",
77            "last_updated",
78            "regex",
79            "type",
80            "group",
81            "managed",
82            "is_unique",
83            "is_required",
84        ]
85        extra_kwargs = {
86            "last_updated": {"read_only": True},
87            "created": {"read_only": True},
88            "pk": {"read_only": True},
89        }
90
91
92class ObjectAttributeViewSet(ModelViewSet):
93    serializer_class = ObjectAttributeSerializer
94    queryset = ObjectAttribute.objects.all()
95    filterset_fields = ["object_type__model", "object_type__app_label", "enabled"]
96    search_fields = ["key", "label", "group", "object_type__model", "object_type__app_label"]
97    ordering = ["key"]
class AttributesMixinSerializer(authentik.core.api.utils.ModelSerializer):
16class AttributesMixinSerializer(ModelSerializer):
17    def validate(self, data: dict[str, Any]) -> dict[str, Any]:
18        model = self.Meta.model
19        attrs = data.get("attributes", {})
20        attributes = ObjectAttribute.objects.filter(
21            object_type=ContentType.objects.get_for_model(model),
22            enabled=True,
23        )
24        instance = self.instance if isinstance(self.instance, Model) else None
25        hidden = self.field_rules(instance).hidden
26        for attr in attributes:
27            path = f"attributes.{attr.key}"
28            if any(path == key or path.startswith(f"{key}.") for key in hidden):
29                continue
30            value = get_path_from_dict(attrs, attr.key)
31            attr.run_validation(value, instance)
32        return data

A ModelSerializer is just a regular Serializer, except that:

  • A set of default fields are automatically populated.
  • A set of default validators are automatically populated.
  • Default .create() and .update() implementations are provided.

The process of automatically determining a set of serializer fields based on the model fields is reasonably complex, but you almost certainly don't need to dig into the implementation.

If the ModelSerializer class doesn't generate the set of fields that you need you should either declare the extra/differing fields explicitly on the serializer class, or simply use a Serializer class.

def validate(self, data: dict[str, typing.Any]) -> dict[str, typing.Any]:
17    def validate(self, data: dict[str, Any]) -> dict[str, Any]:
18        model = self.Meta.model
19        attrs = data.get("attributes", {})
20        attributes = ObjectAttribute.objects.filter(
21            object_type=ContentType.objects.get_for_model(model),
22            enabled=True,
23        )
24        instance = self.instance if isinstance(self.instance, Model) else None
25        hidden = self.field_rules(instance).hidden
26        for attr in attributes:
27            path = f"attributes.{attr.key}"
28            if any(path == key or path.startswith(f"{key}.") for key in hidden):
29                continue
30            value = get_path_from_dict(attrs, attr.key)
31            attr.run_validation(value, instance)
32        return data
class ContentTypeSerializer(authentik.core.api.utils.ModelSerializer):
35class ContentTypeSerializer(ModelSerializer):
36    app_label = CharField(read_only=True)
37    model = CharField(read_only=True)
38    verbose_name_plural = SerializerMethodField()
39    fully_qualified_model = SerializerMethodField()
40
41    def get_fully_qualified_model(self, ct: ContentType) -> str:
42        return f"{ct.app_label}.{ct.model}"
43
44    def get_verbose_name_plural(self, ct: ContentType) -> str:
45        return ct.model_class()._meta.verbose_name_plural
46
47    class Meta:
48        model = ContentType
49        fields = ("id", "app_label", "model", "verbose_name_plural", "fully_qualified_model")

A ModelSerializer is just a regular Serializer, except that:

  • A set of default fields are automatically populated.
  • A set of default validators are automatically populated.
  • Default .create() and .update() implementations are provided.

The process of automatically determining a set of serializer fields based on the model fields is reasonably complex, but you almost certainly don't need to dig into the implementation.

If the ModelSerializer class doesn't generate the set of fields that you need you should either declare the extra/differing fields explicitly on the serializer class, or simply use a Serializer class.

app_label
model
verbose_name_plural
fully_qualified_model
def get_fully_qualified_model(self, ct: django.contrib.contenttypes.models.ContentType) -> str:
41    def get_fully_qualified_model(self, ct: ContentType) -> str:
42        return f"{ct.app_label}.{ct.model}"
def get_verbose_name_plural(self, ct: django.contrib.contenttypes.models.ContentType) -> str:
44    def get_verbose_name_plural(self, ct: ContentType) -> str:
45        return ct.model_class()._meta.verbose_name_plural
class ContentTypeSerializer.Meta:
47    class Meta:
48        model = ContentType
49        fields = ("id", "app_label", "model", "verbose_name_plural", "fully_qualified_model")
model = <class 'django.contrib.contenttypes.models.ContentType'>
fields = ('id', 'app_label', 'model', 'verbose_name_plural', 'fully_qualified_model')
class ObjectAttributeSerializer(authentik.core.api.utils.ModelSerializer):
52class ObjectAttributeSerializer(ModelSerializer):
53    object_type = CharField()
54    object_type_obj = ContentTypeSerializer(read_only=True, source="object_type")
55
56    def validate_object_type(self, fqm: str) -> ContentType:
57        app_label, _, model = fqm.partition(".")
58        ct = ContentType.objects.filter(app_label=app_label, model=model).first()
59        if not ct or not issubclass(ct.model_class(), AttributesMixin):
60            raise ValidationError("Invalid object type")
61        return ct
62
63    def validate(self, attrs: dict[str, Any]) -> dict[str, Any]:
64        if attrs.get("is_unique") and attrs.get("is_array"):
65            raise ValidationError(_("Unique cannot be enabled for arrays."))
66        return super().validate(attrs)
67
68    class Meta:
69        model = ObjectAttribute
70        fields = [
71            "pk",
72            "object_type",
73            "object_type_obj",
74            "enabled",
75            "created",
76            "key",
77            "label",
78            "last_updated",
79            "regex",
80            "type",
81            "group",
82            "managed",
83            "is_unique",
84            "is_required",
85        ]
86        extra_kwargs = {
87            "last_updated": {"read_only": True},
88            "created": {"read_only": True},
89            "pk": {"read_only": True},
90        }

A ModelSerializer is just a regular Serializer, except that:

  • A set of default fields are automatically populated.
  • A set of default validators are automatically populated.
  • Default .create() and .update() implementations are provided.

The process of automatically determining a set of serializer fields based on the model fields is reasonably complex, but you almost certainly don't need to dig into the implementation.

If the ModelSerializer class doesn't generate the set of fields that you need you should either declare the extra/differing fields explicitly on the serializer class, or simply use a Serializer class.

object_type
object_type_obj
def validate_object_type(self, fqm: str) -> django.contrib.contenttypes.models.ContentType:
56    def validate_object_type(self, fqm: str) -> ContentType:
57        app_label, _, model = fqm.partition(".")
58        ct = ContentType.objects.filter(app_label=app_label, model=model).first()
59        if not ct or not issubclass(ct.model_class(), AttributesMixin):
60            raise ValidationError("Invalid object type")
61        return ct
def validate(self, attrs: dict[str, typing.Any]) -> dict[str, typing.Any]:
63    def validate(self, attrs: dict[str, Any]) -> dict[str, Any]:
64        if attrs.get("is_unique") and attrs.get("is_array"):
65            raise ValidationError(_("Unique cannot be enabled for arrays."))
66        return super().validate(attrs)
class ObjectAttributeSerializer.Meta:
68    class Meta:
69        model = ObjectAttribute
70        fields = [
71            "pk",
72            "object_type",
73            "object_type_obj",
74            "enabled",
75            "created",
76            "key",
77            "label",
78            "last_updated",
79            "regex",
80            "type",
81            "group",
82            "managed",
83            "is_unique",
84            "is_required",
85        ]
86        extra_kwargs = {
87            "last_updated": {"read_only": True},
88            "created": {"read_only": True},
89            "pk": {"read_only": True},
90        }
fields = ['pk', 'object_type', 'object_type_obj', 'enabled', 'created', 'key', 'label', 'last_updated', 'regex', 'type', 'group', 'managed', 'is_unique', 'is_required']
extra_kwargs = {'last_updated': {'read_only': True}, 'created': {'read_only': True}, 'pk': {'read_only': True}}
class ObjectAttributeViewSet(rest_framework.viewsets.ModelViewSet):
93class ObjectAttributeViewSet(ModelViewSet):
94    serializer_class = ObjectAttributeSerializer
95    queryset = ObjectAttribute.objects.all()
96    filterset_fields = ["object_type__model", "object_type__app_label", "enabled"]
97    search_fields = ["key", "label", "group", "object_type__model", "object_type__app_label"]
98    ordering = ["key"]

A viewset that provides default create(), retrieve(), update(), partial_update(), destroy() and list() actions.

serializer_class = <class 'ObjectAttributeSerializer'>
queryset = <QuerySet []>
filterset_fields = ['object_type__model', 'object_type__app_label', 'enabled']
search_fields = ['key', 'label', 'group', 'object_type__model', 'object_type__app_label']
ordering = ['key']
name = None
description = None
suffix = None
detail = None
basename = None