From aca011569d2e4c5a32ccbb1a556b87c0c7b8b7b4 Mon Sep 17 00:00:00 2001
From: Nicolas ROCHE <nroche@entrouvert.com>
Date: Thu, 13 Jun 2019 15:24:51 +0200
Subject: [PATCH 5/5] hobo_deploy: allow several templates for user/agent combo
 portals (#33876)

---
 .../combo/management/commands/import_template.py |  5 +++--
 hobo/matomo/utils.py                             |  2 +-
 hobo/multitenant/settings_loaders.py             | 13 +++++++------
 tests/test_import_template.py                    |  4 ++--
 tests/test_matomo_utils.py                       | 16 +++++++++++-----
 tests_multitenant/conftest.py                    | 15 ++++++++++++++-
 tests_multitenant/test_settings.py               |  2 ++
 7 files changed, 40 insertions(+), 17 deletions(-)

diff --git a/hobo/agent/combo/management/commands/import_template.py b/hobo/agent/combo/management/commands/import_template.py
index c6dc1e0..1d1352b 100644
--- a/hobo/agent/combo/management/commands/import_template.py
+++ b/hobo/agent/combo/management/commands/import_template.py
@@ -22,7 +22,8 @@ class Command(import_template.Command):
         try:
             return super(Command, self).handle(*args, **kwargs)
         except import_template.UnknownTemplateError:
-            # ignore errors if template name is portal-user or portal-agent as
+            # ignore errors if template name contains portal-user or portal-agent as
             # those names do not actually require an existing file to work.
-            if kwargs.get('template_name') not in ('portal-user', 'portal-agent'):
+            if not any(name in kwargs.get('template_name')
+                       for name in ('portal-user', 'portal-agent')):
                 raise
diff --git a/hobo/matomo/utils.py b/hobo/matomo/utils.py
index 7ff0bcb..b5f208f 100644
--- a/hobo/matomo/utils.py
+++ b/hobo/matomo/utils.py
@@ -89,7 +89,7 @@ def put_tracking_js(tracking_js):
 def get_tenant_name_and_public_urls():
     """get an alias for our matomo's id and urls to monitor"""
     tenant_name = None
-    services = [x for x in Combo.objects.all() if x.template_name == 'portal-user']
+    services = [x for x in Combo.objects.all() if 'portal-user' in x.template_name]
     if services != [] and services[0] != '':
         tenant_name = urlparse.urlparse(services[0].base_url).netloc
     services += [x for x in Wcs.objects.all()]
diff --git a/hobo/multitenant/settings_loaders.py b/hobo/multitenant/settings_loaders.py
index d4a6cc6..2a7fcd7 100644
--- a/hobo/multitenant/settings_loaders.py
+++ b/hobo/multitenant/settings_loaders.py
@@ -99,7 +99,8 @@ class KnownServices(FileBaseSettingsLoader):
                         service.get('title'),
                         service.get('variables').get('ou-label'))
 
-            if service.get('service-id') == 'combo' and service.get('template_name') == 'portal-agent':
+            if (service.get('service-id') == 'combo' and
+                    'portal-agent' in service.get('template_name', '')):
                 service_data['is-portal-agent'] = True
 
             # compute a symmetric shared secret using XOR
@@ -132,10 +133,10 @@ class TemplateVars(FileBaseSettingsLoader):
             variables['%s_url' % service.get('slug').replace('-','_')] = service.get('base_url')
 
             if service.get('service-id') == 'combo' and not service.get('secondary'):
-                if service.get('template_name') == 'portal-agent':
+                if 'portal-agent' in service.get('template_name', ''):
                     variables['portal_agent_url'] = service.get('base_url')
                     variables['portal_agent_title'] = service.get('title')
-                if service.get('template_name') == 'portal-user':
+                if 'portal-user' in service.get('template_name', ''):
                     variables['portal_user_url'] = service.get('base_url')
                     variables['portal_user_title'] = service.get('title')
 
@@ -151,7 +152,7 @@ class TemplateVars(FileBaseSettingsLoader):
             variables.update(service.get('variables') or {})
             variables['site_title'] = service.get('title')
 
-            if service.get('template_name') == 'portal-agent':
+            if 'portal-agent' in service.get('template_name', ''):
                 variables['is_portal_agent'] = True
 
         if getattr(settings, 'HOBO_MANAGER_HOMEPAGE_TITLE_VAR', None):
@@ -258,7 +259,7 @@ class SharedThemeSettings(FileBaseSettingsLoader):
         for service in hobo_json.get('services', []):
             if service.get('service-id') != 'combo':
                 continue
-            if service.get('template_name') != 'portal-user':
+            if 'portal-user' not in service.get('template_name', ''):
                 continue
             if service.get('secondary'):
                 continue
@@ -337,7 +338,7 @@ class Authentic(FileBaseSettingsLoader):
         for service in hobo_json.get('services', []):
             if service.get('service-id') != 'combo':
                 continue
-            if service.get('template_name') != 'portal-user':
+            if 'portal-user' not in service.get('template_name', ''):
                 continue
             tenant_settings.A2_HOMEPAGE_URL = service.get('base_url')
 
diff --git a/tests/test_import_template.py b/tests/test_import_template.py
index 658cec9..6b27f20 100644
--- a/tests/test_import_template.py
+++ b/tests/test_import_template.py
@@ -2,11 +2,11 @@ import pytest
 import mock
 
 from django.conf import settings
