Skip to content

Commit

Permalink
fix: API Enrollment in Create/Edit form
Browse files Browse the repository at this point in the history
  • Loading branch information
mazzi committed Nov 8, 2023
1 parent 1ed6c77 commit df03b86
Show file tree
Hide file tree
Showing 7 changed files with 25 additions and 130 deletions.
82 changes: 0 additions & 82 deletions tests/inventory/test_setup_views.py
Original file line number Diff line number Diff line change
Expand Up @@ -221,88 +221,6 @@ def test_update_meta_business_unit(self, post_event):
'type': 'zentral_audit'}
)

# meta business unit api enrollment

def test_meta_business_unit_api_enrollment_redirect(self):
meta_business_unit = MetaBusinessUnit.objects.create(name=get_random_string(12))
self._login_redirect(reverse("inventory:mbu_api_enrollment", args=(meta_business_unit.pk,)))

def test_meta_business_unit_api_enrollment_permission_denied(self):
meta_business_unit = MetaBusinessUnit.objects.create(name=get_random_string(12))
self._login()
response = self.client.get(reverse("inventory:mbu_api_enrollment", args=(meta_business_unit.pk,)))
self.assertEqual(response.status_code, 403)

@patch("zentral.core.queues.backends.kombu.EventQueues.post_event")
def test_meta_business_unit_api_enrollment(self, post_event):
self._login(
"inventory.change_metabusinessunit",
"inventory.view_machinesnapshot",
"inventory.view_metabusinessunit",
)
meta_business_unit = MetaBusinessUnit.objects.create(name=get_random_string(12))
prev_updated_at = meta_business_unit.updated_at
with self.captureOnCommitCallbacks(execute=True) as callbacks:
response = self.client.post(
reverse("inventory:mbu_api_enrollment", args=(meta_business_unit.pk,)),
follow=True
)
self.assertEqual(response.status_code, 200)
self.assertEqual(len(callbacks), 1)
self.assertTemplateUsed(response, "inventory/mbu_machines.html")
meta_business_unit = response.context["object"]
self.assertTrue(meta_business_unit.api_enrollment_enabled())
event = post_event.call_args_list[0].args[0]
self.assertIsInstance(event, AuditEvent)
self.assertEqual(
event.payload,
{"action": "updated",
"object": {
"model": "inventory.metabusinessunit",
"pk": str(meta_business_unit.pk),
"prev_value": {
"pk": meta_business_unit.pk,
"name": meta_business_unit.name,
"api_enrollment_enabled": False,
"created_at": meta_business_unit.created_at,
"updated_at": prev_updated_at,
},
"new_value": {
"pk": meta_business_unit.pk,
"name": meta_business_unit.name,
"api_enrollment_enabled": True,
"created_at": meta_business_unit.created_at,
"updated_at": meta_business_unit.updated_at
}
}}
)
metadata = event.metadata.serialize()
metadata["tags"].sort()
self.assertEqual(
metadata,
{'created_at': event.metadata.created_at.isoformat(),
'id': str(event.metadata.uuid),
'index': 0,
'namespace': 'zentral_audit',
'objects': {'meta_business_unit': [str(meta_business_unit.pk)]},
'request': {'ip': '127.0.0.1',
'method': 'POST',
'path': f'/inventory/business_units/{meta_business_unit.pk}/api_enrollment/',
'user': {'email': self.user.email,
'id': self.user.pk,
'is_remote': False,
'is_service_account': False,
'is_superuser': False,
'session': {'is_remote': False,
'mfa_authenticated': False,
'token_authenticated': False,
'expire_at_browser_close': False,
'expiry_age': 1209600},
'username': self.user.username}},
'tags': ['inventory', 'zentral'],
'type': 'zentral_audit'}
)

# delete meta business unit

def test_delete_meta_business_unit_redirect(self):
Expand Down
29 changes: 17 additions & 12 deletions zentral/contrib/inventory/forms.py
Original file line number Diff line number Diff line change
Expand Up @@ -59,11 +59,27 @@ class MetaBusinessUnitSearchForm(forms.Form):


class MetaBusinessUnitForm(forms.ModelForm):

api_enrollment = forms.BooleanField(label="API Enrollment", required=False,)

def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
if self.instance.pk and self.instance.api_enrollment_enabled():
self.fields['api_enrollment'].initial = True
self.fields['api_enrollment'].disabled = True

class Meta:
model = MetaBusinessUnit
fields = ("name",)
fields = ("name", )
widgets = {"name": forms.TextInput}

