From 26757c678519e20a30355fcabf2970eaaef51e86 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?P=C4=93teris=20Caune?= Date: Tue, 25 Feb 2020 11:05:52 +0200 Subject: [PATCH] Clean up Pushover validation. --- hc/front/forms.py | 22 ++++++++++++++++++++++ hc/front/views.py | 24 +++++++----------------- 2 files changed, 29 insertions(+), 17 deletions(-) diff --git a/hc/front/forms.py b/hc/front/forms.py index f8c15c2b..901bf06f 100644 --- a/hc/front/forms.py +++ b/hc/front/forms.py @@ -90,6 +90,28 @@ class AddOpsGenieForm(forms.Form): key = forms.CharField(max_length=40) +PRIO_CHOICES = [ + ("-2", "Lowest Priority"), + ("-1", "Low Priority"), + ("0", "Normal Priority"), + ("1", "High Priority"), + ("2", "Emergency Priority"), +] + + +class AddPushoverForm(forms.Form): + error_css_class = "has-error" + pushover_user_key = forms.CharField() + prio = forms.ChoiceField(initial="0", choices=PRIO_CHOICES) + prio_up = forms.ChoiceField(initial="0", choices=PRIO_CHOICES) + + def get_value(self): + key = self.cleaned_data["pushover_user_key"] + prio = self.cleaned_data["prio"] + prio_up = self.cleaned_data["prio_up"] + return "%s|%s|%s" % (key, prio, prio_up) + + class AddEmailForm(forms.Form): error_css_class = "has-error" value = forms.EmailField(max_length=100) diff --git a/hc/front/views.py b/hc/front/views.py index 1e136d3e..9602212a 100644 --- a/hc/front/views.py +++ b/hc/front/views.py @@ -41,6 +41,7 @@ from hc.front.forms import ( AddMatrixForm, AddOpsGenieForm, AddPdForm, + AddPushoverForm, AddShellForm, AddSmsForm, AddUrlForm, @@ -1254,7 +1255,6 @@ def add_pushover(request, code): project = _get_project_for_user(request, code) if request.method == "POST": - # Initiate the subscription state = token_urlsafe() failure_url = settings.SITE_ROOT + reverse("hc-p-channels", args=[project.code]) @@ -1288,27 +1288,17 @@ def add_pushover(request, code): if request.GET.get("state") != state: return HttpResponseForbidden() - key = request.GET.get("pushover_user_key") - if key is None: - return HttpResponseBadRequest() - - # Validate priority - prio = request.GET.get("prio") - if prio not in ("-2", "-1", "0", "1", "2"): - return HttpResponseBadRequest() - - prio_up = request.GET.get("prio_up") - if prio_up not in ("-2", "-1", "0", "1", "2"): - return HttpResponseBadRequest() - if request.GET.get("pushover_unsubscribed") == "1": # Unsubscription: delete all Pushover channels for this project Channel.objects.filter(project=project, kind="po").delete() - return redirect("hc-channels") + return redirect("hc-p-channels", project.code) + + form = AddPushoverForm(request.GET) + if not form.is_valid(): + return HttpResponseBadRequest() - # Subscription channel = Channel(project=project, kind="po") - channel.value = "%s|%s|%s" % (key, prio, prio_up) + channel.value = form.get_value() channel.save() channel.assign_all_checks()