authentik.endpoints.api.devices
1from datetime import timedelta 2from uuid import uuid4 3 4from django.db.models import OuterRef, Prefetch, Subquery 5from django.utils.timezone import now 6from drf_spectacular.utils import extend_schema 7from rest_framework.decorators import action 8from rest_framework.fields import IntegerField, SerializerMethodField 9from rest_framework.request import Request 10from rest_framework.response import Response 11from rest_framework.serializers import ValidationError 12from rest_framework.viewsets import ModelViewSet 13 14from authentik.core.api.used_by import UsedByMixin 15from authentik.core.api.utils import ModelSerializer, PassiveSerializer 16from authentik.endpoints.api.device_access_group import DeviceAccessGroupSerializer 17from authentik.endpoints.api.device_connections import DeviceConnectionSerializer 18from authentik.endpoints.api.device_fact_snapshots import DeviceFactSnapshotSerializer 19from authentik.endpoints.api.device_user_bindings import DeviceUserBindingSerializer 20from authentik.endpoints.models import Device, DeviceFactSnapshot, DeviceUserBinding 21from authentik.providers.rac.api.connection_overrides import RACConnectionOverrideSerializer 22from authentik.providers.rac.models import RACConnectionOverride 23 24 25class EndpointDeviceSerializer(ModelSerializer): 26 27 access_group_obj = DeviceAccessGroupSerializer(source="access_group", required=False) 28 29 facts = SerializerMethodField(allow_null=True) 30 31 primary_binding_obj = DeviceUserBindingSerializer( 32 source="primary_user_binding", read_only=True, allow_null=True 33 ) 34 35 rac = RACConnectionOverrideSerializer(source="rac_override", allow_null=True) 36 37 def get_facts(self, instance: Device) -> DeviceFactSnapshotSerializer: 38 try: 39 return DeviceFactSnapshotSerializer(instance.cached_facts).data 40 except KeyError, AttributeError: 41 return None 42 43 def validate(self, attrs: dict) -> dict: 44 attrs = super().validate(attrs) 45 # A device which is added through the API is not enrolled by a connector, so it 46 # cannot report how it is reached and has to be told 47 if not self.instance and not attrs.get("rac_override"): 48 raise ValidationError({"rac": "This field is required."}) 49 return attrs 50 51 def create(self, validated_data: dict) -> Device: 52 """Devices created through the API are not enrolled by a connector, so they get 53 a generated identifier and don't expire.""" 54 override = validated_data.pop("rac_override") 55 validated_data.setdefault("identifier", f"manual://{uuid4()}") 56 validated_data.setdefault("expiring", False) 57 device = super().create(validated_data) 58 RACConnectionOverride.objects.create(device=device, **override) 59 return device 60 61 def update(self, instance: Device, validated_data: dict) -> Device: 62 override = validated_data.pop("rac_override", None) 63 device = super().update(instance, validated_data) 64 if override: 65 RACConnectionOverride.objects.update_or_create(device=device, defaults=override) 66 return device 67 68 class Meta: 69 model = Device 70 fields = [ 71 "device_uuid", 72 "pbm_uuid", 73 "name", 74 "access_group", 75 "access_group_obj", 76 "expiring", 77 "expires", 78 "facts", 79 "attributes", 80 "primary_binding_obj", 81 "rac", 82 ] 83 84 85class EndpointDeviceDetailsSerializer(EndpointDeviceSerializer): 86 87 connections_obj = DeviceConnectionSerializer(many=True, source="deviceconnection_set") 88 89 def get_facts(self, instance: Device) -> DeviceFactSnapshotSerializer: 90 try: 91 return DeviceFactSnapshotSerializer(instance.facts).data 92 except KeyError, AttributeError: 93 return None 94 95 class Meta(EndpointDeviceSerializer.Meta): 96 fields = EndpointDeviceSerializer.Meta.fields + [ 97 "connections_obj", 98 "policies", 99 "connections", 100 ] 101 102 103class DeviceViewSet(UsedByMixin, ModelViewSet): 104 105 queryset = ( 106 Device.objects.all() 107 .select_related("access_group") 108 .prefetch_related( 109 Prefetch("bindings", queryset=DeviceUserBinding.objects.all(), to_attr="user_bindings") 110 ) 111 ) 112 serializer_class = EndpointDeviceSerializer 113 search_fields = [ 114 "name", 115 "identifier", 116 ] 117 ordering = ["identifier"] 118 filterset_fields = ["name", "identifier"] 119 120 class DeviceSummarySerializer(PassiveSerializer): 121 """Summary of registered devices""" 122 123 total_count = IntegerField() 124 unreachable_count = IntegerField() 125 outdated_agent_count = IntegerField() 126 127 def get_serializer_class(self): 128 if self.action == "retrieve": 129 return EndpointDeviceDetailsSerializer 130 return super().get_serializer_class() 131 132 def get_queryset(self): 133 if self.action == "retrieve": 134 return super().get_queryset().prefetch_related("connections") 135 return super().get_queryset() 136 137 @extend_schema(responses={200: DeviceSummarySerializer()}) 138 @action(methods=["GET"], detail=False) 139 def summary(self, request: Request) -> Response: 140 delta = now() - timedelta(hours=24) 141 unreachable = ( 142 Device.objects.all() 143 .annotate( 144 latest_snapshot=Subquery( 145 DeviceFactSnapshot.objects.filter(connection__device=OuterRef("pk")) 146 .order_by("-created") 147 .values("created")[:1] 148 ) 149 ) 150 .filter(latest_snapshot__lte=delta) 151 .distinct() 152 .count() 153 ) 154 data = { 155 "total_count": Device.objects.all().count(), 156 "unreachable_count": unreachable, 157 # Currently not supported 158 "outdated_agent_count": 0, 159 } 160 return Response(data)
26class EndpointDeviceSerializer(ModelSerializer): 27 28 access_group_obj = DeviceAccessGroupSerializer(source="access_group", required=False) 29 30 facts = SerializerMethodField(allow_null=True) 31 32 primary_binding_obj = DeviceUserBindingSerializer( 33 source="primary_user_binding", read_only=True, allow_null=True 34 ) 35 36 rac = RACConnectionOverrideSerializer(source="rac_override", allow_null=True) 37 38 def get_facts(self, instance: Device) -> DeviceFactSnapshotSerializer: 39 try: 40 return DeviceFactSnapshotSerializer(instance.cached_facts).data 41 except KeyError, AttributeError: 42 return None 43 44 def validate(self, attrs: dict) -> dict: 45 attrs = super().validate(attrs) 46 # A device which is added through the API is not enrolled by a connector, so it 47 # cannot report how it is reached and has to be told 48 if not self.instance and not attrs.get("rac_override"): 49 raise ValidationError({"rac": "This field is required."}) 50 return attrs 51 52 def create(self, validated_data: dict) -> Device: 53 """Devices created through the API are not enrolled by a connector, so they get 54 a generated identifier and don't expire.""" 55 override = validated_data.pop("rac_override") 56 validated_data.setdefault("identifier", f"manual://{uuid4()}") 57 validated_data.setdefault("expiring", False) 58 device = super().create(validated_data) 59 RACConnectionOverride.objects.create(device=device, **override) 60 return device 61 62 def update(self, instance: Device, validated_data: dict) -> Device: 63 override = validated_data.pop("rac_override", None) 64 device = super().update(instance, validated_data) 65 if override: 66 RACConnectionOverride.objects.update_or_create(device=device, defaults=override) 67 return device 68 69 class Meta: 70 model = Device 71 fields = [ 72 "device_uuid", 73 "pbm_uuid", 74 "name", 75 "access_group", 76 "access_group_obj", 77 "expiring", 78 "expires", 79 "facts", 80 "attributes", 81 "primary_binding_obj", 82 "rac", 83 ]
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.
44 def validate(self, attrs: dict) -> dict: 45 attrs = super().validate(attrs) 46 # A device which is added through the API is not enrolled by a connector, so it 47 # cannot report how it is reached and has to be told 48 if not self.instance and not attrs.get("rac_override"): 49 raise ValidationError({"rac": "This field is required."}) 50 return attrs
52 def create(self, validated_data: dict) -> Device: 53 """Devices created through the API are not enrolled by a connector, so they get 54 a generated identifier and don't expire.""" 55 override = validated_data.pop("rac_override") 56 validated_data.setdefault("identifier", f"manual://{uuid4()}") 57 validated_data.setdefault("expiring", False) 58 device = super().create(validated_data) 59 RACConnectionOverride.objects.create(device=device, **override) 60 return device
Devices created through the API are not enrolled by a connector, so they get a generated identifier and don't expire.
69 class Meta: 70 model = Device 71 fields = [ 72 "device_uuid", 73 "pbm_uuid", 74 "name", 75 "access_group", 76 "access_group_obj", 77 "expiring", 78 "expires", 79 "facts", 80 "attributes", 81 "primary_binding_obj", 82 "rac", 83 ]
86class EndpointDeviceDetailsSerializer(EndpointDeviceSerializer): 87 88 connections_obj = DeviceConnectionSerializer(many=True, source="deviceconnection_set") 89 90 def get_facts(self, instance: Device) -> DeviceFactSnapshotSerializer: 91 try: 92 return DeviceFactSnapshotSerializer(instance.facts).data 93 except KeyError, AttributeError: 94 return None 95 96 class Meta(EndpointDeviceSerializer.Meta): 97 fields = EndpointDeviceSerializer.Meta.fields + [ 98 "connections_obj", 99 "policies", 100 "connections", 101 ]
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.
96 class Meta(EndpointDeviceSerializer.Meta): 97 fields = EndpointDeviceSerializer.Meta.fields + [ 98 "connections_obj", 99 "policies", 100 "connections", 101 ]
Inherited Members
104class DeviceViewSet(UsedByMixin, ModelViewSet): 105 106 queryset = ( 107 Device.objects.all() 108 .select_related("access_group") 109 .prefetch_related( 110 Prefetch("bindings", queryset=DeviceUserBinding.objects.all(), to_attr="user_bindings") 111 ) 112 ) 113 serializer_class = EndpointDeviceSerializer 114 search_fields = [ 115 "name", 116 "identifier", 117 ] 118 ordering = ["identifier"] 119 filterset_fields = ["name", "identifier"] 120 121 class DeviceSummarySerializer(PassiveSerializer): 122 """Summary of registered devices""" 123 124 total_count = IntegerField() 125 unreachable_count = IntegerField() 126 outdated_agent_count = IntegerField() 127 128 def get_serializer_class(self): 129 if self.action == "retrieve": 130 return EndpointDeviceDetailsSerializer 131 return super().get_serializer_class() 132 133 def get_queryset(self): 134 if self.action == "retrieve": 135 return super().get_queryset().prefetch_related("connections") 136 return super().get_queryset() 137 138 @extend_schema(responses={200: DeviceSummarySerializer()}) 139 @action(methods=["GET"], detail=False) 140 def summary(self, request: Request) -> Response: 141 delta = now() - timedelta(hours=24) 142 unreachable = ( 143 Device.objects.all() 144 .annotate( 145 latest_snapshot=Subquery( 146 DeviceFactSnapshot.objects.filter(connection__device=OuterRef("pk")) 147 .order_by("-created") 148 .values("created")[:1] 149 ) 150 ) 151 .filter(latest_snapshot__lte=delta) 152 .distinct() 153 .count() 154 ) 155 data = { 156 "total_count": Device.objects.all().count(), 157 "unreachable_count": unreachable, 158 # Currently not supported 159 "outdated_agent_count": 0, 160 } 161 return Response(data)
Mixin to add a used_by endpoint to return a list of all objects using this object
128 def get_serializer_class(self): 129 if self.action == "retrieve": 130 return EndpointDeviceDetailsSerializer 131 return super().get_serializer_class()
Return the class to use for the serializer.
Defaults to using self.serializer_class.
You may want to override this if you need to provide different serializations depending on the incoming request.
(Eg. admins get full serialization, others get basic serialization)
133 def get_queryset(self): 134 if self.action == "retrieve": 135 return super().get_queryset().prefetch_related("connections") 136 return super().get_queryset()
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)
138 @extend_schema(responses={200: DeviceSummarySerializer()}) 139 @action(methods=["GET"], detail=False) 140 def summary(self, request: Request) -> Response: 141 delta = now() - timedelta(hours=24) 142 unreachable = ( 143 Device.objects.all() 144 .annotate( 145 latest_snapshot=Subquery( 146 DeviceFactSnapshot.objects.filter(connection__device=OuterRef("pk")) 147 .order_by("-created") 148 .values("created")[:1] 149 ) 150 ) 151 .filter(latest_snapshot__lte=delta) 152 .distinct() 153 .count() 154 ) 155 data = { 156 "total_count": Device.objects.all().count(), 157 "unreachable_count": unreachable, 158 # Currently not supported 159 "outdated_agent_count": 0, 160 } 161 return Response(data)
Inherited Members
121 class DeviceSummarySerializer(PassiveSerializer): 122 """Summary of registered devices""" 123 124 total_count = IntegerField() 125 unreachable_count = IntegerField() 126 outdated_agent_count = IntegerField()
Summary of registered devices