From ad5542d3ca221291b03a57d95878a875ec303769 Mon Sep 17 00:00:00 2001
From: Christophe Siraut <csiraut@entrouvert.com>
Date: Fri, 21 Jun 2019 11:24:30 +0200
Subject: [PATCH] environment: use current domain name for services creation
 form (#34212)

---
 debian/control            |  3 ++-
 hobo/environment/utils.py | 15 +++++++++++++++
 hobo/environment/views.py |  4 +---
 hobo/settings.py          |  2 --
 tests/test_environment.py | 26 ++++++++++++++++++++++++++
 tox.ini                   |  1 +
 6 files changed, 45 insertions(+), 6 deletions(-)

diff --git a/debian/control b/debian/control
index 4445a04..9f34852 100644
--- a/debian/control
+++ b/debian/control
@@ -20,7 +20,8 @@ Depends: ${misc:Depends},
     python-prometheus-client,
     python-djangorestframework,
     python-dnspython,
-    python-systemd
+    python-systemd,
+    python-six
 Recommends:
     python-gadjo,
     python-django-mellon (>= 1.2.22.26),
diff --git a/hobo/environment/utils.py b/hobo/environment/utils.py
index d215015..349ae92 100644
--- a/hobo/environment/utils.py
+++ b/hobo/environment/utils.py
@@ -1,3 +1,5 @@
+from six.moves.urllib.parse import urlparse
+
 from django.conf import settings
 from django.core.urlresolvers import reverse
 from django.db import connection
@@ -58,3 +60,16 @@ def get_setting_variable(name):
     variable, created = Variable.objects.get_or_create(name=name,
             defaults={'auto': True, 'value': settings.VARIABLE_SETTINGS_DEFAULTS.get(name) or ''})
     return variable
+
+def create_base_url(hostname, service):
+    """
+    Distinguish mutualised domains (matching a "-" in the first part of the netloc)
+    from the normal scenario with a dedicated parent domain.
+    """
+    ph = urlparse(hostname)
+    parts = ph.netloc.split('.')
+    if '-' in parts[0]:
+        netloc = '%s-%s.%s' % (service, parts[0].split('-')[1], '.'.join(parts[1:]))
+    else:
+        netloc = '%s.%s' % (service, '.'.join(parts[1:]))
+    return '%s://%s' % (ph.scheme, netloc)
diff --git a/hobo/environment/views.py b/hobo/environment/views.py
index 19f2cea..7f2979e 100644
--- a/hobo/environment/views.py
+++ b/hobo/environment/views.py
@@ -24,7 +24,6 @@ class HomeView(TemplateView):
 
     def get_context_data(self, **kwargs):
         context = super(HomeView, self).get_context_data(**kwargs)
-        context['url_template'] = settings.SERVICE_URL_TEMPLATE
         context['available_services'] = [
                 AvailableService(x) for x in AVAILABLE_SERVICES if x.is_enabled()]
         context['installed_services'] = [x for x in utils.get_installed_services() if not x.secondary]
@@ -114,8 +113,7 @@ class ServiceCreateView(CreateView):
 
     def get_initial(self):
         initial = super(ServiceCreateView, self).get_initial()
-        initial['base_url'] = string.Template(settings.SERVICE_URL_TEMPLATE
-                ).substitute({'app': self.model.Extra.service_id})
+        initial['base_url'] = utils.create_base_url(self.request.build_absolute_uri(), self.model.Extra.service_default_slug)
         initial['slug'] = self.model.Extra.service_default_slug
         return initial
 
diff --git a/hobo/settings.py b/hobo/settings.py
index 997ba2c..eb78c3c 100644
--- a/hobo/settings.py
+++ b/hobo/settings.py
@@ -137,8 +137,6 @@ AUTHENTICATION_BACKENDS = (
     'django.contrib.auth.backends.ModelBackend',
 )
 
-SERVICE_URL_TEMPLATE = 'https://${app}.example.net'
-
 # SERVICE_TEMPLATES: possible "flavours" for the various service types.
 # This variable expects a dictionary mapping service identifiers
 # to a list of (template name, template title) tuples.
diff --git a/tests/test_environment.py b/tests/test_environment.py
index 0c8517d..bd26942 100644
--- a/tests/test_environment.py
+++ b/tests/test_environment.py
@@ -1,12 +1,25 @@
 # -*- coding: utf-8 -*-
 import pytest
 
+from django.contrib.auth.models import User
 from django.core.exceptions import ValidationError
 from django.utils import timezone
+
 from hobo.environment.models import AVAILABLE_SERVICES, Combo, Passerelle
 
 pytestmark = pytest.mark.django_db
 
+
+def login(app, username='admin', password='password'):
+    login_page = app.get('/login/')
+    login_form = login_page.forms[0]
+    login_form['username'] = username
+    login_form['password'] = password
+    resp = login_form.submit()
+    assert resp.status_int == 302
+    return app
+
+
 def test_service_id():
     for service in AVAILABLE_SERVICES:
         assert service.Extra.service_id
@@ -58,3 +71,16 @@ def test_base_url_field_validator():
             combo = Combo(base_url=url, slug='wesh_'+str(cpt), **kwargs)
             combo.full_clean()
             combo.save()
+
+
+def test_service_creation_filling(app, admin_user, monkeypatch):
+    from django.http.request import HttpRequest
+    monkeypatch.setattr(HttpRequest, 'get_host', lambda x: 'test.example.net')
+    app = login(app)
+    response = app.get('/sites/new-combo')
+    assert 'value="http://portal.example.net"' in response.text
+
+    monkeypatch.setattr(HttpRequest, 'get_host', lambda x: 'hobo-test.example.net')
+    app = login(app)
+    response = app.get('/sites/new-combo')
+    assert 'value="http://portal-test.example.net"' in response.text
diff --git a/tox.ini b/tox.ini
index 9071ea8..3ea6853 100644
--- a/tox.ini
+++ b/tox.ini
@@ -52,6 +52,7 @@ deps:
 	httmock
 	requests
 	pytest-freezegun
+	six
 commands =
 	./getlasso.sh
 	hobo: py.test {env:COVERAGE:} {env:NOMIGRATIONS:} {posargs:tests/}
-- 
2.20.1