def save(self):
self.instance.save()
if self.cleaned_data.get("api_enrollment"):
if not self.instance.api_enrollment_business_units().count():
self.instance.create_enrollment_business_unit()
return self.instance


class MergeMBUForm(forms.Form):
mbu = forms.ModelMultipleChoiceField(queryset=MetaBusinessUnit.objects.all())
Expand All @@ -85,17 +101,6 @@ def merge(self):
return dest_mbu


class MBUAPIEnrollmentForm(forms.ModelForm):
class Meta:
model = MetaBusinessUnit
fields = []

def save(self):
if not self.instance.api_enrollment_business_units().count():
self.instance.create_enrollment_business_unit()
return self.instance


class CreateTagForm(forms.ModelForm):
class Meta:
model = Tag
Expand Down
7 changes: 7 additions & 0 deletions zentral/contrib/inventory/templates/inventory/edit_mbu.html
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
{% extends 'base.html' %}
{% load inventory_extras %}

{% block content %}
<ol class="breadcrumb">
Expand All @@ -13,6 +14,12 @@
</ol>

<h2>{% if object %}Update{% else %}Create{% endif %} Business Unit</h2>
<p>
{% for tag in object.tags %}
{% inventory_tag tag %}
{% endfor %}
</p>

<form method="POST" class="update-form">{% csrf_token %}

{{ form }}
Expand Down

This file was deleted.

6 changes: 0 additions & 6 deletions zentral/contrib/inventory/templates/inventory/mbu_list.html
Original file line number Diff line number Diff line change
Expand Up @@ -84,12 +84,6 @@ <h2 class="m-0">Business unit{{ page_obj.paginator.count|pluralize }} ({{ page_o
{% endif %}
</td>
<td class="text-end py-0">
{% if not mbu.api_enrollment_enabled and perms.inventory.change_metabusinessunit %}
<a href="{% url 'inventory:mbu_api_enrollment' mbu.id %}" class="btn btn-link text-decoration-none text-dark"
data-bs-toggle="tooltip" data-bs-placement="bottom" data-bs-title="Enable API enrollment">
<i class="bi bi-person"></i>
</a>
{% endif %}
{% if perms.inventory.view_metabusinessunittag and perms.inventory.add_metabusinessunittag and perms.inventory.change_metabusinessunittag and perms.inventory.delete_metabusinessunittag and perms.inventory.add_tag %}
<a href="{% url 'inventory:mbu_tags' mbu.id %}" class="btn btn-link text-decoration-none text-dark"
data-bs-toggle="tooltip" data-bs-placement="bottom" data-bs-title="Manage Tags">
Expand Down
3 changes: 0 additions & 3 deletions zentral/contrib/inventory/urls.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,6 @@
name='remove_mbu_tag'),
path('business_units/<int:pk>/machines/', views.MBUMachinesView.as_view(), name='mbu_machines'),
path('business_units/<int:pk>/detach_bu/<int:bu_id>/', views.DetachBUView.as_view(), name='detach_bu'),
path('business_units/<int:pk>/api_enrollment/',
views.MBUAPIEnrollmentView.as_view(),
name='mbu_api_enrollment'),

# machines
path('machine/<str:urlsafe_serial_number>/events/',
Expand Down
9 changes: 1 addition & 8 deletions zentral/contrib/inventory/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@
from .events import JMESPathCheckCreated, JMESPathCheckUpdated, JMESPathCheckDeleted
from .forms import (MetaBusinessUnitForm,
MetaBusinessUnitSearchForm, MachineGroupSearchForm,
MergeMBUForm, MBUAPIEnrollmentForm, AddMBUTagForm, AddMachineTagForm,
MergeMBUForm, AddMBUTagForm, AddMachineTagForm,
CreateTagForm, UpdateTagForm,
AndroidAppSearchForm, DebPackageSearchForm, IOSAppSearchForm,
MacOSAppSearchForm, ProgramsSearchForm,
Expand Down Expand Up @@ -436,13 +436,6 @@ def post(self, *args, **kwargs):
return HttpResponseRedirect(mbu.get_absolute_url())


class MBUAPIEnrollmentView(PermissionRequiredMixin, UpdateViewWithAudit):
permission_required = "inventory.change_metabusinessunit"
template_name = "inventory/mbu_api_enrollment.html"
model = MetaBusinessUnit
form_class = MBUAPIEnrollmentForm


class MBUMachinesView(MachineListView):
permission_required = ("inventory.view_metabusinessunit", "inventory.view_machinesnapshot")
template_name = "inventory/mbu_machines.html"
Expand Down

0 comments on commit df03b86

Please sign in to comment.