Skip to content

Commit 4e39ab4

Browse files
committed
Remove credentials from OnboardingTask model entirely; capture them at form save time instead
1 parent 8c35620 commit 4e39ab4

File tree

5 files changed

+44
-99
lines changed

5 files changed

+44
-99
lines changed

netbox_onboarding/forms.py

Lines changed: 31 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,13 +13,15 @@
1313
"""
1414

1515
from django import forms
16+
from django_rq import get_queue
1617

1718
from utilities.forms import BootstrapMixin
1819
from dcim.models import Site, Platform, DeviceRole
1920
from extras.forms import CustomFieldModelCSVForm
2021

2122
from .models import OnboardingTask
2223
from .choices import OnboardingStatusChoices, OnboardingFailChoices
24+
from .utils.credentials import Credentials
2325

2426
BLANK_CHOICE = (("", "---------"),)
2527

@@ -39,7 +41,26 @@ class OnboardingTaskForm(BootstrapMixin, forms.ModelForm):
3941

4042
class Meta: # noqa: D106 "Missing docstring in public nested class"
4143
model = OnboardingTask
42-
fields = ["ip_address", "site", "username", "password", "secret", "role", "device_type", "platform", "port", "timeout"]
44+
fields = [
45+
"ip_address",
46+
"site",
47+
"username",
48+
"password",
49+
"secret",
50+
"role",
51+
"device_type",
52+
"platform",
53+
"port",
54+
"timeout",
55+
]
56+
57+
def save(self, commit=True, **kwargs):
58+
"""Save the model, and add it and the associated credentials to the onboarding worker queue."""
59+
model = super().save(commit=commit, **kwargs)
60+
if commit:
61+
credentials = Credentials(self.data["username"], self.data["password"], self.data["secret"])
62+
get_queue("default").enqueue("netbox_onboarding.worker.onboard_device", model.pk, credentials)
63+
return model
4364

4465

4566
class OnboardingTaskFilterForm(BootstrapMixin, forms.ModelForm):
@@ -63,7 +84,7 @@ class Meta: # noqa: D106 "Missing docstring in public nested class"
6384

6485

6586
class OnboardingTaskFeedCSVForm(CustomFieldModelCSVForm):
66-
"""TODO document me."""
87+
"""Form for entering CSV to bulk-import OnboardingTask entries."""
6788

6889
site = forms.ModelChoiceField(
6990
queryset=Site.objects.all(),
@@ -98,3 +119,11 @@ class OnboardingTaskFeedCSVForm(CustomFieldModelCSVForm):
98119
class Meta: # noqa: D106 "Missing docstring in public nested class"
99120
model = OnboardingTask
100121
fields = OnboardingTask.csv_headers
122+
123+
def save(self, commit=True, **kwargs):
124+
"""Save the model, and add it and the associated credentials to the onboarding worker queue."""
125+
model = super().save(commit=commit, **kwargs)
126+
if commit:
127+
credentials = Credentials(self.data.get("username"), self.data.get("password"), self.data.get("secret"))
128+
get_queue("default").enqueue("netbox_onboarding.worker.onboard_device", model.pk, credentials)
129+
return model

netbox_onboarding/migrations/0001_initial.py

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
# Generated by Django 3.0.6 on 2020-05-12 10:21
1+
# Generated by Django 3.0.6 on 2020-05-18 13:04
22

33
from django.conf import settings
44
from django.db import migrations, models
@@ -21,9 +21,6 @@ class Migration(migrations.Migration):
2121
("id", models.AutoField(auto_created=True, primary_key=True, serialize=False)),
2222
("group_id", models.CharField(blank=True, max_length=255)),
2323
("ip_address", models.CharField(max_length=255, null=True)),
24-
("username", models.CharField(blank=True, max_length=255)),
25-
("password", models.CharField(blank=True, max_length=255)),
26-
("secret", models.CharField(blank=True, max_length=255)),
2724
("device_type", models.CharField(max_length=255, null=True)),
2825
("status", models.CharField(max_length=255)),
2926
("failed_reason", models.CharField(max_length=255, null=True)),

netbox_onboarding/models.py

Lines changed: 0 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -31,12 +31,6 @@ class OnboardingTask(models.Model):
3131

3232
site = models.ForeignKey(to="dcim.Site", on_delete=models.SET_NULL, blank=True, null=True)
3333

34-
username = models.CharField(max_length=255, help_text="Device Username (optional)", blank=True)
35-
36-
password = models.CharField(max_length=255, help_text="Device Password (optional)", blank=True)
37-
38-
secret = models.CharField(max_length=255, help_text="Device Secret Password (optional)", blank=True)
39-
4034
role = models.ForeignKey(to="dcim.DeviceRole", on_delete=models.SET_NULL, blank=True, null=True)
4135

4236
device_type = models.CharField(
@@ -63,9 +57,6 @@ class OnboardingTask(models.Model):
6357
csv_headers = [
6458
"site",
6559
"ip_address",
66-
"username",
67-
"password",
68-
"secret",
6960
"port",
7061
"timeout",
7162
"platform",

netbox_onboarding/views.py

Lines changed: 0 additions & 79 deletions
Original file line numberDiff line numberDiff line change
@@ -12,15 +12,9 @@
1212
limitations under the License.
1313
"""
1414
import logging
15-
from django.contrib import messages
1615
from django.contrib.auth.mixins import PermissionRequiredMixin
17-
from django.core.exceptions import ValidationError
18-
from django.db import transaction
19-
from django.shortcuts import render
20-
from django_rq import get_queue
2116
from utilities.views import BulkImportView, ObjectEditView, ObjectListView
2217

