From 02d965a77b14ba9d15f5caf9a127425a4ddb059f Mon Sep 17 00:00:00 2001 From: Louis Date: Wed, 21 Oct 2026 14:02:53 +0200 Subject: [PATCH] feat: add certificate management with expiration reminders Add a Certificate model alongside software licenses with type, common name, SANs, issuer, serial number, fingerprint, validity period, auto renewal, certificate file and storage locations. Certificates can be assigned to software products, installations, devices, virtual machines and tenants. Extract the expiration reminder settings and logic into a shared ExpirationNotificationModel base and a generic notification job, so certificates get the same default/custom reminders, NetBox notifications and optional SMTP emails as licenses (separate event type, log model and email permission). Includes UI views, filters, table, bulk import/edit, REST API endpoint, migration 0015, German translations, tests and README/CHANGELOG updates. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 3 + README.md | 59 +++- netbox_slm/__init__.py | 5 +- netbox_slm/api/serializers.py | 96 +++++- netbox_slm/api/urls.py | 2 + netbox_slm/api/views.py | 9 + netbox_slm/events.py | 1 + netbox_slm/filtersets.py | 50 ++- netbox_slm/forms/__init__.py | 6 + netbox_slm/forms/certificate.py | 301 ++++++++++++++++++ netbox_slm/jobs.py | 145 ++++++--- netbox_slm/locale/de/LC_MESSAGES/django.mo | Bin 8583 -> 11097 bytes netbox_slm/locale/de/LC_MESSAGES/django.po | 129 ++++++++ netbox_slm/migrations/0015_certificate.py | 181 +++++++++++ netbox_slm/models.py | 247 +++++++++++--- netbox_slm/navigation.py | 19 ++ netbox_slm/tables.py | 70 +++- .../templates/netbox_slm/certificate.html | 187 +++++++++++ netbox_slm/tests/test_models.py | 74 ++++- netbox_slm/urls.py | 2 + netbox_slm/views/__init__.py | 8 + netbox_slm/views/certificate.py | 55 ++++ 22 files changed, 1547 insertions(+), 102 deletions(-) create mode 100644 netbox_slm/forms/certificate.py create mode 100644 netbox_slm/migrations/0015_certificate.py create mode 100644 netbox_slm/templates/netbox_slm/certificate.html create mode 100644 netbox_slm/views/certificate.py diff --git a/CHANGELOG.md b/CHANGELOG.md index ae02240..9f464b0 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,9 @@ ### Added +* Certificate management with type, common name, SANs, issuer, serial number, fingerprint and validity period +* Optional certificate assignment to software products, installations, devices, virtual machines and tenants +* Daily certificate expiration notifications with the same reminder and email options as licenses * Optional tenant group and tenant assignments for software licenses * German translation for navigation, forms, tables, detail views, choices, and validation messages * Optional lifetime or recurring renewal interval for licenses diff --git a/README.md b/README.md index d2dba84..d9229f3 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,7 @@ # NetBox SLM -NetBox SLM erweitert NetBox um die Verwaltung von Softwareprodukten, Versionen, Installationen und Lizenzen. +NetBox SLM erweitert NetBox um die Verwaltung von Softwareprodukten, Versionen, Installationen, Lizenzen und +Zertifikaten. Lizenzen können optional einer NetBox-Mandantengruppe und einem Mandanten zugeordnet werden. Diese Variante ist für **NetBox 4.6.5** vorgesehen. @@ -20,6 +21,9 @@ Benutzer ausgewählten Sprache. - Zusätzliche eigene Vorwarnzeit in Tagen, Wochen oder Monaten - NetBox-Benachrichtigungen und optionaler E-Mail-Versand über die NetBox-SMTP-Konfiguration - Lizenzen Mandantengruppen und Mandanten zuordnen +- Zertifikate mit Common Name, SANs, Aussteller, Seriennummer, Fingerabdruck und Gültigkeitszeitraum verwalten +- Zertifikate Softwareprodukten, Installationen, Geräten, virtuellen Maschinen und Mandanten zuordnen +- Zertifikatsdateien und Ablageorte hinterlegen (keine privaten Schlüssel) - Bedienung über die NetBox-Oberfläche und REST-API - Filter, Bulk-Import und Bulk-Bearbeitung @@ -70,7 +74,8 @@ Für diese Variante muss dort mindestens Version `1.12.0` stehen. ## Ablaufbenachrichtigungen -Für Lizenzen mit Ablaufdatum sind Benachrichtigungen standardmäßig aktiviert. Die Standardtermine liegen einen +Für Lizenzen und Zertifikate mit Ablaufdatum sind Benachrichtigungen standardmäßig aktiviert. Beide Objekttypen +verwenden dieselben Einstellungen; die folgenden Abschnitte gelten daher für Zertifikate entsprechend. Die Standardtermine liegen einen Monat und eine Woche vor dem Ablaufdatum. Pro Lizenz kann zusätzlich eine eigene Vorwarnzeit festgelegt oder die Standardtermine deaktiviert werden. @@ -83,10 +88,11 @@ das Plugin auch eine E-Mail an die im Benutzerkonto hinterlegte Adresse. Dafür konfiguriert sein. Die Aktivierung des E-Mail-Versands darf nur durch Administratoren oder Benutzer mit der Berechtigung -`netbox_slm.manage_softwarelicense_email_notifications` geändert werden. Die eigentlichen SMTP-Zugangsdaten werden +`netbox_slm.manage_softwarelicense_email_notifications` (Lizenzen) bzw. +`netbox_slm.manage_certificate_email_notifications` (Zertifikate) geändert werden. Die eigentlichen SMTP-Zugangsdaten werden ausschließlich in der NetBox-Serverkonfiguration gepflegt und sind im Plugin nicht einsehbar. -Die Prüfung läuft einmal täglich als NetBox-Systemjob. Sobald der erste konfigurierte Erinnerungstermin erreicht ist, +Die Prüfung läuft einmal täglich als NetBox-Systemjob (je ein Job für Lizenzen und Zertifikate). Sobald der erste konfigurierte Erinnerungstermin erreicht ist, werden die Abonnenten bei jedem Joblauf erneut informiert: immer über NetBox und bei aktivierter E-Mail-Option zusätzlich per SMTP. Dies wird bis einschließlich des Ablaufdatums wiederholt. Der NetBox-RQ-Worker muss dafür mit Scheduler-Unterstützung laufen; dies ist bei der regulären NetBox-Installation mit `rqworker` standardmäßig der Fall. @@ -158,3 +164,48 @@ Die Anpassungen in diesem Fork werden unter Das Projekt steht unter der [Apache License 2.0](LICENSE). Die Hinweise auf die ursprünglichen Urheber bleiben erhalten. + +## Certificates (English) + +In addition to software licenses, NetBox SLM manages certificates (menu **Licences → Certificates**). + +### Fields + +- Name, description and type (TLS server, TLS client, certificate authority, code signing, S/MIME email, other) +- Common name, subject alternative names (one DNS name or IP address per line), issuer, serial number and SHA-256 + fingerprint +- Validity period (valid from / valid until) and an automatic renewal flag +- Certificate file, stored location (with optional URL) and provider portal URL +- Optional assignment to a software product, installation, device, virtual machine, tenant group and tenant + +> **Note:** Private keys are intentionally not stored. Keep them in a dedicated secret store and reference that +> location through the stored location fields if needed. + +### Expiration notifications + +Certificates use the same reminder settings as licenses: + +- Reminders are enabled by default one month and one week before the expiration date. +- An additional custom interval in days, weeks or months can be configured, and the default intervals can be disabled. +- Users opt in by opening a certificate and choosing **Subscribe**. Without subscribers no message is sent. +- A NetBox notification is always created. If **Email notifications** is enabled on the certificate, an email is sent + as well via the SMTP settings configured in NetBox. +- Changing the email option requires the permission `netbox_slm.manage_certificate_email_notifications` + (licenses use `netbox_slm.manage_softwarelicense_email_notifications`). +- The check runs once a day as the NetBox system job **Certificate Expiration Notifications**. Once the first reminder + date is reached, subscribers are notified on every run up to and including the expiration date. + +### REST API + +Certificates are available at `/api/plugins/slm/certificates/` and support filtering, e.g. by `type`, `common_name`, +`issuer`, `device_id`, `virtualmachine_id`, `tenant_id`, `expiration_date__lte` and `expiration_date__gte`. + +### Upgrading + +The feature adds the migration `0015_certificate`. After upgrading the plugin run: + +```bash +cd /opt/netbox/netbox +/opt/netbox/venv/bin/python manage.py migrate +sudo systemctl restart netbox netbox-rq +``` diff --git a/netbox_slm/__init__.py b/netbox_slm/__init__.py index 2033879..4c9c66d 100644 --- a/netbox_slm/__init__.py +++ b/netbox_slm/__init__.py @@ -17,7 +17,7 @@ limitations under the License. from netbox.plugins import PluginConfig from django.utils.translation import gettext, gettext_lazy as _ -__version__ = "1.13.0" +__version__ = "1.14.0" class SLMConfig(PluginConfig): @@ -40,9 +40,10 @@ class SLMConfig(PluginConfig): super().ready() from netbox.events import EVENT_TYPE_KIND_WARNING, EventType - from netbox_slm.events import LICENSE_EXPIRING + from netbox_slm.events import CERTIFICATE_EXPIRING, LICENSE_EXPIRING EventType(LICENSE_EXPIRING, gettext("License expiring"), kind=EVENT_TYPE_KIND_WARNING).register() + EventType(CERTIFICATE_EXPIRING, gettext("Certificate expiring"), kind=EVENT_TYPE_KIND_WARNING).register() from netbox_slm import jobs # noqa: F401 diff --git a/netbox_slm/api/serializers.py b/netbox_slm/api/serializers.py index 5ef5a6b..6becda4 100644 --- a/netbox_slm/api/serializers.py +++ b/netbox_slm/api/serializers.py @@ -3,7 +3,13 @@ from rest_framework.serializers import SerializerMethodField, HyperlinkedIdentit from django.utils.translation import gettext_lazy as _ from netbox.api.serializers import NetBoxModelSerializer -from netbox_slm.models import SoftwareProduct, SoftwareProductVersion, SoftwareProductInstallation, SoftwareLicense +from netbox_slm.models import ( + Certificate, + SoftwareProduct, + SoftwareProductVersion, + SoftwareProductInstallation, + SoftwareLicense, +) class SoftwareLicenseSerializer(NetBoxModelSerializer): @@ -185,3 +191,91 @@ class SoftwareProductVersionSerializer(NetBoxModelSerializer): def get_display(self, obj): return f"{obj}" + + +class CertificateSerializer(NetBoxModelSerializer): + display = SerializerMethodField() + url = HyperlinkedIdentityField(view_name="plugins-api:netbox_slm-api:certificate-detail") + + class Meta: + model = Certificate + fields = ( + "id", + "display", + "url", + "name", + "description", + "type", + "common_name", + "subject_alternative_names", + "issuer", + "serial_number", + "fingerprint", + "start_date", + "expiration_date", + "auto_renewal", + "certificate_file", + "stored_location", + "stored_location_url", + "provider_portal_url", + "expiration_notifications_enabled", + "default_notification_intervals", + "custom_notification_interval", + "custom_notification_interval_unit", + "email_notifications", + "software_product", + "installation", + "device", + "virtualmachine", + "tenant_group", + "tenant", + "tags", + "comments", + "custom_field_data", + "created", + "last_updated", + ) + brief_fields = ("id", "display", "url", "name", "description", "expiration_date") + + def get_display(self, obj): + return f"{obj}" + + def validate(self, attrs): + request = self.context.get("request") + if ( + "email_notifications" in attrs + and request is not None + and not request.user.has_perm("netbox_slm.manage_certificate_email_notifications") + ): + raise serializers.ValidationError( + {"email_notifications": _("You do not have permission to change email notifications.")} + ) + + tenant_group = attrs.get("tenant_group", getattr(self.instance, "tenant_group", None)) + tenant = attrs.get("tenant", getattr(self.instance, "tenant", None)) + if tenant_group and tenant and tenant.group_id != tenant_group.pk: + raise serializers.ValidationError( + {"tenant": _("The selected tenant does not belong to the selected tenant group.")} + ) + start_date = attrs.get("start_date", getattr(self.instance, "start_date", None)) + expiration_date = attrs.get("expiration_date", getattr(self.instance, "expiration_date", None)) + if start_date and expiration_date and start_date > expiration_date: + raise serializers.ValidationError( + {"expiration_date": _("The expiration date must not be before the start date.")} + ) + custom_interval = attrs.get( + "custom_notification_interval", getattr(self.instance, "custom_notification_interval", None) + ) + custom_interval_unit = attrs.get( + "custom_notification_interval_unit", + getattr(self.instance, "custom_notification_interval_unit", ""), + ) + if bool(custom_interval) != bool(custom_interval_unit): + raise serializers.ValidationError( + { + "custom_notification_interval": _( + "Custom notification interval and unit must be specified together." + ) + } + ) + return attrs diff --git a/netbox_slm/api/urls.py b/netbox_slm/api/urls.py index 270e5d3..42fd788 100644 --- a/netbox_slm/api/urls.py +++ b/netbox_slm/api/urls.py @@ -5,6 +5,7 @@ from netbox_slm.api.views import ( SoftwareProductVersionViewSet, SoftwareProductInstallationViewSet, SoftwareLicenseViewSet, + CertificateViewSet, ) router = NetBoxRouter() @@ -14,5 +15,6 @@ router.register("softwareproducts", SoftwareProductViewSet) router.register("softwareproductversions", SoftwareProductVersionViewSet) router.register("softwareproductinstallations", SoftwareProductInstallationViewSet) router.register("softwarelicenses", SoftwareLicenseViewSet) +router.register("certificates", CertificateViewSet) urlpatterns = router.urls diff --git a/netbox_slm/api/views.py b/netbox_slm/api/views.py index e489b59..14b6e64 100644 --- a/netbox_slm/api/views.py +++ b/netbox_slm/api/views.py @@ -6,18 +6,21 @@ from netbox_slm.api.serializers import ( SoftwareProductVersionSerializer, SoftwareProductInstallationSerializer, SoftwareLicenseSerializer, + CertificateSerializer, ) from netbox_slm.filtersets import ( SoftwareProductFilterSet, SoftwareProductVersionFilterSet, SoftwareProductInstallationFilterSet, SoftwareLicenseFilterSet, + CertificateFilterSet, ) from netbox_slm.models import ( SoftwareProduct, SoftwareProductVersion, SoftwareProductInstallation, SoftwareLicense, + Certificate, ) @@ -48,3 +51,9 @@ class SoftwareLicenseViewSet(NetBoxModelViewSet): queryset = SoftwareLicense.objects.all().order_by("id") serializer_class = SoftwareLicenseSerializer filterset_class = SoftwareLicenseFilterSet + + +class CertificateViewSet(NetBoxModelViewSet): + queryset = Certificate.objects.all().order_by("id") + serializer_class = CertificateSerializer + filterset_class = CertificateFilterSet diff --git a/netbox_slm/events.py b/netbox_slm/events.py index a0886e9..c3d0993 100644 --- a/netbox_slm/events.py +++ b/netbox_slm/events.py @@ -1 +1,2 @@ LICENSE_EXPIRING = "netbox_slm_license_expiring" +CERTIFICATE_EXPIRING = "netbox_slm_certificate_expiring" diff --git a/netbox_slm/filtersets.py b/netbox_slm/filtersets.py index e9d7038..9d818cc 100644 --- a/netbox_slm/filtersets.py +++ b/netbox_slm/filtersets.py @@ -1,6 +1,6 @@ from django.db.models import Q from django.utils.translation import gettext_lazy as _ -from django_filters import CharFilter, ModelMultipleChoiceFilter, MultipleChoiceFilter, NumberFilter +from django_filters import CharFilter, DateFilter, ModelMultipleChoiceFilter, MultipleChoiceFilter, NumberFilter from dcim.models import Device, Manufacturer from netbox.filtersets import NetBoxModelFilterSet @@ -10,6 +10,8 @@ from netbox_slm.models import ( SoftwareProductInstallation, SoftwareLicense, SoftwareReleaseTypes, + Certificate, + CertificateTypes, RenewalIntervalUnits, ) from virtualization.models import Cluster, VirtualMachine @@ -151,3 +153,49 @@ class SoftwareLicenseFilterSet(NetBoxModelFilterSet): | Q(comments__icontains=value) ) return queryset.filter(qs_filter) + + +class CertificateFilterSet(NetBoxModelFilterSet): + """Filter capabilities for Certificate instances.""" + + name = CharFilter(lookup_expr="icontains") + description = CharFilter(lookup_expr="icontains") + type = MultipleChoiceFilter(choices=CertificateTypes.choices) + common_name = CharFilter(lookup_expr="icontains") + issuer = CharFilter(lookup_expr="icontains") + serial_number = CharFilter(lookup_expr="icontains") + expiration_date__lte = DateFilter(field_name="expiration_date", lookup_expr="lte") + expiration_date__gte = DateFilter(field_name="expiration_date", lookup_expr="gte") + + software_product_id = ModelMultipleChoiceFilter( + queryset=SoftwareProduct.objects.all(), + label=_("Software Product"), + ) + installation_id = ModelMultipleChoiceFilter(queryset=SoftwareProductInstallation.objects.all()) + device_id = ModelMultipleChoiceFilter(queryset=Device.objects.all()) + virtualmachine_id = ModelMultipleChoiceFilter(queryset=VirtualMachine.objects.all(), label=_("Virtual Machine")) + tenant_group_id = ModelMultipleChoiceFilter(queryset=TenantGroup.objects.all(), label=_("Tenant Group")) + tenant_id = ModelMultipleChoiceFilter(queryset=Tenant.objects.all(), label=_("Tenant")) + + class Meta: + model = Certificate + fields = ("auto_renewal", "expiration_notifications_enabled", "email_notifications") + + def search(self, queryset, name, value): + """Perform the filtered search.""" + if not value.strip(): + return queryset + qs_filter = ( + Q(name__icontains=value) + | Q(description__icontains=value) + | Q(common_name__icontains=value) + | Q(subject_alternative_names__icontains=value) + | Q(issuer__icontains=value) + | Q(serial_number__icontains=value) + | Q(fingerprint__icontains=value) + | Q(device__name__icontains=value) + | Q(virtualmachine__name__icontains=value) + | Q(tenant__name__icontains=value) + | Q(comments__icontains=value) + ) + return queryset.filter(qs_filter) diff --git a/netbox_slm/forms/__init__.py b/netbox_slm/forms/__init__.py index a8ddb1d..33d025e 100644 --- a/netbox_slm/forms/__init__.py +++ b/netbox_slm/forms/__init__.py @@ -22,3 +22,9 @@ from .software_product_version import ( SoftwareProductVersionBulkImportForm, SoftwareProductVersionBulkEditForm, ) +from .certificate import ( + CertificateForm, + CertificateFilterForm, + CertificateBulkImportForm, + CertificateBulkEditForm, +) diff --git a/netbox_slm/forms/certificate.py b/netbox_slm/forms/certificate.py new file mode 100644 index 0000000..b7969d2 --- /dev/null +++ b/netbox_slm/forms/certificate.py @@ -0,0 +1,301 @@ +from django.forms import CharField, ChoiceField, DateField, IntegerField, MultipleChoiceField, Textarea +from django.utils.translation import gettext_lazy as _ + +from dcim.models import Device +from netbox.forms import NetBoxModelForm, NetBoxModelFilterSetForm, NetBoxModelImportForm, NetBoxModelBulkEditForm +from netbox_slm.models import ( + Certificate, + CertificateTypes, + NotificationIntervalUnits, + SoftwareProduct, + SoftwareProductInstallation, +) +from tenancy.models import Tenant, TenantGroup +from utilities.forms import add_blank_choice +from utilities.forms.constants import BOOLEAN_WITH_BLANK_CHOICES +from utilities.forms.fields import ( + CommentField, + DynamicModelChoiceField, + DynamicModelMultipleChoiceField, + LaxURLField, + TagFilterField, +) +from utilities.forms.rendering import FieldSet +from utilities.forms.widgets import DatePicker +from virtualization.models import VirtualMachine + + +class CertificateForm(NetBoxModelForm): + comments = CommentField() + fieldsets = ( + FieldSet("name", "description", "type", name=_("Certificate")), + FieldSet("software_product", "installation", "device", "virtualmachine", name=_("Assignment")), + FieldSet("tenant_group", "tenant", name=_("Tenancy")), + FieldSet( + "common_name", + "subject_alternative_names", + "issuer", + "serial_number", + "fingerprint", + "start_date", + "expiration_date", + "auto_renewal", + name=_("Certificate Details"), + ), + FieldSet( + "certificate_file", + "stored_location", + "stored_location_url", + "provider_portal_url", + name=_("Storage"), + ), + FieldSet( + "expiration_notifications_enabled", + "default_notification_intervals", + "custom_notification_interval", + "custom_notification_interval_unit", + "email_notifications", + name=_("Expiration Notifications"), + ), + FieldSet("tags", name=_("Tags")), + ) + + subject_alternative_names = CharField( + required=False, + widget=Textarea(attrs={"rows": 3}), + label=_("Subject alternative names"), + help_text=_("One DNS name or IP address per line"), + ) + start_date = DateField(required=False, widget=DatePicker(), label=_("Valid from")) + expiration_date = DateField(required=False, widget=DatePicker(), label=_("Valid until")) + stored_location_url = LaxURLField(required=False, label=_("Stored location URL")) + provider_portal_url = LaxURLField(required=False, label=_("Provider portal URL")) + custom_notification_interval = IntegerField(required=False, min_value=1) + + software_product = DynamicModelChoiceField( + queryset=SoftwareProduct.objects.all(), + required=False, + label=_("Software Product"), + ) + installation = DynamicModelChoiceField( + queryset=SoftwareProductInstallation.objects.all(), + required=False, + query_params={"software_product_id": "$software_product"}, + label=_("Installation"), + ) + device = DynamicModelChoiceField(queryset=Device.objects.all(), required=False, label=_("Device")) + virtualmachine = DynamicModelChoiceField( + queryset=VirtualMachine.objects.all(), required=False, label=_("Virtual Machine") + ) + tenant_group = DynamicModelChoiceField( + queryset=TenantGroup.objects.all(), + required=False, + label=_("Tenant Group"), + ) + tenant = DynamicModelChoiceField( + queryset=Tenant.objects.all(), + required=False, + query_params={"group_id": "$tenant_group"}, + label=_("Tenant"), + ) + + class Meta: + model = Certificate + fields = ( + "name", + "description", + "type", + "common_name", + "subject_alternative_names", + "issuer", + "serial_number", + "fingerprint", + "start_date", + "expiration_date", + "auto_renewal", + "certificate_file", + "stored_location", + "stored_location_url", + "provider_portal_url", + "expiration_notifications_enabled", + "default_notification_intervals", + "custom_notification_interval", + "custom_notification_interval_unit", + "email_notifications", + "software_product", + "installation", + "device", + "virtualmachine", + "tenant_group", + "tenant", + "tags", + "comments", + ) + + +class CertificateFilterForm(NetBoxModelFilterSetForm): + model = Certificate + fieldsets = ( + FieldSet("q", "filter_id", "tag"), + FieldSet( + "name", + "type", + "common_name", + "issuer", + "serial_number", + "auto_renewal", + "expiration_notifications_enabled", + "email_notifications", + name=_("Attributes"), + ), + FieldSet( + "software_product_id", + "installation_id", + "device_id", + "virtualmachine_id", + "tenant_group_id", + "tenant_id", + name=_("Assignment"), + ), + ) + selector_fields = ("q", "filter_id", "name") + + tag = TagFilterField(model) + + name = CharField(required=False) + type = MultipleChoiceField(required=False, choices=CertificateTypes.choices) + common_name = CharField(required=False) + issuer = CharField(required=False) + serial_number = CharField(required=False) + auto_renewal = ChoiceField(required=False, choices=BOOLEAN_WITH_BLANK_CHOICES) + expiration_notifications_enabled = ChoiceField(required=False, choices=BOOLEAN_WITH_BLANK_CHOICES) + email_notifications = ChoiceField(required=False, choices=BOOLEAN_WITH_BLANK_CHOICES) + + software_product_id = DynamicModelMultipleChoiceField( + queryset=SoftwareProduct.objects.all(), required=False, label=_("Software Product") + ) + installation_id = DynamicModelMultipleChoiceField( + queryset=SoftwareProductInstallation.objects.all(), required=False, label=_("Installation") + ) + device_id = DynamicModelMultipleChoiceField(queryset=Device.objects.all(), required=False, label=_("Device")) + virtualmachine_id = DynamicModelMultipleChoiceField( + queryset=VirtualMachine.objects.all(), required=False, label=_("Virtual Machine") + ) + tenant_group_id = DynamicModelMultipleChoiceField( + queryset=TenantGroup.objects.all(), required=False, label=_("Tenant Group") + ) + tenant_id = DynamicModelMultipleChoiceField( + queryset=Tenant.objects.all(), + required=False, + query_params={"group_id": "$tenant_group_id"}, + label=_("Tenant"), + ) + + +class CertificateBulkImportForm(NetBoxModelImportForm): + class Meta: + model = Certificate + fields = ( + "name", + "description", + "type", + "common_name", + "subject_alternative_names", + "issuer", + "serial_number", + "fingerprint", + "start_date", + "expiration_date", + "auto_renewal", + "stored_location", + "stored_location_url", + "provider_portal_url", + "expiration_notifications_enabled", + "default_notification_intervals", + "custom_notification_interval", + "custom_notification_interval_unit", + "email_notifications", + "software_product", + "installation", + "device", + "virtualmachine", + "tenant_group", + "tenant", + "tags", + ) + + +class CertificateBulkEditForm(NetBoxModelBulkEditForm): + model = Certificate + fieldsets = ( + FieldSet( + "type", + "issuer", + "start_date", + "expiration_date", + "auto_renewal", + "stored_location", + "stored_location_url", + "provider_portal_url", + "expiration_notifications_enabled", + "default_notification_intervals", + "custom_notification_interval", + "custom_notification_interval_unit", + "email_notifications", + "software_product", + "device", + "virtualmachine", + "tenant_group", + "tenant", + ), + ) + nullable_fields = ( + "type", + "issuer", + "start_date", + "expiration_date", + "stored_location", + "stored_location_url", + "provider_portal_url", + "custom_notification_interval", + "custom_notification_interval_unit", + "software_product", + "device", + "virtualmachine", + "tenant_group", + "tenant", + ) + + tag = TagFilterField(model) + comments = CommentField() + + type = ChoiceField(required=False, choices=add_blank_choice(CertificateTypes.choices)) + issuer = CharField(required=False) + start_date = DateField(required=False, widget=DatePicker(), label=_("Valid from")) + expiration_date = DateField(required=False, widget=DatePicker(), label=_("Valid until")) + auto_renewal = ChoiceField(required=False, choices=BOOLEAN_WITH_BLANK_CHOICES) + stored_location = CharField(required=False) + stored_location_url = LaxURLField(required=False) + provider_portal_url = LaxURLField(required=False) + expiration_notifications_enabled = ChoiceField(required=False, choices=BOOLEAN_WITH_BLANK_CHOICES) + default_notification_intervals = ChoiceField(required=False, choices=BOOLEAN_WITH_BLANK_CHOICES) + custom_notification_interval = IntegerField(required=False, min_value=1) + custom_notification_interval_unit = ChoiceField( + required=False, choices=add_blank_choice(NotificationIntervalUnits.choices) + ) + email_notifications = ChoiceField(required=False, choices=BOOLEAN_WITH_BLANK_CHOICES) + + software_product = DynamicModelChoiceField( + queryset=SoftwareProduct.objects.all(), required=False, label=_("Software Product") + ) + device = DynamicModelChoiceField(queryset=Device.objects.all(), required=False, label=_("Device")) + virtualmachine = DynamicModelChoiceField( + queryset=VirtualMachine.objects.all(), required=False, label=_("Virtual Machine") + ) + tenant_group = DynamicModelChoiceField(queryset=TenantGroup.objects.all(), required=False, label=_("Tenant Group")) + tenant = DynamicModelChoiceField( + queryset=Tenant.objects.all(), + required=False, + query_params={"group_id": "$tenant_group"}, + label=_("Tenant"), + ) diff --git a/netbox_slm/jobs.py b/netbox_slm/jobs.py index 5dd64d5..2cbee85 100644 --- a/netbox_slm/jobs.py +++ b/netbox_slm/jobs.py @@ -8,84 +8,143 @@ from core.choices import JobIntervalChoices from extras.models import Notification from netbox.jobs import JobRunner, system_job -from netbox_slm.events import LICENSE_EXPIRING -from netbox_slm.models import SoftwareLicense, SoftwareLicenseNotificationLog +from netbox_slm.events import CERTIFICATE_EXPIRING, LICENSE_EXPIRING +from netbox_slm.models import ( + Certificate, + CertificateNotificationLog, + SoftwareLicense, + SoftwareLicenseNotificationLog, +) -@system_job(interval=JobIntervalChoices.INTERVAL_DAILY) -class LicenseExpirationNotificationJob(JobRunner): - class Meta: - name = "Software License Expiration Notifications" +class ExpirationNotificationJob(JobRunner): + """Shared reminder logic; subclasses define the model, log model, event type and email text.""" + + model = None + log_model = None + log_object_field = None + event_type = None + + def get_queryset(self, today): + return self.model.objects.filter( + expiration_notifications_enabled=True, + expiration_date__gte=today, + ) + + def get_email(self, obj): + raise NotImplementedError def run(self, *args, **kwargs): today = timezone.localdate() - licenses = SoftwareLicense.objects.filter( - expiration_notifications_enabled=True, - lifetime=False, - expiration_date__gte=today, - ).prefetch_related("subscriptions__user") + objects = self.get_queryset(today).prefetch_related("subscriptions__user") - for license in licenses: - due_dates = [date for date in license.get_notification_dates() if date <= today] + for obj in objects: + due_dates = [date for date in obj.get_notification_dates() if date <= today] if not due_dates: continue - for subscription in license.subscriptions.all(): + for subscription in obj.subscriptions.all(): user = subscription.user if not user.is_active: continue # If notifications were enabled late, send only the most recent reminder instead of one per elapsed # interval. Normally this still produces one reminder at each configured threshold. - self._notify(license, user, max(due_dates)) + self._notify(obj, user, max(due_dates)) - def _notify(self, license, user, notification_date): - log = SoftwareLicenseNotificationLog.objects.get_or_create( - license=license, + def _notify(self, obj, user, notification_date): + log = self.log_model.objects.get_or_create( + **{self.log_object_field: obj}, user=user, - expiration_date=license.expiration_date, + expiration_date=obj.expiration_date, notification_date=notification_date, )[0] now = timezone.now() + name = self.model._meta.model_name - object_type = ContentType.objects.get_for_model(license) + object_type = ContentType.objects.get_for_model(obj) Notification.objects.update_or_create( object_type=object_type, - object_id=license.pk, + object_id=obj.pk, user=user, defaults={ "created": now, - "object_repr": Notification.get_object_repr(license), - "event_type": LICENSE_EXPIRING, + "object_repr": Notification.get_object_repr(obj), + "event_type": self.event_type, "read": None, }, ) log.netbox_sent_at = now log.save(update_fields=("netbox_sent_at",)) - self.logger.info(f"Created NetBox expiration notification for license {license.pk} and user {user}") - - if license.email_notifications and user.email: - subject = _("License %(license)s expires on %(date)s") % { - "license": license, - "date": license.expiration_date, - } - body = _( - "The software license '%(license)s' for '%(product)s' expires on %(date)s." - ) % { - "license": license, - "product": license.software_product, - "date": license.expiration_date, - } - if license.tenant: - body += "\n" + _("Tenant: %(tenant)s") % {"tenant": license.tenant} - if license.provider_portal_url: - body += "\n" + _("Provider portal: %(url)s") % {"url": license.provider_portal_url} + self.logger.info(f"Created NetBox expiration notification for {name} {obj.pk} and user {user}") + if obj.email_notifications and user.email: + subject, body = self.get_email(obj) try: from_email = settings.SERVER_EMAIL or settings.EMAIL_HOST_USER send_mail(subject, body, from_email, [user.email], fail_silently=False) except Exception: - self.logger.exception(f"Failed to send expiration email for license {license.pk} to user {user}") + self.logger.exception(f"Failed to send expiration email for {name} {obj.pk} to user {user}") else: log.email_sent_at = now log.save(update_fields=("email_sent_at",)) - self.logger.info(f"Sent expiration email for license {license.pk} to user {user}") + self.logger.info(f"Sent expiration email for {name} {obj.pk} to user {user}") + + +@system_job(interval=JobIntervalChoices.INTERVAL_DAILY) +class LicenseExpirationNotificationJob(ExpirationNotificationJob): + model = SoftwareLicense + log_model = SoftwareLicenseNotificationLog + log_object_field = "license" + event_type = LICENSE_EXPIRING + + class Meta: + name = "Software License Expiration Notifications" + + def get_queryset(self, today): + return super().get_queryset(today).filter(lifetime=False) + + def get_email(self, license): + subject = _("License %(license)s expires on %(date)s") % { + "license": license, + "date": license.expiration_date, + } + body = _("The software license '%(license)s' for '%(product)s' expires on %(date)s.") % { + "license": license, + "product": license.software_product, + "date": license.expiration_date, + } + if license.tenant: + body += "\n" + _("Tenant: %(tenant)s") % {"tenant": license.tenant} + if license.provider_portal_url: + body += "\n" + _("Provider portal: %(url)s") % {"url": license.provider_portal_url} + return subject, body + + +@system_job(interval=JobIntervalChoices.INTERVAL_DAILY) +class CertificateExpirationNotificationJob(ExpirationNotificationJob): + model = Certificate + log_model = CertificateNotificationLog + log_object_field = "certificate" + event_type = CERTIFICATE_EXPIRING + + class Meta: + name = "Certificate Expiration Notifications" + + def get_email(self, certificate): + subject = _("Certificate %(certificate)s expires on %(date)s") % { + "certificate": certificate, + "date": certificate.expiration_date, + } + body = _("The certificate '%(certificate)s' expires on %(date)s.") % { + "certificate": certificate, + "date": certificate.expiration_date, + } + if certificate.common_name: + body += "\n" + _("Common name: %(name)s") % {"name": certificate.common_name} + if certificate.issuer: + body += "\n" + _("Issuer: %(issuer)s") % {"issuer": certificate.issuer} + if certificate.tenant: + body += "\n" + _("Tenant: %(tenant)s") % {"tenant": certificate.tenant} + if certificate.provider_portal_url: + body += "\n" + _("Provider portal: %(url)s") % {"url": certificate.provider_portal_url} + return subject, body diff --git a/netbox_slm/locale/de/LC_MESSAGES/django.mo b/netbox_slm/locale/de/LC_MESSAGES/django.mo index e807294b075c84530ae53901e85884e8cadae82e..ffc67b809c4794c7b16b213d1f67cca3772669d7 100644 GIT binary patch literal 11097 zcmbW6e~cu>b;m3GG8`PnfX$BpF5?`#d%oEN0tei2j`nW%V9o7uzCAbsww2zQ-r3I1 z^eo*y_hYTdB(j2KC6Z-Cf^0;bb+O5iXUEl)}x01p5@8C^-+qG57_j@q82VXTHr3qRbDV^z?AuZ$Rno9mt=#j7e)86M@^H>|{5j3zNc|;b+48XQAZ$6_ngp;H~hV;T-%R zFQwNu)Vx0pCFiq{CgxFiHT){v0$&L4|0C3&h0$qz*FueN2b6y2pzQk-Pc0c| z)O-fYZXOBmpN3k;XQ96PY2g1t>Hi#zRdUXU(*Gq;dbkp5oMUhs+#dKKls$hH&cZjK zin&&d)6Z3hB2*_W3m^Jv|38Y4bfOJ^dJ}-?yN~c{WPYd^SSWUkUZy zbx?9{hr8h2Q2l=q{tEmj3~K#84}TSY1#10Y zhSTsTQ1hKcDQb5+RQUkB3;qV&3;!HSA8$eF?Hm?e{l6FLyK5k-F*m_m;6W(8{2tW2 z9*0_oZ$jzwJ5cNYDwMwd2TEUOGilB90w}xr0F=E?K-uRM+yiH!zWYMpm*H8IpM?7E zDX8{;2{n!vp#1n1xC6ccZ-&>Q%vtyecmO^L&xCJ5$^RLYU7S1SYVl^%hRykG%0Kw5q5!2SK>MfjT^S;G~;3^&L+)tbSyX1@nY0%6{9=R>%5*NE3yEd z4`WtlI?1DjR@^YtoqAVm?d{{91AD1ClD0ZgV_-p@I(l!)^>ei|BNlNc_0ngULTAzD z-IbM2R+yQ-CGH!rjmirxWwqg;5$$1FY<(%NFX!F1QOT)(w(aE4R;{^Oz-S-rCU_BM z6V;2>G0Y~mE7<*FCu`eAoEJ&zR4{3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lZDQ=h(>gE2y3IQeS@pjVu~oT#wIU z8)o3ws1^K#%|!)Vj(RW?wbEkLS*ds2ij>o|qZV=y=XStx02S|ysEHS(%-7nDD$)I@8keGe5x1a9_%bTsAym9$sFIyVHp^T_ zmF@>r!v7%8SD9F%Xksra^BmNnS&Q1TCmc7S0&hW;~GO{Y7F2G)kEVo5bJMG!1N*fk^%6=E!XZOVX8rt$)N^6I& zxqEv@yB&%xw=Q>q9daMBwQ-}-zWG4L*U{G2(%!wx_-sd5f_-JlExTjsfc3=RwH{B( zNUdjgK!_$cRn6_~HXt#@HYCQlN}V(wPWr%xFPj~CAh|lg-b`t*EvftLbm|(rZuykm zoHjV(N)HMM?C9#Yk9lkDptsC6X1rr#SBytF5lq$m{LNjqV&#n8kokp;Opmj9tIoML V_jGn@ self.expiration_date: + raise ValidationError({"expiration_date": _("The expiration date must not be before the start date.")}) + self.clean_notification_settings() + + @property + def stored_location_txt(self): + if self.stored_location_url and not self.stored_location: + return _("Link") + return self.stored_location + + +class CertificateNotificationLog(models.Model): + certificate = models.ForeignKey( + to="netbox_slm.Certificate", on_delete=models.CASCADE, related_name="notification_logs" + ) + user = models.ForeignKey(to=settings.AUTH_USER_MODEL, on_delete=models.CASCADE) + expiration_date = models.DateField() + notification_date = models.DateField() + netbox_sent_at = models.DateTimeField(null=True, blank=True) + email_sent_at = models.DateTimeField(null=True, blank=True) + + class Meta: + constraints = [ + models.UniqueConstraint( + fields=("certificate", "user", "expiration_date", "notification_date"), + name="netbox_slm_certificate_notification_unique", + ) + ] diff --git a/netbox_slm/navigation.py b/netbox_slm/navigation.py index 5c137f9..a301691 100644 --- a/netbox_slm/navigation.py +++ b/netbox_slm/navigation.py @@ -79,6 +79,25 @@ slm_items = ( ), ), ), + PluginMenuItem( + link="plugins:netbox_slm:certificate_list", + link_text=_("Certificates"), + permissions=["netbox_slm.view_certificate"], + buttons=( + PluginMenuButton( + "plugins:netbox_slm:certificate_add", + _("Add"), + "mdi mdi-plus-thick", + permissions=["netbox_slm.add_certificate"], + ), + PluginMenuButton( + "plugins:netbox_slm:certificate_bulk_import", + _("Import"), + "mdi mdi-upload", + permissions=["netbox_slm.add_certificate"], + ), + ), + ), ) if get_plugin_config("netbox_slm", "top_level_menu"): diff --git a/netbox_slm/tables.py b/netbox_slm/tables.py index 4675f55..c2f7fb8 100644 --- a/netbox_slm/tables.py +++ b/netbox_slm/tables.py @@ -3,7 +3,13 @@ from django.db.models import Count, F, Value from django.utils.translation import gettext_lazy as _ from netbox.tables import NetBoxTable, ToggleColumn, columns -from netbox_slm.models import SoftwareProduct, SoftwareProductVersion, SoftwareProductInstallation, SoftwareLicense +from netbox_slm.models import ( + Certificate, + SoftwareProduct, + SoftwareProductVersion, + SoftwareProductInstallation, + SoftwareLicense, +) class SoftwareProductTable(NetBoxTable): @@ -195,3 +201,65 @@ class SoftwareLicenseTable(NetBoxTable): def render_installation(self, **kwargs): return f"{kwargs['record'].installation.platform}" + + +class CertificateTable(NetBoxTable): + """Table for displaying Certificate objects.""" + + pk = ToggleColumn() + name = tables.LinkColumn() + + type = tables.Column() + stored_location = tables.Column(accessor="stored_location_txt", linkify=lambda record: record.stored_location_url) + software_product = tables.Column(accessor="software_product", verbose_name=_("Software Product"), linkify=True) + installation = tables.Column(accessor="installation", linkify=True) + device = tables.Column(accessor="device", linkify=True) + virtualmachine = tables.Column(accessor="virtualmachine", verbose_name=_("Virtual Machine"), linkify=True) + tenant_group = tables.Column(accessor="tenant_group", verbose_name=_("Tenant Group"), linkify=True) + tenant = tables.Column(accessor="tenant", linkify=True) + provider_portal_url = tables.Column(verbose_name=_("Provider Portal"), linkify=True) + + tags = columns.TagColumn(url_name="plugins:netbox_slm:certificate_list") + + class Meta(NetBoxTable.Meta): + model = Certificate + fields = ( + "pk", + "name", + "description", + "type", + "common_name", + "issuer", + "serial_number", + "fingerprint", + "start_date", + "expiration_date", + "auto_renewal", + "stored_location", + "software_product", + "installation", + "device", + "virtualmachine", + "tenant_group", + "tenant", + "provider_portal_url", + "expiration_notifications_enabled", + "email_notifications", + "tags", + ) + default_columns = ( + "pk", + "name", + "type", + "common_name", + "issuer", + "device", + "virtualmachine", + "tenant", + "expiration_date", + "expiration_notifications_enabled", + "tags", + ) + + def render_installation(self, **kwargs): + return f"{kwargs['record'].installation.platform}" diff --git a/netbox_slm/templates/netbox_slm/certificate.html b/netbox_slm/templates/netbox_slm/certificate.html new file mode 100644 index 0000000..5472f03 --- /dev/null +++ b/netbox_slm/templates/netbox_slm/certificate.html @@ -0,0 +1,187 @@ +{% extends 'generic/object.html' %} +{% load buttons %} +{% load static %} +{% load helpers %} +{% load plugins %} +{% load i18n %} + +{% block content %} +
+
+
+
+ {% trans "Certificate" %} +
+ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
{% trans "Name" %}{{ object.name }}
{% trans "Description" %}{{ object.description|placeholder }}
{% trans "Type" %}{{ object.get_type_display|placeholder }}
{% trans "Common name" %}{{ object.common_name|placeholder }}
{% trans "Subject alternative names" %}{% if object.subject_alternative_names %}{{ object.subject_alternative_names|linebreaksbr }}{% else %}{{ None|placeholder }}{% endif %}
{% trans "Issuer" %}{{ object.issuer|placeholder }}
{% trans "Serial number" %}{% if object.serial_number %}{{ object.serial_number }}{% else %}{{ None|placeholder }}{% endif %}
{% trans "SHA-256 fingerprint" %}{% if object.fingerprint %}{{ object.fingerprint }}{% else %}{{ None|placeholder }}{% endif %}
{% trans "Valid from" %}{{ object.start_date|placeholder }}
{% trans "Valid until" %}{{ object.expiration_date|placeholder }}
{% trans "Automatic renewal" %}{% if object.auto_renewal %}{% trans "Yes" %}{% else %}{% trans "No" %}{% endif %}
+
+
+
+ {% trans "Assignment" %} +
+ + + + + + + + + + + + + + + + + + + + + + + + + +
{% trans "Software Product" %}{{ object.software_product|linkify|placeholder }}
{% trans "Installation" %}{{ object.installation|linkify|placeholder }}
{% trans "Device" %}{{ object.device|linkify|placeholder }}
{% trans "Virtual Machine" %}{{ object.virtualmachine|linkify|placeholder }}
{% trans "Tenant Group" %}{{ object.tenant_group|linkify|placeholder }}
{% trans "Tenant" %}{{ object.tenant|linkify|placeholder }}
+
+{% include 'inc/panels/custom_fields.html' %} +{% include 'inc/panels/tags.html' %} +{% include 'inc/panels/comments.html' %} +{% plugin_left_page object %} +
+
+
+
+ {% trans "Storage" %} +
+ + + + + + + +{% if object.stored_location_url %} + +{% else %} + +{% endif %} + + + + + +
{% trans "Certificate file" %} +{% if object.certificate_file %} + {% trans "Download certificate file" %} +{% else %} + {{ None|placeholder }} +{% endif %} +
{% trans "Stored location" %}{{ object.stored_location_txt }}{{ object.stored_location_txt|placeholder }}
{% trans "Provider Portal" %} +{% if object.provider_portal_url %} + {{ object.provider_portal_url }} +{% else %} + {{ None|placeholder }} +{% endif %} +
+
+
+
+ {% trans "Expiration Notifications" %} +
+ + + + + + + + + + + + + + + + + + + + + +
{% trans "Expiration notifications" %}{% if object.expiration_notifications_enabled %}{% trans "Yes" %}{% else %}{% trans "No" %}{% endif %}
{% trans "Default notification intervals" %} +{% if object.default_notification_intervals %} + {% trans "One month and one week before expiration" %} +{% else %} + {% trans "Disabled" %} +{% endif %} +
{% trans "Custom notification interval" %} +{% if object.custom_notification_interval %} + {{ object.custom_notification_interval }} {{ object.get_custom_notification_interval_unit_display }} +{% else %} + {{ None|placeholder }} +{% endif %} +
{% trans "Email notifications" %}{% if object.email_notifications %}{% trans "Enabled" %}{% else %}{% trans "Disabled" %}{% endif %}
{% trans "Notification recipients" %} +{% for subscription in object.subscriptions.all %} + {{ subscription.user|linkify }}{% if not forloop.last %}, {% endif %} +{% empty %} + {% trans "No subscribers. Users can subscribe to this certificate using the Subscribe action." %} +{% endfor %} +
+
+{% plugin_right_page object %} +
+
+
+
+{% plugin_full_width_page object %} +
+
+{% endblock %} diff --git a/netbox_slm/tests/test_models.py b/netbox_slm/tests/test_models.py index 07e96b6..fc7bc85 100644 --- a/netbox_slm/tests/test_models.py +++ b/netbox_slm/tests/test_models.py @@ -10,8 +10,10 @@ from django.utils.translation import gettext, override from extras.models import Notification, Subscription from netbox_slm.forms import SoftwareLicenseForm, SoftwareProductInstallationForm -from netbox_slm.jobs import LicenseExpirationNotificationJob +from netbox_slm.jobs import CertificateExpirationNotificationJob, LicenseExpirationNotificationJob from netbox_slm.models import ( + Certificate, + CertificateNotificationLog, NotificationIntervalUnits, RenewalIntervalUnits, SoftwareLicense, @@ -208,3 +210,73 @@ class ModelTestCase(SlmBaseTestCase): with self.assertRaisesMessage(ValidationError, "does not belong to the selected tenant group"): self.software_license.full_clean() + + +class CertificateTestCase(SlmBaseTestCase): + def test_certificate_absolute_url(self): + certificate = Certificate.objects.create(name="example.com") + self.assertEqual("example.com", str(certificate)) + self.assertEqual(f"/plugins/slm/certificates/{certificate.pk}/", certificate.get_absolute_url()) + + def test_certificate_notification_dates(self): + certificate = Certificate( + name="expiring certificate", + expiration_date=date(2027, 3, 31), + custom_notification_interval=3, + custom_notification_interval_unit=NotificationIntervalUnits.DAYS, + ) + self.assertEqual( + [date(2027, 2, 28), date(2027, 3, 24), date(2027, 3, 28)], + certificate.get_notification_dates(), + ) + + def test_certificate_rejects_expiration_before_start(self): + certificate = Certificate( + name="invalid certificate", + start_date=date(2027, 1, 1), + expiration_date=date(2026, 1, 1), + ) + with self.assertRaisesMessage(ValidationError, "must not be before the start date"): + certificate.full_clean() + + def test_certificate_requires_custom_interval_and_unit_together(self): + certificate = Certificate(name="invalid interval", custom_notification_interval=2) + with self.assertRaisesMessage(ValidationError, "must be specified together"): + certificate.full_clean() + + @override_settings(SERVER_EMAIL="netbox@example.com", EMAIL_HOST_USER="smtp-user") + @patch("netbox_slm.jobs.send_mail") + def test_certificate_expiration_job_notifies_subscribers(self, send_mail): + user = get_user_model().objects.create_user( + username="certificate-recipient", + email="recipient@example.com", + ) + certificate = Certificate.objects.create( + name="expiring.example.com", + common_name="expiring.example.com", + expiration_date=timezone.localdate() + timedelta(days=1), + default_notification_intervals=False, + custom_notification_interval=1, + custom_notification_interval_unit=NotificationIntervalUnits.DAYS, + email_notifications=True, + ) + Subscription.objects.create( + user=user, + object_type=ContentType.objects.get_for_model(certificate), + object_id=certificate.pk, + ) + runner = CertificateExpirationNotificationJob.__new__(CertificateExpirationNotificationJob) + runner.logger = Mock() + + runner.run() + + self.assertTrue(Notification.objects.filter(user=user, object_id=certificate.pk).exists()) + self.assertEqual( + 1, CertificateNotificationLog.objects.filter(user=user, certificate=certificate).count() + ) + self.assertEqual(1, send_mail.call_count) + self.assertIn("expiring.example.com", send_mail.call_args.args[1]) + + def test_german_translation(self): + with override("de"): + self.assertEqual("Zertifikate", gettext("Certificates")) diff --git a/netbox_slm/urls.py b/netbox_slm/urls.py index 85c8392..1f3e465 100644 --- a/netbox_slm/urls.py +++ b/netbox_slm/urls.py @@ -12,4 +12,6 @@ urlpatterns = [ path("installations//", include(get_model_urls("netbox_slm", "softwareproductinstallation"))), path("licenses/", include(get_model_urls("netbox_slm", "softwarelicense", detail=False))), path("licenses//", include(get_model_urls("netbox_slm", "softwarelicense"))), + path("certificates/", include(get_model_urls("netbox_slm", "certificate", detail=False))), + path("certificates//", include(get_model_urls("netbox_slm", "certificate"))), ] diff --git a/netbox_slm/views/__init__.py b/netbox_slm/views/__init__.py index 3dc5830..8c88056 100644 --- a/netbox_slm/views/__init__.py +++ b/netbox_slm/views/__init__.py @@ -30,3 +30,11 @@ from .software_product_version import ( SoftwareProductVersionBulkDeleteView, SoftwareProductVersionBulkImportView, ) +from .certificate import ( + CertificateListView, + CertificateView, + CertificateEditView, + CertificateDeleteView, + CertificateBulkDeleteView, + CertificateBulkImportView, +) diff --git a/netbox_slm/views/certificate.py b/netbox_slm/views/certificate.py new file mode 100644 index 0000000..85c9295 --- /dev/null +++ b/netbox_slm/views/certificate.py @@ -0,0 +1,55 @@ +from netbox.views import generic +from netbox_slm import filtersets, forms, tables +from netbox_slm.models import Certificate +from netbox_slm.views.software_license import EmailNotificationPermissionMixin +from utilities.views import register_model_view + + +class CertificateEmailNotificationPermissionMixin(EmailNotificationPermissionMixin): + email_permission = "netbox_slm.manage_certificate_email_notifications" + + +@register_model_view(Certificate, "list", path="", detail=False) +class CertificateListView(generic.ObjectListView): + queryset = Certificate.objects.all() + filterset = filtersets.CertificateFilterSet + filterset_form = forms.CertificateFilterForm + table = tables.CertificateTable + + +@register_model_view(Certificate) +class CertificateView(generic.ObjectView): + queryset = Certificate.objects.all() + + +@register_model_view(Certificate, "add", detail=False) +@register_model_view(Certificate, "edit") +class CertificateEditView(CertificateEmailNotificationPermissionMixin, generic.ObjectEditView): + queryset = Certificate.objects.all() + form = forms.CertificateForm + + +@register_model_view(Certificate, "delete") +class CertificateDeleteView(generic.ObjectDeleteView): + queryset = Certificate.objects.all() + + +@register_model_view(Certificate, "bulk_import", detail=False) +class CertificateBulkImportView(CertificateEmailNotificationPermissionMixin, generic.BulkImportView): + queryset = Certificate.objects.all() + model_form = forms.CertificateBulkImportForm + + +@register_model_view(Certificate, "bulk_edit", path="edit", detail=False) +class CertificateBulkEditView(CertificateEmailNotificationPermissionMixin, generic.BulkEditView): + queryset = Certificate.objects.all() + filterset = filtersets.CertificateFilterSet + table = tables.CertificateTable + form = forms.CertificateBulkEditForm + + +@register_model_view(Certificate, "bulk_delete", path="delete", detail=False) +class CertificateBulkDeleteView(generic.BulkDeleteView): + queryset = Certificate.objects.all() + filterset = filtersets.CertificateFilterSet + table = tables.CertificateTable