From ab95b1aa1925cb10fc3491c73c10b3001d0c10b9 Mon Sep 17 00:00:00 2001
From: Benjamin Bertrand <benjamin.bertrand@esss.se>
Date: Fri, 9 Feb 2018 15:51:39 +0100
Subject: [PATCH] Add extra validator on interface name

The interface name shall start with the hostname of the host it is
associated to.

Note that this is only enforced via the UI (from which most users will interact),
not from the API.

Fixes INFRA-195
---
 app/network/forms.py   | 18 +++++++++++++++++-
 app/static/js/hosts.js |  4 ++++
 2 files changed, 21 insertions(+), 1 deletion(-)

diff --git a/app/network/forms.py b/app/network/forms.py
index 5af7ca6..b82c482 100644
--- a/app/network/forms.py
+++ b/app/network/forms.py
@@ -18,6 +18,21 @@ from ..validators import (Unique, RegexpList, IPNetwork, HOST_NAME_RE,
 from .. import utils, models
 
 
+def starts_with_hostname(form, field):
+    """Check that interface name starts with hostname"""
+    try:
+        # Create / Edit interface form
+        host_id_field = form['host_id']
+    except KeyError:
+        # Create host form
+        hostname = form['name'].data
+    else:
+        host = models.Host.query.get(host_id_field.data)
+        hostname = host.name
+    if not field.data.startswith(hostname):
+        raise validators.ValidationError(f'Interface name shall start with the hostname "{hostname}"')
+
+
 def validate_tags(form, field):
     choices = dict(field.choices)
     for tag_id in field.data:
@@ -115,7 +130,8 @@ class InterfaceForm(CSEntryForm):
         description='name must be 2-20 characters long and contain only letters, numbers and dash',
         validators=[validators.InputRequired(),
                     validators.Regexp(HOST_NAME_RE),
-                    Unique(models.Interface)],
+                    Unique(models.Interface),
+                    starts_with_hostname],
         filters=[utils.lowercase_field])
     mac_address = StringField(
         'MAC',
diff --git a/app/static/js/hosts.js b/app/static/js/hosts.js
index c9bf938..4c4b976 100644
--- a/app/static/js/hosts.js
+++ b/app/static/js/hosts.js
@@ -48,6 +48,10 @@ $(document).ready(function() {
     $("#interface_name").val(hostname);
   });
 
+  // Force the first interface to have the hostname as name
+  // This only applies to the hostForm (not when editing or adding interfaces)
+  $("#hostForm input[name=interface_name]").prop("readonly", true);
+
   var hosts_table =  $("#hosts_table").DataTable({
     "ajax": function(data, callback, settings) {
       $.getJSON(
-- 
GitLab