Merge pull request #3701 from modoboa/tool/add_allowed_hosts

New command to add allowed hosts to OAuth2 application
This commit is contained in:
Antoine Nguyen
2025-08-28 15:25:14 +02:00
committed by GitHub
2 changed files with 57 additions and 0 deletions
@@ -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()
+24
View File
@@ -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."""