authentik.rbac.api.custom_permissions
1from re import compile as re_compile 2 3from django.contrib.contenttypes.models import ContentType 4from django.utils.translation import gettext_lazy as _ 5from django_filters.rest_framework import DjangoFilterBackend 6from rest_framework.exceptions import ValidationError 7from rest_framework.fields import CharField, SerializerMethodField 8from rest_framework.filters import OrderingFilter, SearchFilter 9from rest_framework.viewsets import ModelViewSet 10 11from authentik.core.api.utils import ModelSerializer 12from authentik.rbac.models import CUSTOM_PERMISSION_PREFIX, CustomPermission 13 14CODENAME = re_compile(rf"{CUSTOM_PERMISSION_PREFIX}[a-z0-9_]+") 15 16 17class ModelLabelField(CharField): 18 """The content type of an authentik model, as app_label.model_name""" 19 20 def to_representation(self, content_type: ContentType) -> str: 21 return f"{content_type.app_label}.{content_type.model}" 22 23 def to_internal_value(self, data) -> ContentType: 24 app_label, dot, model = super().to_internal_value(data).partition(".") 25 content_type = ContentType.objects.filter(app_label=app_label, model=model).first() 26 if not dot or content_type is None or not app_label.startswith("authentik"): 27 raise ValidationError(_("Unknown model.")) 28 return content_type 29 30 31class CustomPermissionSerializer(ModelSerializer): 32 model = ModelLabelField(source="content_type") 33 permission = SerializerMethodField() 34 35 def get_permission(self, instance: CustomPermission) -> str: 36 return f"{instance.content_type.app_label}.{instance.codename}" 37 38 def validate_codename(self, codename: str) -> str: 39 if self.instance and codename != self.instance.codename: 40 raise ValidationError(_("This cannot change.")) 41 if not CODENAME.fullmatch(codename): 42 raise ValidationError( 43 _("Start with custom_, followed by lowercase letters, digits, and underscores.") 44 ) 45 return codename 46 47 def validate_model(self, content_type: ContentType) -> ContentType: 48 if self.instance and content_type != self.instance.content_type: 49 raise ValidationError(_("This cannot change.")) 50 return content_type 51 52 class Meta: 53 model = CustomPermission 54 fields = ["pk", "codename", "name", "model", "permission"] 55 56 57class CustomPermissionViewSet(ModelViewSet): 58 """Custom permissions""" 59 60 queryset = CustomPermission.objects.select_related("content_type") 61 serializer_class = CustomPermissionSerializer 62 filter_backends = [DjangoFilterBackend, OrderingFilter, SearchFilter] 63 filterset_fields = ["codename"] 64 search_fields = ["codename", "name"] 65 ordering = ["codename"]
CODENAME =
re.compile('custom_[a-z0-9_]+')
class
ModelLabelField(rest_framework.fields.CharField):
18class ModelLabelField(CharField): 19 """The content type of an authentik model, as app_label.model_name""" 20 21 def to_representation(self, content_type: ContentType) -> str: 22 return f"{content_type.app_label}.{content_type.model}" 23 24 def to_internal_value(self, data) -> ContentType: 25 app_label, dot, model = super().to_internal_value(data).partition(".") 26 content_type = ContentType.objects.filter(app_label=app_label, model=model).first() 27 if not dot or content_type is None or not app_label.startswith("authentik"): 28 raise ValidationError(_("Unknown model.")) 29 return content_type
The content type of an authentik model, as app_label.model_name
def
to_representation( self, content_type: django.contrib.contenttypes.models.ContentType) -> str:
21 def to_representation(self, content_type: ContentType) -> str: 22 return f"{content_type.app_label}.{content_type.model}"
Transform the outgoing native value into primitive data.
def
to_internal_value(self, data) -> django.contrib.contenttypes.models.ContentType:
24 def to_internal_value(self, data) -> ContentType: 25 app_label, dot, model = super().to_internal_value(data).partition(".") 26 content_type = ContentType.objects.filter(app_label=app_label, model=model).first() 27 if not dot or content_type is None or not app_label.startswith("authentik"): 28 raise ValidationError(_("Unknown model.")) 29 return content_type
Transform the incoming primitive data into a native value.
32class CustomPermissionSerializer(ModelSerializer): 33 model = ModelLabelField(source="content_type") 34 permission = SerializerMethodField() 35 36 def get_permission(self, instance: CustomPermission) -> str: 37 return f"{instance.content_type.app_label}.{instance.codename}" 38 39 def validate_codename(self, codename: str) -> str: 40 if self.instance and codename != self.instance.codename: 41 raise ValidationError(_("This cannot change.")) 42 if not CODENAME.fullmatch(codename): 43 raise ValidationError( 44 _("Start with custom_, followed by lowercase letters, digits, and underscores.") 45 ) 46 return codename 47 48 def validate_model(self, content_type: ContentType) -> ContentType: 49 if self.instance and content_type != self.instance.content_type: 50 raise ValidationError(_("This cannot change.")) 51 return content_type 52 53 class Meta: 54 model = CustomPermission 55 fields = ["pk", "codename", "name", "model", "permission"]
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_codename(self, codename: str) -> str:
39 def validate_codename(self, codename: str) -> str: 40 if self.instance and codename != self.instance.codename: 41 raise ValidationError(_("This cannot change.")) 42 if not CODENAME.fullmatch(codename): 43 raise ValidationError( 44 _("Start with custom_, followed by lowercase letters, digits, and underscores.") 45 ) 46 return codename
class
CustomPermissionSerializer.Meta:
53 class Meta: 54 model = CustomPermission 55 fields = ["pk", "codename", "name", "model", "permission"]
model =
<class 'authentik.rbac.models.CustomPermission'>
class
CustomPermissionViewSet(rest_framework.viewsets.ModelViewSet):
58class CustomPermissionViewSet(ModelViewSet): 59 """Custom permissions""" 60 61 queryset = CustomPermission.objects.select_related("content_type") 62 serializer_class = CustomPermissionSerializer 63 filter_backends = [DjangoFilterBackend, OrderingFilter, SearchFilter] 64 filterset_fields = ["codename"] 65 search_fields = ["codename", "name"] 66 ordering = ["codename"]
Custom permissions
serializer_class =
<class 'CustomPermissionSerializer'>