From 0674b521fa37a4ac9b2adb37125c54313c205590 Mon Sep 17 00:00:00 2001 From: Frederico Sequeira <frederico.sequeira@ext.ec.europa.eu> Date: Mon, 3 Feb 2025 11:32:21 +0000 Subject: [PATCH 1/2] =?UTF-8?q?=F0=9F=92=84=20Remove=20Edit=20button=20fro?= =?UTF-8?q?m=20payload=20list?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- netbox_sys_plugin/models/operation.py | 3 +++ netbox_sys_plugin/tables.py | 4 ++++ 2 files changed, 7 insertions(+) diff --git a/netbox_sys_plugin/models/operation.py b/netbox_sys_plugin/models/operation.py index 06126b7..74040e2 100644 --- a/netbox_sys_plugin/models/operation.py +++ b/netbox_sys_plugin/models/operation.py @@ -53,6 +53,9 @@ class WebhookPayload(NetBoxModel): verbose_name = "Webhook Payload" verbose_name_plural = "Webhook Payloads" + def __str__(self): + return f"Webhook Payload {self.pk}" + def get_absolute_url(self): """override""" return reverse("plugins:netbox_sys_plugin:webhookpayloads", args=[self.pk]) diff --git a/netbox_sys_plugin/tables.py b/netbox_sys_plugin/tables.py index 5d21779..f37c978 100644 --- a/netbox_sys_plugin/tables.py +++ b/netbox_sys_plugin/tables.py @@ -231,6 +231,10 @@ class WebhookPayloadTable(NetBoxTable): verbose_name="Payload Data", ) + actions = columns.ActionsColumn( + actions=("delete",), + ) + class Meta(NetBoxTable.Meta): """Meta class""" model = WebhookPayload -- GitLab From 58df49643813d425a896394de9c8095ad0f7edde Mon Sep 17 00:00:00 2001 From: Frederico Sequeira <frederico.sequeira@ext.ec.europa.eu> Date: Mon, 3 Feb 2025 14:18:23 +0000 Subject: [PATCH 2/2] =?UTF-8?q?=F0=9F=94=A5=20Remove=20webook=20settings?= =?UTF-8?q?=20code?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- netbox_sys_plugin/api/nested_serializers.py | 8 +- netbox_sys_plugin/api/serializers.py | 16 +- netbox_sys_plugin/api/urls.py | 1 - netbox_sys_plugin/api/views.py | 7 +- netbox_sys_plugin/forms/__init__.py | 1 - netbox_sys_plugin/forms/createvm.py | 2 - netbox_sys_plugin/forms/operation.py | 38 ---- .../migrations/0007_delete_webhooksettings.py | 16 ++ netbox_sys_plugin/models/operation.py | 31 --- netbox_sys_plugin/navigation.py | 5 - netbox_sys_plugin/tables.py | 34 +-- .../netbox_sys_plugin/webhooksettings.html | 27 --- netbox_sys_plugin/tests/test_init.py | 1 - .../tests/webhook_settings/__init__.py | 0 .../test_webhook_settings_api.py | 209 ------------------ .../test_webhook_settings_view.py | 110 --------- netbox_sys_plugin/urls.py | 10 - netbox_sys_plugin/utils.py | 33 --- netbox_sys_plugin/views.py | 26 --- 19 files changed, 20 insertions(+), 555 deletions(-) delete mode 100644 netbox_sys_plugin/forms/operation.py create mode 100644 netbox_sys_plugin/migrations/0007_delete_webhooksettings.py delete mode 100644 netbox_sys_plugin/templates/netbox_sys_plugin/webhooksettings.html delete mode 100644 netbox_sys_plugin/tests/webhook_settings/__init__.py delete mode 100644 netbox_sys_plugin/tests/webhook_settings/test_webhook_settings_api.py delete mode 100644 netbox_sys_plugin/tests/webhook_settings/test_webhook_settings_view.py diff --git a/netbox_sys_plugin/api/nested_serializers.py b/netbox_sys_plugin/api/nested_serializers.py index 1372abf..de14531 100644 --- a/netbox_sys_plugin/api/nested_serializers.py +++ b/netbox_sys_plugin/api/nested_serializers.py @@ -1,7 +1,7 @@ from drf_spectacular.utils import extend_schema_serializer from netbox.api.serializers import WritableNestedSerializer from virtualization.models import VirtualMachine, Cluster, ClusterType -from .. models import VirtualMachineMaintenance, ProviderCredentials,VmAssignedVirtualMachineType, VirtualMachineType, DomainNames, VmAssignedExtraConfig, WebhookSettings, ProviderTypeExtraConfig +from .. models import VirtualMachineMaintenance, ProviderCredentials,VmAssignedVirtualMachineType, VirtualMachineType, DomainNames, VmAssignedExtraConfig, ProviderTypeExtraConfig from rest_framework import serializers from netbox.api.serializers import WritableNestedSerializer @@ -18,7 +18,6 @@ __all__ = [ 'NestedTenantSerializer', 'NestedDomainNamesSerializer', 'NestedVmAssignedExtraConfigSerializer', - 'NestedWebhookSettingsSerializer', 'NestedProviderTypeExtraConfigSerializer', ] @@ -84,11 +83,6 @@ class NestedVmAssignedExtraConfigSerializer(WritableNestedSerializer): model = VmAssignedExtraConfig fields = ['id', 'extra_config_values', 'created', 'last_updated'] -class NestedWebhookSettingsSerializer(WritableNestedSerializer): - class Meta: - model = WebhookSettings - fields = '__all__' - class NestedProviderTypeExtraConfigSerializer(WritableNestedSerializer): class Meta: model = ProviderTypeExtraConfig diff --git a/netbox_sys_plugin/api/serializers.py b/netbox_sys_plugin/api/serializers.py index 7f746dd..45d35f1 100644 --- a/netbox_sys_plugin/api/serializers.py +++ b/netbox_sys_plugin/api/serializers.py @@ -7,7 +7,7 @@ from dcim.api.nested_serializers import ( from ipam.api.nested_serializers import ( NestedIPAddressSerializer, NestedServiceSerializer ) -from .. models import VirtualMachineMaintenance, ProviderCredentials,VmAssignedVirtualMachineType, VirtualMachineType,DomainNames, WebhookSettings,ProviderTypeExtraConfig,VmAssignedExtraConfig, WebhookPayload +from .. models import VirtualMachineMaintenance, ProviderCredentials,VmAssignedVirtualMachineType, VirtualMachineType,DomainNames, ProviderTypeExtraConfig,VmAssignedExtraConfig, WebhookPayload from django.contrib.contenttypes.models import ContentType from .nested_serializers import * from virtualization.choices import * @@ -199,19 +199,6 @@ class DomainNamesSerializer(NetBoxModelSerializer): validated_data["assigned_object_type"] = assigned_object_type return super().create(validated_data) -class WebhookSettingsSerializer(NetBoxModelSerializer): - id = serializers.IntegerField(read_only=True) - - class Meta: - model = WebhookSettings - fields = '__all__' - - def validate(self, data): - # Validate uniqueness - if not self.partial and WebhookSettings.objects.exists(): - raise serializers.ValidationError("You can only have one webbook setting.") - return data - class WebhookPayloadSerializer(NetBoxModelSerializer): id = serializers.IntegerField(read_only=True) payload_data = serializers.JSONField() @@ -317,7 +304,6 @@ class VirtualMachineSerializer(NetBoxModelSerializer): domain_names = serializers.SerializerMethodField() vm_assigned_extra_config = serializers.SerializerMethodField() - # webhook_settings = NestedWebhookSettingsSerializer(many=True, read_only=True) # provider_type_extra_config = serializers.SerializerMethodField() # Counter fields diff --git a/netbox_sys_plugin/api/urls.py b/netbox_sys_plugin/api/urls.py index 2766642..b6d7df9 100644 --- a/netbox_sys_plugin/api/urls.py +++ b/netbox_sys_plugin/api/urls.py @@ -7,7 +7,6 @@ router.register(r'ProviderCredentials', ProviderCredentialsViewSet) router.register(r'AssignedVmType', VmAssignedVirtualMachineTypeViewSet) router.register(r'VmType', VirtualMachineTypeViewSet) router.register(r'DomainNames', DomainNamesViewSet) -router.register(r'WebhookSettings', WebhookSettingsViewSet) router.register(r'WebhookPayload', WebhookPayloadViewSet) router.register(r'ProviderTypeExtraConfig', ProviderTypeExtraConfigViewSet) router.register(r'VirtualMachine', VirtualMachineViewSet, basename='virtualmachine') diff --git a/netbox_sys_plugin/api/views.py b/netbox_sys_plugin/api/views.py index 3d9ed9f..c407a54 100644 --- a/netbox_sys_plugin/api/views.py +++ b/netbox_sys_plugin/api/views.py @@ -5,7 +5,7 @@ from django.db.models import Prefetch from netbox.api.viewsets import NetBoxModelViewSet from virtualization import filtersets from .. filtersets import VmTypeFilterSet, ProviderTypeExtraConfigFilterSet -from .. models import VirtualMachineMaintenance, ProviderCredentials, VmAssignedVirtualMachineType, VirtualMachineType,DomainNames, WebhookSettings, ProviderTypeExtraConfig, WebhookPayload +from .. models import VirtualMachineMaintenance, ProviderCredentials, VmAssignedVirtualMachineType, VirtualMachineType,DomainNames, ProviderTypeExtraConfig, WebhookPayload from . serializers import * class VirtualMachineMaintenanceViewSet(viewsets.ModelViewSet): @@ -50,11 +50,6 @@ class VirtualMachineViewSet(NetBoxModelViewSet): serializer_class = VirtualMachineSerializer http_method_names = ["get"] -class WebhookSettingsViewSet(viewsets.ModelViewSet): - queryset = WebhookSettings.objects.all() - serializer_class = WebhookSettingsSerializer - http_method_names = ["get", "post", "patch", "delete", "options"] - class WebhookPayloadViewSet(viewsets.ModelViewSet): queryset = WebhookPayload.objects.all() serializer_class = WebhookPayloadSerializer diff --git a/netbox_sys_plugin/forms/__init__.py b/netbox_sys_plugin/forms/__init__.py index 099a164..1d4c209 100644 --- a/netbox_sys_plugin/forms/__init__.py +++ b/netbox_sys_plugin/forms/__init__.py @@ -3,4 +3,3 @@ from .provider import * from .machine import * from .createvm import * -from .operation import * diff --git a/netbox_sys_plugin/forms/createvm.py b/netbox_sys_plugin/forms/createvm.py index 826743d..aeb2261 100644 --- a/netbox_sys_plugin/forms/createvm.py +++ b/netbox_sys_plugin/forms/createvm.py @@ -649,8 +649,6 @@ class CreateVmForm(NetBoxModelForm): wb_payload.full_clean() wb_payload.save() CreateVmForm.assign_tags(wb_payload,data) - # Send webhook - #send_webhook(payload) return vm except ValueError as e: diff --git a/netbox_sys_plugin/forms/operation.py b/netbox_sys_plugin/forms/operation.py deleted file mode 100644 index 40a70c4..0000000 --- a/netbox_sys_plugin/forms/operation.py +++ /dev/null @@ -1,38 +0,0 @@ -"""Operational Forms definitions""" - -from django.core.exceptions import ValidationError -from netbox.forms import NetBoxModelForm, NetBoxModelFilterSetForm -from ..models import WebhookSettings - - - -class WebhookSettingsForm(NetBoxModelForm): - """Webhook Settings form definition class""" - - class Meta: - """Meta class""" - - model = WebhookSettings - fields = ('payload_url','http_content_type','tags') - labels = { - "payload_url": "Payload URL", - "http_content_type": "HTTP Content Type", - } - - def clean(self): - """Clean for Webhook Setting Form""" - cleaned_data = super().clean() - - if self.instance.pk: - return cleaned_data - - if WebhookSettings.objects.exists(): - raise ValidationError("You can only have one webbook setting") - - return None - - -class WebhookSettingsFilterForm(NetBoxModelFilterSetForm): - """Webhook Settings filter form definition class""" - - model = WebhookSettings diff --git a/netbox_sys_plugin/migrations/0007_delete_webhooksettings.py b/netbox_sys_plugin/migrations/0007_delete_webhooksettings.py new file mode 100644 index 0000000..f729ae1 --- /dev/null +++ b/netbox_sys_plugin/migrations/0007_delete_webhooksettings.py @@ -0,0 +1,16 @@ +# Generated by Django 4.2.16 on 2025-02-03 14:10 + +from django.db import migrations + + +class Migration(migrations.Migration): + + dependencies = [ + ('netbox_sys_plugin', '0006_webhookpayload'), + ] + + operations = [ + migrations.DeleteModel( + name='WebhookSettings', + ), + ] diff --git a/netbox_sys_plugin/models/operation.py b/netbox_sys_plugin/models/operation.py index 74040e2..7b3a8cf 100644 --- a/netbox_sys_plugin/models/operation.py +++ b/netbox_sys_plugin/models/operation.py @@ -3,39 +3,8 @@ from django.urls import reverse from django.db import models from django.utils.translation import gettext_lazy as _ -from django.core.validators import URLValidator from netbox.models import NetBoxModel - -class WebhookSettings(NetBoxModel): - """Webhook settings config definition class""" - - payload_url = models.CharField( - max_length=500, - verbose_name=_('URL'), - validators=[URLValidator(schemes=["http", "https"])], - help_text=_( - "This URL will be called using the HTTP POST when the webhook is called." - ) - ) - - http_content_type = models.CharField( - max_length=100, - default='application/json', - verbose_name=_('HTTP content type') - ) - - class Meta: - """Meta class""" - unique_together = ["payload_url"] - ordering = ["payload_url"] - verbose_name = "Webhook Settings" - verbose_name_plural = "Webhook Settings" - - def get_absolute_url(self): - """override""" - return reverse("plugins:netbox_sys_plugin:webhooksettings", args=[self.pk]) - class WebhookPayload(NetBoxModel): """Webhook Payload definition class""" diff --git a/netbox_sys_plugin/navigation.py b/netbox_sys_plugin/navigation.py index 92c70c1..52afac9 100644 --- a/netbox_sys_plugin/navigation.py +++ b/netbox_sys_plugin/navigation.py @@ -133,11 +133,6 @@ vmMachineItem = [ ] operItem =[ - PluginMenuItem( - link="plugins:netbox_sys_plugin:webhooksettings_list", - link_text="Webhook Settings", - permissions=["netbox_sys_plugin.list_webhooksettings"], - ), PluginMenuItem( link="plugins:netbox_sys_plugin:webhookpayloads_list", link_text="Webhook Payload", diff --git a/netbox_sys_plugin/tables.py b/netbox_sys_plugin/tables.py index f37c978..939672a 100644 --- a/netbox_sys_plugin/tables.py +++ b/netbox_sys_plugin/tables.py @@ -7,7 +7,6 @@ from .models import ( ProviderCredentials, VmAssignedVirtualMachineType, VirtualMachineType, - WebhookSettings, WebhookPayload, DomainNames, ProviderTypeExtraConfig, @@ -186,40 +185,9 @@ class DomainNamesTable(NetBoxTable): default_columns = ('id','domain_names','assigned_object') -#WebhookSettings -class WebhookSettingsTable(NetBoxTable): - """webhook Settings Table definition class""" - - pk = columns.ToggleColumn() - id = tables.Column( - linkify=True, - ) - - payload_url = tables.Column( - linkify=True, - verbose_name="Payload Url", - ) - - http_content_type = tables.Column( - linkify=True, - verbose_name="Http Content Type", - ) - - class Meta(NetBoxTable.Meta): - """Meta class""" - model = WebhookSettings - fields = ( - "pk", - "id", - "payload_url", - "http_content_type", - ) - - default_columns = ('id','payload_url','http_content_type') - #WebhookPayload class WebhookPayloadTable(NetBoxTable): - """webhook Settings Table definition class""" + """webhook Payload Table definition class""" pk = columns.ToggleColumn() id = tables.Column( diff --git a/netbox_sys_plugin/templates/netbox_sys_plugin/webhooksettings.html b/netbox_sys_plugin/templates/netbox_sys_plugin/webhooksettings.html deleted file mode 100644 index 4d74ad1..0000000 --- a/netbox_sys_plugin/templates/netbox_sys_plugin/webhooksettings.html +++ /dev/null @@ -1,27 +0,0 @@ -{% extends 'generic/object.html' %} -{% block title%} -Webhook for Create VM Form -{% endblock title%} -{% block content %} -<div class="row mb-3"> - <div class="col col-md-12"> - <div class="card"> - <h5 class="card-header">Webhook Information</h5> - <div class="card-body"> - <table class="table table-hover attr-table"> - <tr> - <th scope="row">Payload URL</th> - <td>{{ object.payload_url }}</td> - </tr> - <tr> - <th scope="row">HTTP Content Type</th> - <td>{{ object.http_content_type }}</td> - </tr> - </table> - </div> - </div> - {% include 'inc/panels/custom_fields.html' %} - {% include 'inc/panels/tags.html' %} - </div> -</div> -{% endblock content %} diff --git a/netbox_sys_plugin/tests/test_init.py b/netbox_sys_plugin/tests/test_init.py index 17f7137..8a0c2e0 100644 --- a/netbox_sys_plugin/tests/test_init.py +++ b/netbox_sys_plugin/tests/test_init.py @@ -20,7 +20,6 @@ class InitTestCase(APITestCase): self.assertTrue("VmType" in content) self.assertTrue("AssignedVmType" in content) self.assertTrue("DomainNames" in content) - self.assertTrue("WebhookSettings" in content) self.assertTrue("ProviderTypeExtraConfig" in content) self.assertTrue("VirtualMachine" in content) self.assertTrue("ExtraConfig" in content) diff --git a/netbox_sys_plugin/tests/webhook_settings/__init__.py b/netbox_sys_plugin/tests/webhook_settings/__init__.py deleted file mode 100644 index e69de29..0000000 diff --git a/netbox_sys_plugin/tests/webhook_settings/test_webhook_settings_api.py b/netbox_sys_plugin/tests/webhook_settings/test_webhook_settings_api.py deleted file mode 100644 index 5412fc7..0000000 --- a/netbox_sys_plugin/tests/webhook_settings/test_webhook_settings_api.py +++ /dev/null @@ -1,209 +0,0 @@ -"""SYS Plugin Webhook Settings API Test Case Class""" - -from users.models import ObjectPermission -from django.contrib.contenttypes.models import ContentType -from rest_framework import status -from netbox_sys_plugin.models import WebhookSettings -from ..base import BaseAPITestCase - -class WebhookSettingsApiTestCase(BaseAPITestCase): - """Test suite for WebhookSettings API""" - model = WebhookSettings - brief_fields = ["payload_url","http_content_type"] - - - @classmethod - def setUpTestData(cls): - - """Set up test data for WebhookSettings API""" - - # Data for valid creation - cls.valid_create_data = [ - { - "payload_url": "https://www.testAnother.com", - "http_content_type": "Test another http content type" - } - ] - - # Data for invalid creation - cls.invalid_create_data = [ - { - "payload_url": "Invalid URL", # Invalid URL - "http_content_type": "Test http content type" - }, - { - "payload_url": None, # Missing - "http_content_type": "Test structure" - - }, - { - "payload_url": "https://www.testAnother.com", - "http_content_type": None # Missing - }, - ] - - # Data for checking unique key - cls.valid_check_unique_data = [ - { - "payload_url": "https://www.test1.com", - "http_content_type": "Test http content type 1" - }, - { - "payload_url": "https://www.test2.com", - "http_content_type": "Test http content type 2" - } - ] - - def test_create_valid_webhook_settings(self): - """Test creating a valid webhook settings""" - - obj_perm = ObjectPermission( - name="Create Webhook Settings Permission", - actions=["add", "view"], - ) - obj_perm.save() - obj_perm.users.add(self.user) - obj_perm.object_types.add(ContentType.objects.get_for_model(WebhookSettings)) - - form_data = self.valid_create_data[0] - response = self.client.post(self._get_list_url(), form_data, format="json", **self.header) - - self.assertHttpStatus(response, status.HTTP_201_CREATED) - self.assertEqual(response.data["payload_url"], form_data["payload_url"]) - self.assertEqual(response.data["http_content_type"], form_data["http_content_type"]) - - def test_only_one_webhook_settings(self): - """Test the creation of 2 webhook settings""" - - # Create Webhook Settings - WebhookSettings.objects.create( - payload_url='https://www.test.com', - http_content_type='test http content type' - ) - - obj_perm = ObjectPermission( - name="Invalid Webhook Settings Permission", - actions=["add", "view"], - ) - obj_perm.save() - obj_perm.users.add(self.user) - obj_perm.object_types.add(ContentType.objects.get_for_model(WebhookSettings)) - - for form_data in self.valid_check_unique_data: - response = self.client.post(self._get_list_url(), form_data, format="json", **self.header) - self.assertHttpStatus(response, status.HTTP_400_BAD_REQUEST) - self.assertIn('You can only have one webbook setting',str(response.data)) - - def test_create_invalid_webhook_settings(self): - """Test creating invalid webhook settings""" - obj_perm = ObjectPermission( - name="Invalid Webhook Settings Permission", - actions=["add", "view"], - ) - obj_perm.save() - obj_perm.users.add(self.user) - obj_perm.object_types.add(ContentType.objects.get_for_model(WebhookSettings)) - - form_data = self.invalid_create_data[0] - response = self.client.post(self._get_list_url(), form_data, format="json", **self.header) - self.assertHttpStatus(response, status.HTTP_400_BAD_REQUEST) - self.assertIn('Enter a valid URL.',str(response.data)) - - form_data = self.invalid_create_data[1] - response = self.client.post(self._get_list_url(), form_data, format="json", **self.header) - self.assertHttpStatus(response, status.HTTP_400_BAD_REQUEST) - self.assertIn('This field may not be null.',str(response.data)) - - form_data = self.invalid_create_data[2] - response = self.client.post(self._get_list_url(), form_data, format="json", **self.header) - self.assertHttpStatus(response, status.HTTP_400_BAD_REQUEST) - self.assertIn('This field may not be null.',str(response.data)) - - def test_update_webhook_settings(self): - """Test updating an existing webhook settings""" - - # Create Webhook Settings - WebhookSettings.objects.create( - payload_url='https://www.test.com', - http_content_type='test http content type' - ) - - webhook_settings = WebhookSettings.objects.first() - obj_perm = ObjectPermission( - name="Update Webhook Settings Permission", - actions=["change", "view"], - ) - obj_perm.save() - obj_perm.users.add(self.user) - obj_perm.object_types.add(ContentType.objects.get_for_model(WebhookSettings)) - - update_data = {"payload_url": "https://www.testupdated.com"} - response = self.client.patch(self._get_detail_url(webhook_settings), update_data, format="json", **self.header) - self.assertHttpStatus(response, status.HTTP_200_OK) - self.assertEqual(response.data["payload_url"], update_data["payload_url"]) - - def test_get_webhook_settings_list(self): - """Test fetching webhook settings list""" - - # Create Webhook Settings - WebhookSettings.objects.create( - payload_url='https://www.test.com', - http_content_type='test http content type' - ) - - obj_perm = ObjectPermission( - name="Create Webhook Settings Permission", - actions=["view"], - ) - obj_perm.save() - obj_perm.users.add(self.user) - obj_perm.object_types.add(ContentType.objects.get_for_model(WebhookSettings)) - - response = self.client.get(self._get_list_url(), **self.header) - self.assertHttpStatus(response, status.HTTP_200_OK) - self.assertGreaterEqual(len(response.data), 2) - - def test_get_single_webhook_settings(self): - """Test fetching a single webhook settings""" - - # Create Webhook Settings - WebhookSettings.objects.create( - payload_url='https://www.test.com', - http_content_type='test http content type' - ) - - obj_perm = ObjectPermission( - name="View Webhook Settings Permission", - actions=["view"], - ) - obj_perm.save() - obj_perm.users.add(self.user) - obj_perm.object_types.add(ContentType.objects.get_for_model(WebhookSettings)) - - webhook_settings = WebhookSettings.objects.first() - response = self.client.get(self._get_detail_url(webhook_settings), **self.header) - self.assertHttpStatus(response, status.HTTP_200_OK) - self.assertEqual(response.data["payload_url"], webhook_settings.payload_url) - self.assertEqual(response.data["http_content_type"], webhook_settings.http_content_type) - - def test_delete_webhook_settings(self): - """Test deleting a webhook settings""" - - # Create Webhook Settings - WebhookSettings.objects.create( - payload_url='https://www.test.com', - http_content_type='test http content type' - ) - - webhook_settings = WebhookSettings.objects.first() - obj_perm = ObjectPermission( - name="Delete Webhook Settings Permission", - actions=["delete"], - ) - obj_perm.save() - obj_perm.users.add(self.user) - obj_perm.object_types.add(ContentType.objects.get_for_model(WebhookSettings)) - - response = self.client.delete(self._get_detail_url(webhook_settings), **self.header) - self.assertHttpStatus(response, status.HTTP_204_NO_CONTENT) - self.assertFalse(WebhookSettings.objects.filter(id=webhook_settings.id).exists()) diff --git a/netbox_sys_plugin/tests/webhook_settings/test_webhook_settings_view.py b/netbox_sys_plugin/tests/webhook_settings/test_webhook_settings_view.py deleted file mode 100644 index 2104952..0000000 --- a/netbox_sys_plugin/tests/webhook_settings/test_webhook_settings_view.py +++ /dev/null @@ -1,110 +0,0 @@ -"""Webhook Settings Test Case Class""" - -from django.contrib.contenttypes.models import ContentType -from users.models import ObjectPermission -from netbox_sys_plugin.models import WebhookSettings -from netbox_sys_plugin.forms import WebhookSettingsForm -from ..base import BaseModelViewTestCase - - -class WebhookSettingsFormTestCase( - BaseModelViewTestCase, -): - """Webhook Settings Test Case Class""" - - model = WebhookSettings - form = WebhookSettingsForm - - def test_create_valid_webhook_settings(self): - """Create a valid webhook settings""" - - form = WebhookSettingsForm(data= { - "payload_url": "https://www.test.com", - "http_content_type": "test http content type" - }) - self.assertTrue(form.is_valid()) - - # Setup object permissions for the test user - obj_perm = ObjectPermission( - name='Test permission', - actions=['add', 'change'] - ) - obj_perm.save() - obj_perm.users.add(self.user) # pylint: disable=no-member - obj_perm.object_types.add(ContentType.objects.get_for_model(self.model)) # pylint: disable=no-member - - def test_invalid_webhook_settings_format(self): - """ - Test invalid webhook settings invalid format. - """ - - # pylint: disable=W0201 - # Set up valid form data - self.invalid_valid_form_data = { - "payload_url": "https://www.test.com", - "http_content_type": "test http content type" - } - - #Invalid payload url - invalid_form_data = self.invalid_valid_form_data.copy() - invalid_form_data["payload_url"] = "Invalid" # Invalid format - form = self.form(data=invalid_form_data) - self.assertFalse(form.is_valid()) - self.assertIn( - "Enter a valid URL.", - form.errors.get("payload_url", []), - ) - - #Missing payload url - invalid_form_data = self.invalid_valid_form_data.copy() - invalid_form_data["payload_url"] = None # Invalid format - form = self.form(data=invalid_form_data) - self.assertFalse(form.is_valid()) - self.assertIn( - "This field is required.", - form.errors.get("payload_url", []), - ) - - #Missing http content type - invalid_form_data = self.invalid_valid_form_data.copy() - invalid_form_data["http_content_type"] = None # Invalid format - form = self.form(data=invalid_form_data) - self.assertFalse(form.is_valid()) - self.assertIn( - "This field is required.", - form.errors.get("http_content_type", []), - ) - - def test_only_one_webhook_settings(self): - """Test the creation of 2 webhook settings""" - - # pylint: disable=W0201 - self.webhookSettings = WebhookSettings.objects.create( - payload_url='https://www.test.com', - http_content_type='test http content type') - - form = WebhookSettingsForm(data= { - "payload_url": "https://www.test2.com", - "http_content_type": "test http content type 2" - }) - - self.assertFalse(form.is_valid()) - # Setup object permissions for the test user - obj_perm = ObjectPermission( - name='Test permission', - actions=['add', 'change'] - ) - obj_perm.save() - obj_perm.users.add(self.user) # pylint: disable=no-member - obj_perm.object_types.add(ContentType.objects.get_for_model(self.model)) # pylint: disable=no-member - - self.assertIn( - "You can only have one webbook setting", - form.errors.get("__all__",[]) - ) - - - def tearDown(self) -> None:# pylint: disable=invalid-name - """Method called immediately after the test method has been called and the result recorded.""" - WebhookSettings.objects.all().delete() - super().tearDown() diff --git a/netbox_sys_plugin/urls.py b/netbox_sys_plugin/urls.py index 7c8ea9e..4b754c8 100644 --- a/netbox_sys_plugin/urls.py +++ b/netbox_sys_plugin/urls.py @@ -58,16 +58,6 @@ urlpatterns = ( 'model': models.DomainNames}), #CreateVM path('create-vm/', CreateVmView.as_view(), name='creatvm_add'), - #WebhookSettings - path('webhook-settings/<int:pk>/', views.WebhookSettingsView.as_view(), name='webhooksettings'), - path('webhook-settings/', views.WebhookSettingsListView.as_view(), name='webhooksettings_list'), - path('webhook-settings/add/', views.WebhookSettingsEditView.as_view(), name='webhooksettings_add'), - path('webhook-settings/<int:pk>/edit/', views.WebhookSettingsEditView.as_view(), name='webhooksettings_edit'), - path('webhook-settings/<int:pk>/delete/', views.WebhookSettingsDeleteView.as_view(), name='webhooksettings_delete'), - path('webhook-settings/<int:pk>/changelog/', ObjectChangeLogView.as_view(), name='webhooksettings_changelog', kwargs={ - 'model': models.WebhookSettings}), - path('webhook-settings/<int:pk>/journal/', ObjectJournalView.as_view(), name='webhooksettings_journal', kwargs={ - 'model': models.WebhookSettings}), #WebhookPayload path('webhook-payload/<int:pk>/', views.WebhookPayloadView.as_view(), name='webhookpayload'), path('webhook-payload/', views.WebhookPayloadListView.as_view(), name='webhookpayloads_list'), diff --git a/netbox_sys_plugin/utils.py b/netbox_sys_plugin/utils.py index d87bbf3..c5ef991 100644 --- a/netbox_sys_plugin/utils.py +++ b/netbox_sys_plugin/utils.py @@ -1,38 +1,5 @@ """Utils definition""" -import requests -from .models import WebhookSettings - -def get_webhook_settings(): - """Get webhook user defined settings""" - try: - webhook_settings = WebhookSettings.objects.first() - if not webhook_settings: - raise ValueError("No webhook configured") - - return { - "url":webhook_settings.payload_url, - "content_type":webhook_settings.http_content_type - } - #pylint: disable=W0718 - except Exception as e: - print(f"Error Fetching webhook settings: {e}") - return None - -def send_webhook(payload): - """Send a webhook to the specified endpoint.""" - settings = get_webhook_settings() - if not settings: - print("Cannot send webhook, missing configurations") - return - try: - headers = {'Content-Type': settings['content_type']} - response = requests.post(settings['url'], json=payload, headers=headers,timeout=60) - response.raise_for_status() - print(f"Webhook sent successfully: {response.status_code}") - except requests.RequestException as e: - print(f"Error sending webhook: {e}") - def validate_extra_config_values(structure, values): """Validates the user-provided `extra_config_values` against the `extra_config_structure`.""" errors = [] diff --git a/netbox_sys_plugin/views.py b/netbox_sys_plugin/views.py index bbd8d28..87a0141 100644 --- a/netbox_sys_plugin/views.py +++ b/netbox_sys_plugin/views.py @@ -179,32 +179,6 @@ class DomainNamesDeleteView(generic.ObjectDeleteView): queryset = models.DomainNames.objects.all() -#Webhook Settings -class WebhookSettingsView(generic.ObjectView): - - """ Webhook Settings view definition""" - - queryset = ( - models.WebhookSettings.objects.all() - ) - -class WebhookSettingsListView(generic.ObjectListView): - """Webhook Settings list view definition""" - - queryset = models.WebhookSettings.objects.all() - table = tables.WebhookSettingsTable - -class WebhookSettingsEditView(generic.ObjectEditView): - """ - Defines the edit view for the Webhook Settings django model. - """ - queryset = models.WebhookSettings.objects.all() - form = forms.WebhookSettingsForm - -class WebhookSettingsDeleteView(generic.ObjectDeleteView): - """Webhook Settings Delete delete view definition""" - queryset = models.WebhookSettings.objects.all() - #Webhook Payload class WebhookPayloadView(generic.ObjectView): -- GitLab