+from django.core.management import load_command_class
 from django.core.management.base import CommandError
 from django.test import override_settings
 
 from hobo.agent.common.management.commands.import_template import Command, UnknownTemplateError
-from django.core.management import load_command_class
 
 
 @mock.patch('hobo.agent.common.management.commands.import_template.os.path.exists')
@@ -90,7 +90,7 @@ def test_import_template_on_combo_agent(mocked_super):
 
     # do nothing on internal templates
     mocked_super.side_effect = UnknownTemplateError
-    for template in 'portal-user', 'portal-agent':
+    for template in 'portal-user', 'portal-agent', 'x-portal-user-x', 'x-portal-agent-x':
         command.handle(template_name=template)
 
     # template no found
diff --git a/tests/test_matomo_utils.py b/tests/test_matomo_utils.py
index 69c8761..b02c002 100644
--- a/tests/test_matomo_utils.py
+++ b/tests/test_matomo_utils.py
@@ -7,7 +7,7 @@ from requests import Response
 
 from django.test import override_settings
 
-from hobo.environment.models import Variable, Wcs, Combo, Fargo
+from hobo.environment.models import Variable, Combo, Hobo, Fargo, Wcs
 from hobo.matomo.utils import \
      get_variable, get_variable_value, get_tracking_js, put_tracking_js, \
      get_tenant_name_and_public_urls, MatomoError, MatomoException, MatomoWS, \
@@ -207,12 +207,18 @@ def test_get_variable_value():
 
 def test_get_tenant_name_and_public_urls():
     Combo.objects.create(base_url='https://combo.dev.publik.love',
-                         template_name='portal-user')
+                         template_name='...portal-user...')
+    Combo.objects.create(base_url='https://agent-combo.dev.publik.love',
+                         template_name='...portal-agent...')
+    Combo.objects.create(base_url='https://no-template-combo.dev.publik.love')
     Wcs.objects.create(base_url='https://wcs.dev.publik.love')
     Fargo.objects.create(base_url='https://fargo.dev.publik.love')
+    Hobo.objects.create(base_url='https://hobo.dev.publik.love')
     tenant_name, site_urls = get_tenant_name_and_public_urls()
     assert tenant_name == 'combo.dev.publik.love'
-    assert site_urls[2] == 'https://fargo.dev.publik.love/'
+    assert site_urls == ['https://combo.dev.publik.love/',
+                         'https://wcs.dev.publik.love/',
+                         'https://fargo.dev.publik.love/']
 
 def test_matomo_constructor():
     """build the matomo webservice object"""
@@ -652,7 +658,7 @@ def test_auto_configure_matomo(mocked_post):
     logme_url_var = get_variable('matomo_logme_url', '')
 
     Combo.objects.create(base_url='https://combo.dev.publik.love',
-                         template_name='portal-user')
+                         template_name='...portal-user...')
     Wcs.objects.create(base_url='https://wcs.dev.publik.love')
     Fargo.objects.create(base_url='https://fargo.dev.publik.love')
 
@@ -685,7 +691,7 @@ def test_auto_configure_matomo_error(mocked_post):
     tracking_js_var = get_variable('visits_tracking_js', 'js_code')
 
     Combo.objects.create(base_url='https://combo.dev.publik.love',
-                         template_name='portal-user')
+                         template_name='...portal-user...')
     Wcs.objects.create(base_url='https://wcs.dev.publik.love')
     Fargo.objects.create(base_url='https://fargo.dev.publik.love')
 
diff --git a/tests_multitenant/conftest.py b/tests_multitenant/conftest.py
index 07bc0c9..c64523f 100644
--- a/tests_multitenant/conftest.py
+++ b/tests_multitenant/conftest.py
@@ -63,7 +63,20 @@ def tenants(transactional_db, request, settings):
                      'title': 'Other',
                      'secret_key': 'abcde',
                      'service-id': 'authentic',
-                     'base_url': 'http://other.example.net'},
+                     'base_url': 'http://other.example.net'
+                    },
+                    {'slug': 'another',
+                     'title': 'Agent portal',
+                     'service-id': 'combo',
+                     'template_name': '...portal-agent...',
+                     'base_url': 'http://portal-agent.example.net'
+                    },
+                    {'slug': 'another2',
+                     'title': 'User portal',
+                     'service-id': 'combo',
+                     'template_name': '...portal-user...',
+                     'base_url': 'http://portal-user.example.net'
+                    }
                     ]}, fd)
         t = Tenant(domain_url=name,
                       schema_name=name.replace('-', '_').replace('.', '_'))
diff --git a/tests_multitenant/test_settings.py b/tests_multitenant/test_settings.py
index 98ee238..98700f4 100644
--- a/tests_multitenant/test_settings.py
+++ b/tests_multitenant/test_settings.py
@@ -87,6 +87,8 @@ def test_tenant_template_vars(tenants, settings, client):
                 assert django.conf.settings.TEMPLATE_VARS['other_url'] == 'http://other.example.net'
                 assert django.conf.settings.TEMPLATE_VARS['site_title'] == 'Test'
                 assert django.conf.settings.TEMPLATE_VARS['other_variable'] == 'bar'
+                assert django.conf.settings.TEMPLATE_VARS['portal_agent_url'] == 'http://portal-agent.example.net'
+                assert django.conf.settings.TEMPLATE_VARS['portal_user_url'] == 'http://portal-user.example.net'
 
         # check it's no longer defined after going back to the public schema
         with pytest.raises(AttributeError):
-- 
2.20.1

