Skip to content

Commit 5508809

Browse files
committed
[fix] Prevent command creation for devices without a DeviceConnection #1016
Added a check before creation to ensure device has credentials via 'DeviceConnection'. To ensure only relevant connection and command types are displayed modified their queryset in serializer's 'init'. Closes #1016 Signed-off-by: DragnEmperor <dragnemperor@gmail.com>
1 parent e1d4e69 commit 5508809

2 files changed

Lines changed: 20 additions & 0 deletions

File tree

openwisp_controller/connection/api/serializers.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,21 @@ class CommandSerializer(ValidatedDeviceFieldSerializer):
3131
pk_field=serializers.UUIDField(format='hex_verbose'),
3232
)
3333

34+
def __init__(self, *args, **kwargs):
35+
super().__init__(*args, **kwargs)
36+
# show only connections and command types available for the device
37+
if (
38+
device := Device.objects.filter(pk=self.context.get('device_id'))
39+
.only('organization_id', 'id')
40+
.first()
41+
):
42+
self.fields['connection'].queryset = DeviceConnection.objects.filter(
43+
device=device
44+
)
45+
self.fields['type'].choices = Command.get_org_choices(
46+
device.organization_id
47+
)
48+
3449
def to_representation(self, instance):
3550
repr = super().to_representation(instance)
3651
repr['type'] = instance.get_type_display()

openwisp_controller/connection/api/views.py

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,11 @@ class CommandListCreateView(BaseCommandView, ListCreateAPIView):
6666

6767
def create(self, request, *args, **kwargs):
6868
self.assert_parent_exists()
69+
if not DeviceConnection.objects.filter(
70+
device_id=self.kwargs['device_pk'],
71+
credentials__isnull=False,
72+
).exists():
73+
raise NotFound(detail='Device has no credentials assigned.')
6974
return super().create(request, *args, **kwargs)
7075

7176

0 commit comments

Comments
 (0)