diff --git a/netbox_sys_plugin/api/nested_serializers.py b/netbox_sys_plugin/api/nested_serializers.py index 1372abfd7aa799ad6828d0997e8bae78fff1eccb..de145313e2b6879a3030e9735d354cca96cb2765 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 7f746ddd679694db4ae33db6066263c61e3ad005..45d35f1a6eb694e3091034870c48feb2fe83e070 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 2766642dfb3c58eaa9a169a0abe01f200d5aed53..b6d7df961be9e650a4e68f4d9217b01bbeee36c5 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 3d9ed9f85c58df079701e9acca31992ecde95705..c407a5412339f914289540ea91610c1888bd2e4c 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 099a164c111bdd96408fcbe07060d16d0a5961a5..1d4c2096f1e5b369875e0bc3bb4a149cacb24c2b 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 826743dd3847f59817bd706dafd3062137db9224..aeb22610a8b261d8af679364ec731e65b7300cc5 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 40a70c49d5d0c40a6cf4866d318839d22fc90b24..0000000000000000000000000000000000000000 --- 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 0000000000000000000000000000000000000000..f729ae1ff0cf4b78871c3729f33cc71f217cbece --- /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 06126b78018d7e84d9a3b6ce3fb8f8a6656956f9..7b3a8cf3e830105c57807a17d8686991904f5c6d 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""" @@ -53,6 +22,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/navigation.py b/netbox_sys_plugin/navigation.py index 92c70c1e8fda21e625de13ab705f2289b9bd388a..52afac96fd77673f0cc74fc7e8511514d4be97dd 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 5d21779265fbc72d556c94735b9d2c38c165160c..939672af324db032035909229983b4d387b2389b 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( @@ -231,6 +199,10 @@ class WebhookPayloadTable(NetBoxTable): verbose_name="Payload Data", ) + actions = columns.ActionsColumn( + actions=("delete",), + ) + class Meta(NetBoxTable.Meta): """Meta class""" model = WebhookPayload 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 4d74ad1d20974edfe19b6f0a75f8fe37732e450a..0000000000000000000000000000000000000000 --- 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 17f7137cb983c48c2cf7d633ba88356f79be2ee0..8a0c2e0d70e9556cf6f7718867a04b26644ed88d 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 e69de29bb2d1d6434b8b29ae775ad8c2e48c5391..0000000000000000000000000000000000000000 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 5412fc728fe9232a75ce726249ff607f23d38477..0000000000000000000000000000000000000000 --- 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 21049522b1e9cd5ea7bbbef7296d6497d9c9874c..0000000000000000000000000000000000000000 --- 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 7c8ea9e1468ba00c49a3732d700f1295ca8e8602..4b754c8fdae54110ccf778e7e21f0c96ca417504 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 d87bbf374e279e0e976694d48a373f026ed90e7d..c5ef9917ef891752d6e88db9653db8558490b098 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 bbd8d28ced3b209f7905dd6e4a939769aaca6731..87a014127033229adf548dcb8c2b26b3980709da 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):