From b4f947cf1f58f3fd3c1ed6ac95270191605cd3a7 Mon Sep 17 00:00:00 2001 From: Michael Aerni Date: Fri, 1 Nov 2024 14:09:38 -0400 Subject: [PATCH] Select correct site when using multiple domains --- src/Http/Middleware/CP/SelectedSite.php | 11 ++++-- tests/Http/Middleware/SelectedSiteTest.php | 42 ++++++++++++++++++++++ 2 files changed, 51 insertions(+), 2 deletions(-) diff --git a/src/Http/Middleware/CP/SelectedSite.php b/src/Http/Middleware/CP/SelectedSite.php index bbb9e833e9..eed0e960a4 100644 --- a/src/Http/Middleware/CP/SelectedSite.php +++ b/src/Http/Middleware/CP/SelectedSite.php @@ -10,13 +10,20 @@ class SelectedSite { public function handle($request, Closure $next) { - $this->updateSelectedSite(); + $this->updateSelectedSite($request); return $next($request); } - private function updateSelectedSite() + private function updateSelectedSite($request) { + $siteByUrl = Site::findByUrl($request->getSchemeAndHttpHost()); + + /* Ensure that we only make this automatic selection when first loggin in */ + if (! session('statamic.cp.selected-site') && $siteByUrl) { + Site::setSelected($siteByUrl->handle()); + } + if (User::current()->can('view', Site::selected())) { return; } diff --git a/tests/Http/Middleware/SelectedSiteTest.php b/tests/Http/Middleware/SelectedSiteTest.php index c778d686e0..0f22766f0c 100644 --- a/tests/Http/Middleware/SelectedSiteTest.php +++ b/tests/Http/Middleware/SelectedSiteTest.php @@ -81,6 +81,48 @@ public function it_doesnt_do_anything_when_there_are_no_authorized_sites() $this->assertEquals('de', Site::selected()->handle()); } + #[Test] + public function it_sets_the_correct_site_when_first_logging_in() + { + $this->setSites([ + 'en' => ['url' => 'https://en.test', 'locale' => 'en'], + 'fr' => ['url' => 'https://fr.test', 'locale' => 'fr'], + 'de' => ['url' => 'https://de.test', 'locale' => 'de'], + ]); + + $this->setTestRoles(['test' => [ + // no authorized sites + ]]); + $user = tap(User::make()->assignRole('test'))->save(); + + $this->actingAs($user); + $request = $this->createRequest('https://fr.test/cp/foo'); + $handled = false; + + (new SelectedSite())->handle($request, function () use (&$handled) { + $handled = true; + + return new Response; + }); + + $this->assertTrue($handled); + $this->assertEquals('fr', Site::selected()->handle()); + + Site::setSelected('en'); + + $request = $this->createRequest('https://fr.test/cp/bar'); + $handled = false; + + (new SelectedSite())->handle($request, function () use (&$handled) { + $handled = true; + + return new Response; + }); + + $this->assertTrue($handled); + $this->assertEquals('en', Site::selected()->handle()); + } + #[Test] public function middleware_attached_to_routes() {