Keep the chosen language across sign-in and forced sign-out

A language picked on a signed-out page is now stored on the account when
the user signs in (StoreLocaleChosenBeforeLogin), so the app does not
switch back to the account default. EnsureAccountIsUsable keeps the user's
language for the login page when it ends a disabled account's session.

ChangePreferredLocale runs in a transaction like the other use cases, the
language names come from layout.languages instead of the Locale enum, and
the translation test also compares fi.json with en.json and rejects
English files without a Finnish counterpart.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
2026-11-25 07:09:22 +02:00
co-authored by Claude Opus 5.5
parent 4f926c238b
commit 45dbb04344
14 changed files with 170 additions and 36 deletions
@@ -4,19 +4,24 @@ declare(strict_types=1);
namespace App\Modules\Users\Application\UseCases; namespace App\Modules\Users\Application\UseCases;
use App\Modules\Shared\Application\Contracts\TransactionManager;
use App\Modules\Users\Domain\Contracts\UserAccountRepository; use App\Modules\Users\Domain\Contracts\UserAccountRepository;
use App\Modules\Users\Domain\Enums\Locale; use App\Modules\Users\Domain\Enums\Locale;
/** /**
* A user chooses the language of the user interface from their profile menu. * A user chooses the language of the user interface: from their profile menu,
* The choice is kept on the account, so it follows them to every device. * or on the signed-out pages before signing in. The choice is kept on the
* account, so it follows them to every device.
*/ */
final class ChangePreferredLocale final class ChangePreferredLocale
{ {
public function __construct(private UserAccountRepository $users) {} public function __construct(
private UserAccountRepository $users,
private TransactionManager $transactions,
) {}
public function execute(int $userId, Locale $locale): void public function execute(int $userId, Locale $locale): void
{ {
$this->users->changeLocale($userId, $locale); $this->transactions->run(fn () => $this->users->changeLocale($userId, $locale));
} }
} }
+2 -12
View File
@@ -6,21 +6,11 @@ namespace App\Modules\Users\Domain\Enums;
/** /**
* The languages of the user interface. A user's choice is kept on their * The languages of the user interface. A user's choice is kept on their
* account; signed-out pages keep it in the session. * account; signed-out pages keep it in the session. Their names are the
* translations layout.languages.<value>.
*/ */
enum Locale: string enum Locale: string
{ {
case Finnish = 'fi'; case Finnish = 'fi';
case English = 'en'; case English = 'en';
/**
* The language's name in the language itself, as language pickers show it.
*/
public function nativeName(): string
{
return match ($this) {
self::Finnish => 'Suomi',
self::English => 'English',
};
}
} }
@@ -14,13 +14,16 @@ use App\Modules\Users\Infrastructure\Persistence\Repositories\EloquentUserAccoun
use App\Modules\Users\Infrastructure\Persistence\Repositories\EloquentUserAccountRepository; use App\Modules\Users\Infrastructure\Persistence\Repositories\EloquentUserAccountRepository;
use App\Modules\Users\Infrastructure\SystemClock; use App\Modules\Users\Infrastructure\SystemClock;
use App\Modules\Users\Presentation\Console\CreateAdminCommand; use App\Modules\Users\Presentation\Console\CreateAdminCommand;
use App\Modules\Users\Presentation\Http\Listeners\StoreLocaleChosenBeforeLogin;
use App\Modules\Users\Presentation\Http\Middleware\EnsureAccountIsUsable; use App\Modules\Users\Presentation\Http\Middleware\EnsureAccountIsUsable;
use App\Modules\Users\Presentation\Http\Middleware\SetLocale; use App\Modules\Users\Presentation\Http\Middleware\SetLocale;
use Illuminate\Auth\Events\Login;
use Illuminate\Auth\Notifications\ResetPassword; use Illuminate\Auth\Notifications\ResetPassword;
use Illuminate\Contracts\Auth\CanResetPassword; use Illuminate\Contracts\Auth\CanResetPassword;
use Illuminate\Notifications\Messages\MailMessage; use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Routing\Router; use Illuminate\Routing\Router;
use Illuminate\Session\Middleware\AuthenticateSession; use Illuminate\Session\Middleware\AuthenticateSession;
use Illuminate\Support\Facades\Event;
use Illuminate\Support\Facades\Gate; use Illuminate\Support\Facades\Gate;
use Illuminate\Support\ServiceProvider; use Illuminate\Support\ServiceProvider;
use Illuminate\Validation\Rules\Password; use Illuminate\Validation\Rules\Password;
@@ -63,6 +66,7 @@ class UsersServiceProvider extends ServiceProvider
// The language of the user interface; after the session has started. // The language of the user interface; after the session has started.
$router->pushMiddlewareToGroup('web', SetLocale::class); $router->pushMiddlewareToGroup('web', SetLocale::class);
Event::listen(Login::class, StoreLocaleChosenBeforeLogin::class);
if ($this->app->runningInConsole()) { if ($this->app->runningInConsole()) {
$this->commands([CreateAdminCommand::class]); $this->commands([CreateAdminCommand::class]);
@@ -30,6 +30,8 @@ class SwitchLocaleController
// The signed-in user object may outlive this request (e.g. Octane, in-process browser tests). // The signed-in user object may outlive this request (e.g. Octane, in-process browser tests).
$user->locale = $locale; $user->locale = $locale;
} else {
$request->session()->put(SetLocale::CHOSEN_SESSION_KEY, true);
} }
$request->session()->put(SetLocale::SESSION_KEY, $locale->value); $request->session()->put(SetLocale::SESSION_KEY, $locale->value);
@@ -0,0 +1,39 @@
<?php
namespace App\Modules\Users\Presentation\Http\Listeners;
use App\Models\User;
use App\Modules\Users\Application\UseCases\ChangePreferredLocale;
use App\Modules\Users\Domain\Enums\Locale;
use App\Modules\Users\Presentation\Http\Middleware\SetLocale;
use Illuminate\Auth\Events\Login;
use Illuminate\Contracts\Session\Session;
/**
* A language the user picked on a signed-out page (login, forgot or set
* password) becomes their account's language when they sign in, so the
* pages after signing in stay in the language they just chose.
*/
class StoreLocaleChosenBeforeLogin
{
public function __construct(
private Session $session,
private ChangePreferredLocale $changeLocale,
) {}
public function handle(Login $event): void
{
if (! $event->user instanceof User || ! $this->session->pull(SetLocale::CHOSEN_SESSION_KEY, false)) {
return;
}
$locale = Locale::tryFrom((string) $this->session->get(SetLocale::SESSION_KEY));
if ($locale === null || $locale === $event->user->locale) {
return;
}
$this->changeLocale->execute($event->user->id, $locale);
$event->user->locale = $locale;
}
}
@@ -2,6 +2,7 @@
namespace App\Modules\Users\Presentation\Http\Middleware; namespace App\Modules\Users\Presentation\Http\Middleware;
use App\Models\User;
use App\Modules\Users\Application\UseCases\CheckLoginAllowed; use App\Modules\Users\Application\UseCases\CheckLoginAllowed;
use Closure; use Closure;
use Illuminate\Http\Request; use Illuminate\Http\Request;
@@ -21,10 +22,18 @@ class EnsureAccountIsUsable
$userId = Auth::id(); $userId = Auth::id();
if ($userId !== null && ! $this->checkLoginAllowed->execute((int) $userId)) { if ($userId !== null && ! $this->checkLoginAllowed->execute((int) $userId)) {
$user = $request->user();
$locale = $user instanceof User ? $user->locale->value : null;
Auth::guard('web')->logout(); Auth::guard('web')->logout();
$request->session()->invalidate(); $request->session()->invalidate();
$request->session()->regenerateToken(); $request->session()->regenerateToken();
// The login page explains why, in the language the user had chosen.
if ($locale !== null) {
$request->session()->put(SetLocale::SESSION_KEY, $locale);
}
// The reason goes in the URL: Livewire follows this redirect with // The reason goes in the URL: Livewire follows this redirect with
// fetch first, which would consume a flashed message. // fetch first, which would consume a flashed message.
return redirect()->route('login', ['access' => 'ended']); return redirect()->route('login', ['access' => 'ended']);
@@ -19,6 +19,12 @@ class SetLocale
{ {
public const SESSION_KEY = 'locale'; public const SESSION_KEY = 'locale';
/**
* Set when the user picked the language on a signed-out page: signing in
* then stores it on the account (StoreLocaleChosenBeforeLogin).
*/
public const CHOSEN_SESSION_KEY = 'locale_chosen';
public function handle(Request $request, Closure $next): Response public function handle(Request $request, Closure $next): Response
{ {
$user = $request->user(); $user = $request->user();
+5
View File
@@ -32,6 +32,11 @@ return [
'workflow_templates' => 'Workflow templates', 'workflow_templates' => 'Workflow templates',
'price_list_admin' => 'Price list maintenance', 'price_list_admin' => 'Price list maintenance',
'current_section' => '(current section)', 'current_section' => '(current section)',
// Each language by its own name, the same in every language.
'languages' => [
'fi' => 'Suomi',
'en' => 'English',
],
'profile' => [ 'profile' => [
'menu' => 'Profile: :name', 'menu' => 'Profile: :name',
'language' => 'Language', 'language' => 'Language',
+5
View File
@@ -32,6 +32,11 @@ return [
'workflow_templates' => 'Työnkulkupohjat', 'workflow_templates' => 'Työnkulkupohjat',
'price_list_admin' => 'Hinnaston ylläpito', 'price_list_admin' => 'Hinnaston ylläpito',
'current_section' => '(nykyinen osio)', 'current_section' => '(nykyinen osio)',
// Each language by its own name, the same in every language.
'languages' => [
'fi' => 'Suomi',
'en' => 'English',
],
'profile' => [ 'profile' => [
'menu' => 'Profiili: :name', 'menu' => 'Profiili: :name',
'language' => 'Kieli', 'language' => 'Kieli',
@@ -66,7 +66,7 @@
@if ($isCurrent) @if ($isCurrent)
<x-icon name="check" class="size-4" aria-hidden="true" /> <x-icon name="check" class="size-4" aria-hidden="true" />
@endif @endif
{{ $locale->nativeName() }} {{ __('layout.languages.'.$locale->value) }}
</button> </button>
@endforeach @endforeach
</div> </div>
@@ -24,7 +24,7 @@
@if ($isCurrent) @if ($isCurrent)
<x-icon name="check" class="size-4" aria-hidden="true" /> <x-icon name="check" class="size-4" aria-hidden="true" />
@endif @endif
{{ $locale->nativeName() }} {{ __('layout.languages.'.$locale->value) }}
</button> </button>
@endforeach @endforeach
</fieldset> </fieldset>
@@ -5,6 +5,7 @@ use App\Modules\Users\Domain\Enums\Locale;
use Illuminate\Auth\Notifications\ResetPassword; use Illuminate\Auth\Notifications\ResetPassword;
use Illuminate\Foundation\Testing\RefreshDatabase; use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Notification; use Illuminate\Support\Facades\Notification;
use Livewire\Livewire;
uses(RefreshDatabase::class); uses(RefreshDatabase::class);
@@ -53,6 +54,45 @@ it('keeps the language on the login page after logging out', function () {
$this->actingAs($user)->post(route('logout'))->assertSessionHas('locale', 'en'); $this->actingAs($user)->post(route('logout'))->assertSessionHas('locale', 'en');
}); });
it('stores the language chosen on the login page on the account when signing in', function () {
$user = User::factory()->create(['email' => '[email protected]', 'locale' => 'fi']);
$this->post(route('locale.update'), ['locale' => 'en'])->assertSessionHas('locale_chosen', true);
Livewire::test('users::login')
->set('email', '[email protected]')
->set('password', 'password')
->call('login')
->assertHasNoErrors();
expect($user->fresh()->locale)->toBe(Locale::English);
});
it('keeps the account language when the language was not chosen before signing in', function () {
$user = User::factory()->create(['email' => '[email protected]', 'locale' => 'en']);
// The login page after logging out of a Finnish account, without a choice of its own.
$this->withSession(['locale' => 'fi']);
Livewire::test('users::login')
->set('email', '[email protected]')
->set('password', 'password')
->call('login')
->assertHasNoErrors();
expect($user->fresh()->locale)->toBe(Locale::English);
});
it('keeps the language on the login page when a disabled account is signed out', function () {
$user = User::factory()->create(['locale' => 'en']);
$this->actingAs($user);
$user->update(['is_active' => false]);
$this->get(route('home'))
->assertRedirect(route('login', ['access' => 'ended']))
->assertSessionHas('locale', 'en');
});
it('rejects an unknown language', function () { it('rejects an unknown language', function () {
$user = User::factory()->create(); $user = User::factory()->create();
@@ -2,17 +2,15 @@
use App\Modules\Users\Application\UseCases\ChangePreferredLocale; use App\Modules\Users\Application\UseCases\ChangePreferredLocale;
use App\Modules\Users\Domain\Enums\Locale; use App\Modules\Users\Domain\Enums\Locale;
use Tests\Fakes\FakeTransactionManager;
use Tests\Fakes\InMemoryUserAccountRepository; use Tests\Fakes\InMemoryUserAccountRepository;
it('stores the chosen language on the account', function () { it('stores the chosen language on the account in a transaction', function () {
$users = new InMemoryUserAccountRepository; $users = new InMemoryUserAccountRepository;
$transactions = new FakeTransactionManager;
(new ChangePreferredLocale($users))->execute(7, Locale::English); (new ChangePreferredLocale($users, $transactions))->execute(7, Locale::English);
expect($users->locales)->toBe([7 => Locale::English]); expect($users->locales)->toBe([7 => Locale::English])
}); ->and($transactions->transactionCount)->toBe(1);
it('names each language in the language itself', function () {
expect(Locale::Finnish->nativeName())->toBe('Suomi')
->and(Locale::English->nativeName())->toBe('English');
}); });
+41 -10
View File
@@ -4,9 +4,17 @@
* Every user interface text exists in every language, with the same placeholders, * Every user interface text exists in every language, with the same placeholders,
* so a new Finnish text cannot be left without its English counterpart. * so a new Finnish text cannot be left without its English counterpart.
*/ */
function langPath(string $path = ''): string
{
return dirname(__DIR__, 2).'/lang'.($path === '' ? '' : '/'.$path);
}
/**
* @return array<string, string>
*/
function translationLines(string $locale, string $file): array function translationLines(string $locale, string $file): array
{ {
$lines = require dirname(__DIR__, 2)."/lang/{$locale}/{$file}"; $lines = require langPath("{$locale}/{$file}");
$flat = []; $flat = [];
$flatten = function (array $values, string $prefix) use (&$flatten, &$flat): void { $flatten = function (array $values, string $prefix) use (&$flatten, &$flat): void {
foreach ($values as $key => $value) { foreach ($values as $key => $value) {
@@ -18,27 +26,50 @@ function translationLines(string $locale, string $file): array
return $flat; return $flat;
} }
/**
* @return list<string>
*/
function placeholdersOf(string $text): array function placeholdersOf(string $text): array
{ {
// A placeholder starts a word: "ALV:n" (Finnish case ending) is not one. // A placeholder starts a word: "ALV:n" (Finnish case ending) is not one.
preg_match_all('/(?<![\p{L}\d]):([a-z_]+)/u', $text, $matches); preg_match_all('/(?<![\p{L}\d]):([a-z_]+)/u', $text, $matches);
$names = array_unique($matches[1]); $names = array_values(array_unique($matches[1]));
sort($names); sort($names);
return $names; return $names;
} }
dataset('translation files', fn () => array_map('basename', glob(dirname(__DIR__, 2).'/lang/fi/*.php'))); /**
* @param array<string, string> $finnish
it('has every Finnish text in English with the same placeholders', function (string $file) { * @param array<string, string> $english
expect(file_exists(dirname(__DIR__, 2)."/lang/en/{$file}"))->toBeTrue("lang/en/{$file} is missing"); */
function expectSameTexts(array $finnish, array $english, string $file): void
$finnish = translationLines('fi', $file); {
$english = translationLines('en', $file);
expect(array_keys($english))->toEqualCanonicalizing(array_keys($finnish)); expect(array_keys($english))->toEqualCanonicalizing(array_keys($finnish));
foreach ($finnish as $key => $text) { foreach ($finnish as $key => $text) {
expect(placeholdersOf($english[$key]))->toBe(placeholdersOf($text), "Placeholders differ in {$file}: {$key}"); expect(placeholdersOf($english[$key]))->toBe(placeholdersOf($text), "Placeholders differ in {$file}: {$key}");
} }
}
dataset('translation files', fn () => array_map('basename', glob(langPath('fi/*.php'))));
it('has every Finnish text in English with the same placeholders', function (string $file) {
expect(file_exists(langPath("en/{$file}")))->toBeTrue("lang/en/{$file} is missing");
expectSameTexts(translationLines('fi', $file), translationLines('en', $file), $file);
})->with('translation files'); })->with('translation files');
it('has no English translation file without a Finnish one', function () {
$finnish = array_map('basename', glob(langPath('fi/*.php')));
$english = array_map('basename', glob(langPath('en/*.php')));
expect($english)->toEqualCanonicalizing($finnish);
});
it('has the same JSON texts in Finnish and English', function () {
$finnish = json_decode((string) file_get_contents(langPath('fi.json')), true, flags: JSON_THROW_ON_ERROR);
$english = json_decode((string) file_get_contents(langPath('en.json')), true, flags: JSON_THROW_ON_ERROR);
expectSameTexts($finnish, $english, 'fi.json / en.json');
});