Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[5.x] Select correct site when using multiple domains #11042

Open
wants to merge 1 commit into
base: 5.x
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 9 additions & 2 deletions src/Http/Middleware/CP/SelectedSite.php
Original file line number Diff line number Diff line change
Expand Up @@ -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;
}
Expand Down
42 changes: 42 additions & 0 deletions tests/Http/Middleware/SelectedSiteTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -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()
{
Expand Down
Loading