diff --git a/modoboa/core/management/commands/add_allowed_hosts.py b/modoboa/core/management/commands/add_allowed_hosts.py new file mode 100644 index 000000000..90463ccc4 --- /dev/null +++ b/modoboa/core/management/commands/add_allowed_hosts.py @@ -0,0 +1,33 @@ +from django.core.management.base import BaseCommand, CommandError + +from oauth2_provider.models import get_application_model + + +class Command(BaseCommand): + """Command class.""" + + help = "Add new allowed hosts to frontend Oauth2 application." + + def add_arguments(self, parser): + parser.add_argument("hostnames", type=str, nargs="+") + + def handle(self, *args, **options): + app_model = get_application_model() + app = app_model.objects.filter(name="modoboa_frontend").first() + if not app: + raise CommandError( + "Application modoboa_frontend not found. " + "Make sure you ran load_initial_data first." + ) + redirect_uris = app.redirect_uris.split(" ") + post_logout_redirect_uris = app.post_logout_redirect_uris.split(" ") + for hostname in options["hostnames"]: + uri = f"https://{hostname}/login/logged" + if uri not in redirect_uris: + redirect_uris.append(uri) + uri = f"https://{hostname}" + if uri not in post_logout_redirect_uris: + post_logout_redirect_uris.append(uri) + app.redirect_uris = " ".join(redirect_uris) + app.post_logout_redirect_uris = " ".join(post_logout_redirect_uris) + app.save() diff --git a/modoboa/core/tests/test_core.py b/modoboa/core/tests/test_core.py index 77cec3457..99a448ebb 100644 --- a/modoboa/core/tests/test_core.py +++ b/modoboa/core/tests/test_core.py @@ -186,6 +186,30 @@ class ManagementCommandsTestCase(SimpleModoTestCase): with self.assertRaises(models.User.DoesNotExist): account.refresh_from_db() + def test_add_allowed_hosts(self): + with self.assertRaises(management.CommandError): + management.call_command( + "add_allowed_hosts", "app1.domain.tld", "app2.domain.tld" + ) + management.call_command("load_initial_data") + management.call_command( + "add_allowed_hosts", "app1.domain.tld", "app2.domain.tld" + ) + app_model = get_application_model() + app = app_model.objects.filter(name="modoboa_frontend").first() + self.assertIn("app1.domain.tld", app.redirect_uris) + self.assertIn("app2.domain.tld", app.redirect_uris) + self.assertIn("app1.domain.tld", app.post_logout_redirect_uris) + self.assertIn("app2.domain.tld", app.post_logout_redirect_uris) + + # Check if same hostname is not added more than once + uri_count = len(app.redirect_uris.split(" ")) + management.call_command( + "add_allowed_hosts", "app1.domain.tld", "app2.domain.tld" + ) + app.refresh_from_db() + self.assertEqual(len(app.redirect_uris.split(" ")), uri_count) + class APICommunicationTestCase(ModoTestCase): """Check communication with the API."""