23-
from netbox_onboarding.utils.credentials import Credentials
2418
from .filters import OnboardingTaskFilter
2519
from .forms import OnboardingTaskForm, OnboardingTaskFilterForm, OnboardingTaskFeedCSVForm
2620
from .models import OnboardingTask
@@ -41,19 +35,6 @@ class OnboardingTaskListView(PermissionRequiredMixin, ObjectListView):
4135
template_name = "netbox_onboarding/onboarding_tasks_list.html"
4236

4337

44-
def handle_created_onboarding_task(task, owner):
45-
"""Sanitize the OnboardingTask and hand it off to the worker queue."""
46-
credentials = Credentials(username=task.username, password=task.password, secret=task.secret)
47-
48-
task.username = ""
49-
task.password = ""
50-
task.secret = ""
51-
task.owner = owner
52-
task.save()
53-
54-
get_queue("default").enqueue("netbox_onboarding.worker.onboard_device", task.pk, credentials)
55-
56-
5738
class OnboardingTaskCreateView(PermissionRequiredMixin, ObjectEditView):
5839
"""View for creating a new OnboardingTask."""
5940

@@ -64,19 +45,6 @@ class OnboardingTaskCreateView(PermissionRequiredMixin, ObjectEditView):
6445
template_name = "netbox_onboarding/onboarding_task_edit.html"
6546
default_return_url = "plugins:netbox_onboarding:onboarding_task_list"
6647

67-
def post(self, request):
68-
"""Process an HTTP POST request."""
69-
form = self.model_form(request.POST)
70-
71-
if form.is_valid():
72-
obj = form.save()
73-
handle_created_onboarding_task(obj, self.request.user)
74-
75-
return render(
76-
request,
77-
self.template_name,
78-
{"form": form}
79-
)
8048

8149
class OnboardingTaskFeedBulkImportView(PermissionRequiredMixin, BulkImportView):
8250
"""View for bulk-importing a CSV file to create OnboardingTasks."""
@@ -85,50 +53,3 @@ class OnboardingTaskFeedBulkImportView(PermissionRequiredMixin, BulkImportView):
8553
model_form = OnboardingTaskFeedCSVForm
8654
table = OnboardingTaskFeedBulkTable
8755
default_return_url = "plugins:netbox_onboarding:onboarding_task_list"
88-
89-
def post(self, request):
90-
"""Process an HTTP POST request."""
91-
new_objs = []
92-
form = self._import_form(request.POST)
93-
94-
if form.is_valid():
95-
try:
96-
# Iterate through CSV data and bind each row to a new model form instance.
97-
with transaction.atomic():
98-
headers, records = form.cleaned_data["csv"]
99-
for row, data in enumerate(records, start=1):
100-
obj_form = self.model_form(data, headers=headers)
101-
if obj_form.is_valid():
102-
obj = self._save_obj(obj_form, request)
103-
new_objs.append(obj)
104-
else:
105-
for field, err in obj_form.errors.items():
106-
form.add_error("csv", "Row {} {}: {}".format(row, field, err[0]))
107-
raise ValidationError("")
108-
109-
for ot in new_objs:
110-
handle_created_onboarding_task(ot, self.request.user)
111-
112-
if new_objs:
113-
msg = "Imported {} {}".format(len(new_objs), new_objs[0]._meta.verbose_name_plural)
114-
messages.success(request, msg)
115-
116-
return render(
117-
request,
118-
"import_success.html",
119-
{"table": self.table(new_objs), "return_url": self.get_return_url(request),},
120-
)
121-
122-
except ValidationError:
123-
pass
124-
125-
return render(
126-
request,
127-
self.template_name,
128-
{
129-
"form": form,
130-
"fields": self.model_form().fields,
131-
"obj_type": self.model_form._meta.model._meta.verbose_name, # pylint:disable=no-member
132-
"return_url": self.get_return_url(request),
133-
},
134-
)

tasks.py

Lines changed: 12 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -167,11 +167,12 @@ def create_user(context, user="admin", netbox_ver=NETBOX_VER, python_ver=PYTHON_
167167

168168

169169
@task
170-
def makemigrations(context, netbox_ver=NETBOX_VER, python_ver=PYTHON_VER):
170+
def makemigrations(context, name="", netbox_ver=NETBOX_VER, python_ver=PYTHON_VER):
171171
"""Run Make Migration in Django.
172172
173173
Args:
174174
context (obj): Used to run specific commands
175+
name (str): Name of the migration to be created
175176
netbox_ver (str): NetBox version to use to build the container
176177
python_ver (str): Will use the Python version docker image to build from
177178
"""
@@ -180,10 +181,16 @@ def makemigrations(context, netbox_ver=NETBOX_VER, python_ver=PYTHON_VER):
180181
env={"NETBOX_VER": netbox_ver, "PYTHON_VER": python_ver},
181182
)
182183

183-
context.run(
184-
f"docker-compose -f {COMPOSE_FILE} -p {BUILD_NAME} run netbox python manage.py makemigrations",
185-
env={"NETBOX_VER": netbox_ver, "PYTHON_VER": python_ver},
186-
)
184+
if name:
185+
context.run(
186+
f"docker-compose -f {COMPOSE_FILE} -p {BUILD_NAME} run netbox python manage.py makemigrations --name {name}",
187+
env={"NETBOX_VER": netbox_ver, "PYTHON_VER": python_ver},
188+
)
189+
else:
190+
context.run(
191+
f"docker-compose -f {COMPOSE_FILE} -p {BUILD_NAME} run netbox python manage.py makemigrations",
192+
env={"NETBOX_VER": netbox_ver, "PYTHON_VER": python_ver},
193+
)
187194

188195
context.run(
189196
f"docker-compose -f {COMPOSE_FILE} -p {BUILD_NAME} down",

0 commit comments

Comments
 (0)