authentik.policies.api.bindings
policy binding API Views
1"""policy binding API Views""" 2 3from collections import OrderedDict 4 5from django.core.exceptions import ObjectDoesNotExist 6from django_filters.filters import BooleanFilter, ModelMultipleChoiceFilter 7from django_filters.filterset import FilterSet 8from rest_framework.exceptions import ValidationError 9from rest_framework.serializers import PrimaryKeyRelatedField 10from rest_framework.viewsets import ModelViewSet 11 12from authentik.core.api.groups import PartialUserSerializer 13from authentik.core.api.used_by import UsedByMixin 14from authentik.core.api.users import PartialGroupSerializer 15from authentik.core.api.utils import ModelSerializer 16from authentik.policies.api.policies import PolicySerializer 17from authentik.policies.models import PolicyBinding, PolicyBindingModel 18 19 20class PolicyBindingModelForeignKey(PrimaryKeyRelatedField): 21 """rest_framework PrimaryKeyRelatedField which resolves 22 model_manager's InheritanceQuerySet""" 23 24 def use_pk_only_optimization(self): 25 return False 26 27 def to_internal_value(self, data): 28 if self.pk_field is not None: 29 data = self.pk_field.to_internal_value(data) 30 try: 31 # pbm_uuid is shared across the inheritance chain, so filtering the base 32 # table by pk resolves straight to the concrete subclass row. 33 return self.get_queryset().get_subclass(pk=data) 34 except ObjectDoesNotExist: 35 self.fail("does_not_exist", pk_value=data) 36 except TypeError, ValueError: 37 self.fail("incorrect_type", data_type=type(data).__name__) 38 39 def to_representation(self, value): 40 correct_model = PolicyBindingModel.objects.get_subclass(pbm_uuid=value.pbm_uuid) 41 return correct_model.pk 42 43 44class PolicyBindingSerializer(ModelSerializer): 45 """PolicyBinding Serializer""" 46 47 # Because we're not interested in the PolicyBindingModel's PK but rather the subclasses PK, 48 # we have to manually declare this field 49 target = PolicyBindingModelForeignKey( 50 queryset=PolicyBindingModel.objects.select_subclasses(), 51 required=True, 52 ) 53 54 policy_obj = PolicySerializer(required=False, allow_null=True, read_only=True, source="policy") 55 group_obj = PartialGroupSerializer( 56 required=False, allow_null=True, read_only=True, source="group" 57 ) 58 user_obj = PartialUserSerializer(required=False, allow_null=True, read_only=True, source="user") 59 60 class Meta: 61 model = PolicyBinding 62 fields = [ 63 "pk", 64 "policy", 65 "group", 66 "user", 67 "policy_obj", 68 "group_obj", 69 "user_obj", 70 "target", 71 "negate", 72 "enabled", 73 "dry_run", 74 "order", 75 "timeout", 76 "failure_result", 77 "expires", 78 "expiring", 79 ] 80 extra_kwargs = { 81 "expires": {"read_only": True}, 82 "expiring": {"read_only": True}, 83 } 84 85 def validate(self, attrs: OrderedDict) -> OrderedDict: 86 """Check that either policy, group or user is set.""" 87 target: PolicyBindingModel = attrs.get("target") 88 supported = target.supported_policy_binding_targets() 89 supported.sort() 90 count = sum([bool(attrs.get(x, None)) for x in supported]) 91 invalid = count > 1 92 empty = count < 1 93 warning = ", ".join(f"'{x}'" for x in supported) 94 if invalid: 95 raise ValidationError(f"Only one of {warning} can be set.") 96 if empty: 97 raise ValidationError(f"One of {warning} must be set.") 98 return attrs 99 100 101class PolicyBindingFilter(FilterSet): 102 """Filter for PolicyBindings""" 103 104 target_in = ModelMultipleChoiceFilter( 105 field_name="target__pbm_uuid", 106 to_field_name="pbm_uuid", 107 queryset=PolicyBindingModel.objects.select_subclasses(), 108 ) 109 policy__isnull = BooleanFilter("policy", "isnull") 110 111 class Meta: 112 model = PolicyBinding 113 fields = ["policy", "policy__isnull", "target", "target_in", "enabled", "order", "timeout"] 114 115 116class PolicyBindingViewSet(UsedByMixin, ModelViewSet): 117 """PolicyBinding Viewset""" 118 119 queryset = ( 120 PolicyBinding.objects.all() 121 .select_related("target", "group", "user") 122 .prefetch_related("policy") 123 ) # prefetching policy so we resolve the subclass 124 serializer_class = PolicyBindingSerializer 125 search_fields = ["policy__name"] 126 filterset_class = PolicyBindingFilter 127 ordering = ["order", "pk"] 128 ordering_fields = ["order", "target__uuid", "pk"]
class
PolicyBindingModelForeignKey(rest_framework.relations.PrimaryKeyRelatedField):
21class PolicyBindingModelForeignKey(PrimaryKeyRelatedField): 22 """rest_framework PrimaryKeyRelatedField which resolves 23 model_manager's InheritanceQuerySet""" 24 25 def use_pk_only_optimization(self): 26 return False 27 28 def to_internal_value(self, data): 29 if self.pk_field is not None: 30 data = self.pk_field.to_internal_value(data) 31 try: 32 # pbm_uuid is shared across the inheritance chain, so filtering the base 33 # table by pk resolves straight to the concrete subclass row. 34 return self.get_queryset().get_subclass(pk=data) 35 except ObjectDoesNotExist: 36 self.fail("does_not_exist", pk_value=data) 37 except TypeError, ValueError: 38 self.fail("incorrect_type", data_type=type(data).__name__) 39 40 def to_representation(self, value): 41 correct_model = PolicyBindingModel.objects.get_subclass(pbm_uuid=value.pbm_uuid) 42 return correct_model.pk
rest_framework PrimaryKeyRelatedField which resolves model_manager's InheritanceQuerySet
def
to_internal_value(self, data):
28 def to_internal_value(self, data): 29 if self.pk_field is not None: 30 data = self.pk_field.to_internal_value(data) 31 try: 32 # pbm_uuid is shared across the inheritance chain, so filtering the base 33 # table by pk resolves straight to the concrete subclass row. 34 return self.get_queryset().get_subclass(pk=data) 35 except ObjectDoesNotExist: 36 self.fail("does_not_exist", pk_value=data) 37 except TypeError, ValueError: 38 self.fail("incorrect_type", data_type=type(data).__name__)
Transform the incoming primitive data into a native value.
45class PolicyBindingSerializer(ModelSerializer): 46 """PolicyBinding Serializer""" 47 48 # Because we're not interested in the PolicyBindingModel's PK but rather the subclasses PK, 49 # we have to manually declare this field 50 target = PolicyBindingModelForeignKey( 51 queryset=PolicyBindingModel.objects.select_subclasses(), 52 required=True, 53 ) 54 55 policy_obj = PolicySerializer(required=False, allow_null=True, read_only=True, source="policy") 56 group_obj = PartialGroupSerializer( 57 required=False, allow_null=True, read_only=True, source="group" 58 ) 59 user_obj = PartialUserSerializer(required=False, allow_null=True, read_only=True, source="user") 60 61 class Meta: 62 model = PolicyBinding 63 fields = [ 64 "pk", 65 "policy", 66 "group", 67 "user", 68 "policy_obj", 69 "group_obj", 70 "user_obj", 71 "target", 72 "negate", 73 "enabled", 74 "dry_run", 75 "order", 76 "timeout", 77 "failure_result", 78 "expires", 79 "expiring", 80 ] 81 extra_kwargs = { 82 "expires": {"read_only": True}, 83 "expiring": {"read_only": True}, 84 } 85 86 def validate(self, attrs: OrderedDict) -> OrderedDict: 87 """Check that either policy, group or user is set.""" 88 target: PolicyBindingModel = attrs.get("target") 89 supported = target.supported_policy_binding_targets() 90 supported.sort() 91 count = sum([bool(attrs.get(x, None)) for x in supported]) 92 invalid = count > 1 93 empty = count < 1 94 warning = ", ".join(f"'{x}'" for x in supported) 95 if invalid: 96 raise ValidationError(f"Only one of {warning} can be set.") 97 if empty: 98 raise ValidationError(f"One of {warning} must be set.") 99 return attrs
PolicyBinding Serializer
def
validate(self, attrs: collections.OrderedDict) -> collections.OrderedDict:
86 def validate(self, attrs: OrderedDict) -> OrderedDict: 87 """Check that either policy, group or user is set.""" 88 target: PolicyBindingModel = attrs.get("target") 89 supported = target.supported_policy_binding_targets() 90 supported.sort() 91 count = sum([bool(attrs.get(x, None)) for x in supported]) 92 invalid = count > 1 93 empty = count < 1 94 warning = ", ".join(f"'{x}'" for x in supported) 95 if invalid: 96 raise ValidationError(f"Only one of {warning} can be set.") 97 if empty: 98 raise ValidationError(f"One of {warning} must be set.") 99 return attrs
Check that either policy, group or user is set.
class
PolicyBindingSerializer.Meta:
61 class Meta: 62 model = PolicyBinding 63 fields = [ 64 "pk", 65 "policy", 66 "group", 67 "user", 68 "policy_obj", 69 "group_obj", 70 "user_obj", 71 "target", 72 "negate", 73 "enabled", 74 "dry_run", 75 "order", 76 "timeout", 77 "failure_result", 78 "expires", 79 "expiring", 80 ] 81 extra_kwargs = { 82 "expires": {"read_only": True}, 83 "expiring": {"read_only": True}, 84 }
model =
<class 'authentik.policies.models.PolicyBinding'>
class
PolicyBindingFilter(django_filters.filterset.FilterSet):
102class PolicyBindingFilter(FilterSet): 103 """Filter for PolicyBindings""" 104 105 target_in = ModelMultipleChoiceFilter( 106 field_name="target__pbm_uuid", 107 to_field_name="pbm_uuid", 108 queryset=PolicyBindingModel.objects.select_subclasses(), 109 ) 110 policy__isnull = BooleanFilter("policy", "isnull") 111 112 class Meta: 113 model = PolicyBinding 114 fields = ["policy", "policy__isnull", "target", "target_in", "enabled", "order", "timeout"]
Filter for PolicyBindings
declared_filters =
OrderedDict({'target_in': <django_filters.filters.ModelMultipleChoiceFilter object>, 'policy__isnull': <django_filters.filters.BooleanFilter object>})
base_filters =
OrderedDict({'policy': <django_filters.filters.ModelChoiceFilter object>, 'policy__isnull': <django_filters.filters.BooleanFilter object>, 'target': <django_filters.filters.ModelChoiceFilter object>, 'target_in': <django_filters.filters.ModelMultipleChoiceFilter object>, 'enabled': <django_filters.filters.BooleanFilter object>, 'order': <django_filters.filters.NumberFilter object>, 'timeout': <django_filters.filters.NumberFilter object>})
class
PolicyBindingFilter.Meta:
112 class Meta: 113 model = PolicyBinding 114 fields = ["policy", "policy__isnull", "target", "target_in", "enabled", "order", "timeout"]
model =
<class 'authentik.policies.models.PolicyBinding'>
class
PolicyBindingViewSet(authentik.core.api.used_by.UsedByMixin, rest_framework.viewsets.ModelViewSet):
117class PolicyBindingViewSet(UsedByMixin, ModelViewSet): 118 """PolicyBinding Viewset""" 119 120 queryset = ( 121 PolicyBinding.objects.all() 122 .select_related("target", "group", "user") 123 .prefetch_related("policy") 124 ) # prefetching policy so we resolve the subclass 125 serializer_class = PolicyBindingSerializer 126 search_fields = ["policy__name"] 127 filterset_class = PolicyBindingFilter 128 ordering = ["order", "pk"] 129 ordering_fields = ["order", "target__uuid", "pk"]
PolicyBinding Viewset
serializer_class =
<class 'PolicyBindingSerializer'>
filterset_class =
<class 'PolicyBindingFilter'>