authentik.core.api.utils
API Utilities
1"""API Utilities""" 2 3from typing import Any 4 5from django.db import models 6from django.db.models import Model 7from drf_spectacular.extensions import OpenApiSerializerFieldExtension 8from drf_spectacular.plumbing import build_basic_type 9from drf_spectacular.types import OpenApiTypes 10from rest_framework.fields import ( 11 CharField, 12 IntegerField, 13 JSONField, 14 SerializerMethodField, 15) 16from rest_framework.serializers import ModelSerializer as BaseModelSerializer 17from rest_framework.serializers import ( 18 Serializer, 19 ValidationError, 20 model_meta, 21 raise_errors_on_nested_writes, 22) 23from structlog.stdlib import get_logger 24 25from authentik.lib.models import SimpleThroughModel 26from authentik.rbac.endpoint_checks import EndpointChecks 27from authentik.rbac.field_rules import FieldRules 28 29LOGGER = get_logger() 30 31 32def is_dict(value: Any): 33 """Ensure a value is a dictionary, useful for JSONFields""" 34 if isinstance(value, dict): 35 return 36 raise ValidationError("Value must be a dictionary, and not have any duplicate keys.") 37 38 39class JSONDictField(JSONField): 40 """JSON Field which only allows dictionaries""" 41 42 default_validators = [is_dict] 43 44 45class JSONExtension(OpenApiSerializerFieldExtension): 46 """Generate API Schema for JSON fields as""" 47 48 target_class = "authentik.core.api.utils.JSONDictField" 49 50 def map_serializer_field(self, auto_schema, direction): 51 return build_basic_type(OpenApiTypes.OBJECT) 52 53 54class ModelSerializer(BaseModelSerializer): 55 # By default, JSON fields we have are used to store dictionaries 56 serializer_field_mapping = BaseModelSerializer.serializer_field_mapping.copy() 57 serializer_field_mapping[models.JSONField] = JSONDictField 58 59 def to_representation(self, instance: Model): 60 data = super().to_representation(instance) 61 # `secret_fields` are visible for users which are allowed to change the object 62 secret_fields = getattr(self.Meta, "secret_fields", []) 63 request = self.context.get("request") 64 if secret_fields and request: 65 permission = f"{instance._meta.app_label}.change_{instance._meta.model_name}" 66 if not request.user.has_perm(permission, instance): 67 for field_name in secret_fields: 68 data.pop(field_name, None) 69 if rules := self.field_rules(instance): 70 data = rules.hide(data, self.fields) 71 return data 72 73 def to_internal_value(self, data): 74 # Strip updates to fields not visible to the user 75 instance = self.instance if isinstance(self.instance, Model) else None 76 if rules := self.field_rules(instance): 77 data = rules.restrict_input(data, instance, self.fields) 78 return super().to_internal_value(data) 79 80 def field_rules(self, instance: Model | None) -> FieldRules: 81 request = self.context.get("request") 82 view = self.context.get("view") 83 model = getattr(getattr(self, "Meta", None), "model", None) 84 if request is None or model is None: 85 return FieldRules() 86 if model is not getattr(getattr(view, "queryset", None), "model", None): 87 return FieldRules() 88 checks = EndpointChecks.for_request(request) 89 rules = checks.field_rules(instance) 90 if unknown := rules.unknown_fields(self.fields): 91 checks.report_unknown_fields(unknown) 92 return rules 93 94 def update(self, instance: Model, validated_data): 95 raise_errors_on_nested_writes("update", self, validated_data) 96 info = model_meta.get_field_info(instance) 97 98 # Simply set each attribute on the instance, and then save it. 99 # Note that unlike `.create()` we don't need to treat many-to-many 100 # relationships as being a special case. During updates we already 101 # have an instance pk for the relationships to be associated with. 102 m2m_fields = [] 103 for attr, value in validated_data.items(): 104 if attr in info.relations and info.relations[attr].to_many: 105 m2m_fields.append((attr, value)) 106 else: 107 setattr(instance, attr, value) 108 109 instance.save() 110 111 # Note that many-to-many fields are set after updating instance. 112 # Setting m2m fields triggers signals which could potentially change 113 # updated instance and we do not want it to collide with .update() 114 for attr, value in m2m_fields: 115 field = getattr(instance, attr) 116 # We can't check for inheritance here as m2m managers are generated dynamically 117 if field.__class__.__name__ == "RelatedManager": 118 field.set(value, bulk=False) 119 else: 120 field.set(value) 121 122 return instance 123 124 # To be safe, DRF handles explicit through models differently than implicit ones, for example, 125 # it marks them as `read_only`. However, for "simple" through models, consisting of only the ids 126 # of the related objects, we'd like DRF to handle them as if they were automatically created. 127 def build_relational_field(self, field_name, relation_info): 128 if ( 129 relation_info.model_field is not None 130 and relation_info.model_field.many_to_many 131 and issubclass(relation_info.model_field.remote_field.through, SimpleThroughModel) 132 ): 133 relation_info = relation_info._replace(has_through_model=False) 134 135 return super().build_relational_field(field_name, relation_info) 136 137 138class PassiveSerializer(Serializer): 139 """Base serializer class which doesn't implement create/update methods""" 140 141 def create(self, validated_data: dict) -> Model: # pragma: no cover 142 return Model() 143 144 def update(self, instance: Model, validated_data: dict) -> Model: # pragma: no cover 145 return Model() 146 147 148class PropertyMappingPreviewSerializer(PassiveSerializer): 149 """Preview how the current user is mapped via the property mappings selected in a provider""" 150 151 preview = JSONDictField(read_only=True) 152 153 154class MetaNameSerializer(PassiveSerializer): 155 """Add verbose names to response""" 156 157 verbose_name = SerializerMethodField() 158 verbose_name_plural = SerializerMethodField() 159 meta_model_name = SerializerMethodField() 160 161 def get_verbose_name(self, obj: Model) -> str: 162 """Return object's verbose_name""" 163 return obj._meta.verbose_name 164 165 def get_verbose_name_plural(self, obj: Model) -> str: 166 """Return object's plural verbose_name""" 167 return obj._meta.verbose_name_plural 168 169 def get_meta_model_name(self, obj: Model) -> str: 170 """Return internal model name""" 171 return f"{obj._meta.app_label}.{obj._meta.model_name}" 172 173 174class CacheSerializer(PassiveSerializer): 175 """Generic cache stats for an object""" 176 177 count = IntegerField(read_only=True) 178 179 180class LinkSerializer(PassiveSerializer): 181 """Returns a single link""" 182 183 link = CharField() 184 185 186class ThemedUrlsSerializer(PassiveSerializer): 187 """Themed URLs - maps theme names to URLs for light and dark themes""" 188 189 light = CharField(required=False, allow_null=True) 190 dark = CharField(required=False, allow_null=True)
33def is_dict(value: Any): 34 """Ensure a value is a dictionary, useful for JSONFields""" 35 if isinstance(value, dict): 36 return 37 raise ValidationError("Value must be a dictionary, and not have any duplicate keys.")
Ensure a value is a dictionary, useful for JSONFields
40class JSONDictField(JSONField): 41 """JSON Field which only allows dictionaries""" 42 43 default_validators = [is_dict]
JSON Field which only allows dictionaries
46class JSONExtension(OpenApiSerializerFieldExtension): 47 """Generate API Schema for JSON fields as""" 48 49 target_class = "authentik.core.api.utils.JSONDictField" 50 51 def map_serializer_field(self, auto_schema, direction): 52 return build_basic_type(OpenApiTypes.OBJECT)
Generate API Schema for JSON fields as
55class ModelSerializer(BaseModelSerializer): 56 # By default, JSON fields we have are used to store dictionaries 57 serializer_field_mapping = BaseModelSerializer.serializer_field_mapping.copy() 58 serializer_field_mapping[models.JSONField] = JSONDictField 59 60 def to_representation(self, instance: Model): 61 data = super().to_representation(instance) 62 # `secret_fields` are visible for users which are allowed to change the object 63 secret_fields = getattr(self.Meta, "secret_fields", []) 64 request = self.context.get("request") 65 if secret_fields and request: 66 permission = f"{instance._meta.app_label}.change_{instance._meta.model_name}" 67 if not request.user.has_perm(permission, instance): 68 for field_name in secret_fields: 69 data.pop(field_name, None) 70 if rules := self.field_rules(instance): 71 data = rules.hide(data, self.fields) 72 return data 73 74 def to_internal_value(self, data): 75 # Strip updates to fields not visible to the user 76 instance = self.instance if isinstance(self.instance, Model) else None 77 if rules := self.field_rules(instance): 78 data = rules.restrict_input(data, instance, self.fields) 79 return super().to_internal_value(data) 80 81 def field_rules(self, instance: Model | None) -> FieldRules: 82 request = self.context.get("request") 83 view = self.context.get("view") 84 model = getattr(getattr(self, "Meta", None), "model", None) 85 if request is None or model is None: 86 return FieldRules() 87 if model is not getattr(getattr(view, "queryset", None), "model", None): 88 return FieldRules() 89 checks = EndpointChecks.for_request(request) 90 rules = checks.field_rules(instance) 91 if unknown := rules.unknown_fields(self.fields): 92 checks.report_unknown_fields(unknown) 93 return rules 94 95 def update(self, instance: Model, validated_data): 96 raise_errors_on_nested_writes("update", self, validated_data) 97 info = model_meta.get_field_info(instance) 98 99 # Simply set each attribute on the instance, and then save it. 100 # Note that unlike `.create()` we don't need to treat many-to-many 101 # relationships as being a special case. During updates we already 102 # have an instance pk for the relationships to be associated with. 103 m2m_fields = [] 104 for attr, value in validated_data.items(): 105 if attr in info.relations and info.relations[attr].to_many: 106 m2m_fields.append((attr, value)) 107 else: 108 setattr(instance, attr, value) 109 110 instance.save() 111 112 # Note that many-to-many fields are set after updating instance. 113 # Setting m2m fields triggers signals which could potentially change 114 # updated instance and we do not want it to collide with .update() 115 for attr, value in m2m_fields: 116 field = getattr(instance, attr) 117 # We can't check for inheritance here as m2m managers are generated dynamically 118 if field.__class__.__name__ == "RelatedManager": 119 field.set(value, bulk=False) 120 else: 121 field.set(value) 122 123 return instance 124 125 # To be safe, DRF handles explicit through models differently than implicit ones, for example, 126 # it marks them as `read_only`. However, for "simple" through models, consisting of only the ids 127 # of the related objects, we'd like DRF to handle them as if they were automatically created. 128 def build_relational_field(self, field_name, relation_info): 129 if ( 130 relation_info.model_field is not None 131 and relation_info.model_field.many_to_many 132 and issubclass(relation_info.model_field.remote_field.through, SimpleThroughModel) 133 ): 134 relation_info = relation_info._replace(has_through_model=False) 135 136 return super().build_relational_field(field_name, relation_info)
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.
60 def to_representation(self, instance: Model): 61 data = super().to_representation(instance) 62 # `secret_fields` are visible for users which are allowed to change the object 63 secret_fields = getattr(self.Meta, "secret_fields", []) 64 request = self.context.get("request") 65 if secret_fields and request: 66 permission = f"{instance._meta.app_label}.change_{instance._meta.model_name}" 67 if not request.user.has_perm(permission, instance): 68 for field_name in secret_fields: 69 data.pop(field_name, None) 70 if rules := self.field_rules(instance): 71 data = rules.hide(data, self.fields) 72 return data
Object instance -> Dict of primitive datatypes.
74 def to_internal_value(self, data): 75 # Strip updates to fields not visible to the user 76 instance = self.instance if isinstance(self.instance, Model) else None 77 if rules := self.field_rules(instance): 78 data = rules.restrict_input(data, instance, self.fields) 79 return super().to_internal_value(data)
Dict of native values <- Dict of primitive datatypes.
81 def field_rules(self, instance: Model | None) -> FieldRules: 82 request = self.context.get("request") 83 view = self.context.get("view") 84 model = getattr(getattr(self, "Meta", None), "model", None) 85 if request is None or model is None: 86 return FieldRules() 87 if model is not getattr(getattr(view, "queryset", None), "model", None): 88 return FieldRules() 89 checks = EndpointChecks.for_request(request) 90 rules = checks.field_rules(instance) 91 if unknown := rules.unknown_fields(self.fields): 92 checks.report_unknown_fields(unknown) 93 return rules
95 def update(self, instance: Model, validated_data): 96 raise_errors_on_nested_writes("update", self, validated_data) 97 info = model_meta.get_field_info(instance) 98 99 # Simply set each attribute on the instance, and then save it. 100 # Note that unlike `.create()` we don't need to treat many-to-many 101 # relationships as being a special case. During updates we already 102 # have an instance pk for the relationships to be associated with. 103 m2m_fields = [] 104 for attr, value in validated_data.items(): 105 if attr in info.relations and info.relations[attr].to_many: 106 m2m_fields.append((attr, value)) 107 else: 108 setattr(instance, attr, value) 109 110 instance.save() 111 112 # Note that many-to-many fields are set after updating instance. 113 # Setting m2m fields triggers signals which could potentially change 114 # updated instance and we do not want it to collide with .update() 115 for attr, value in m2m_fields: 116 field = getattr(instance, attr) 117 # We can't check for inheritance here as m2m managers are generated dynamically 118 if field.__class__.__name__ == "RelatedManager": 119 field.set(value, bulk=False) 120 else: 121 field.set(value) 122 123 return instance
128 def build_relational_field(self, field_name, relation_info): 129 if ( 130 relation_info.model_field is not None 131 and relation_info.model_field.many_to_many 132 and issubclass(relation_info.model_field.remote_field.through, SimpleThroughModel) 133 ): 134 relation_info = relation_info._replace(has_through_model=False) 135 136 return super().build_relational_field(field_name, relation_info)
Create fields for forward and reverse relationships.
139class PassiveSerializer(Serializer): 140 """Base serializer class which doesn't implement create/update methods""" 141 142 def create(self, validated_data: dict) -> Model: # pragma: no cover 143 return Model() 144 145 def update(self, instance: Model, validated_data: dict) -> Model: # pragma: no cover 146 return Model()
Base serializer class which doesn't implement create/update methods
149class PropertyMappingPreviewSerializer(PassiveSerializer): 150 """Preview how the current user is mapped via the property mappings selected in a provider""" 151 152 preview = JSONDictField(read_only=True)
Preview how the current user is mapped via the property mappings selected in a provider
Inherited Members
155class MetaNameSerializer(PassiveSerializer): 156 """Add verbose names to response""" 157 158 verbose_name = SerializerMethodField() 159 verbose_name_plural = SerializerMethodField() 160 meta_model_name = SerializerMethodField() 161 162 def get_verbose_name(self, obj: Model) -> str: 163 """Return object's verbose_name""" 164 return obj._meta.verbose_name 165 166 def get_verbose_name_plural(self, obj: Model) -> str: 167 """Return object's plural verbose_name""" 168 return obj._meta.verbose_name_plural 169 170 def get_meta_model_name(self, obj: Model) -> str: 171 """Return internal model name""" 172 return f"{obj._meta.app_label}.{obj._meta.model_name}"
Add verbose names to response
162 def get_verbose_name(self, obj: Model) -> str: 163 """Return object's verbose_name""" 164 return obj._meta.verbose_name
Return object's verbose_name
166 def get_verbose_name_plural(self, obj: Model) -> str: 167 """Return object's plural verbose_name""" 168 return obj._meta.verbose_name_plural
Return object's plural verbose_name
170 def get_meta_model_name(self, obj: Model) -> str: 171 """Return internal model name""" 172 return f"{obj._meta.app_label}.{obj._meta.model_name}"
Return internal model name
Inherited Members
175class CacheSerializer(PassiveSerializer): 176 """Generic cache stats for an object""" 177 178 count = IntegerField(read_only=True)
Generic cache stats for an object
Inherited Members
181class LinkSerializer(PassiveSerializer): 182 """Returns a single link""" 183 184 link = CharField()
Returns a single link
Inherited Members
187class ThemedUrlsSerializer(PassiveSerializer): 188 """Themed URLs - maps theme names to URLs for light and dark themes""" 189 190 light = CharField(required=False, allow_null=True) 191 dark = CharField(required=False, allow_null=True)
Themed URLs - maps theme names to URLs for light and dark themes