From 8dfc02c4e56544f8de687b8ac636e4b51d078ea6 Mon Sep 17 00:00:00 2001 From: Petri Saarinen Date: Mon, 23 Nov 2026 17:42:37 +0200 Subject: [PATCH] End other sessions on password change and give admin links 72 hours - AuthenticateSession in the web group logs out a user's other sessions when their password changes. - Set-password links made by an admin use a new admin_links broker with its own password_setup_tokens table and a 72-hour expiry, so links handed over by hand don't expire in an hour. Forgot-password links keep 60 minutes. The reset page accepts both, and issuing or using a link ends the user's earlier links. - Admin links are emailed with PasswordSetupLinkNotification; the email body is shared with the forgot-password email via PasswordLinkMail. - Spec chapter 3 and CLAUDE.md describe the link lifetimes. Co-Authored-By: Claude Opus 5.5 --- CLAUDE.md | 2 +- .../Auth/LaravelPasswordLinkSender.php | 18 ++++-- .../Infrastructure/Auth/PasswordLinkMail.php | 28 ++++++++ .../Auth/PasswordSetupLinkNotification.php | 31 +++++++++ .../Providers/UsersServiceProvider.php | 22 +++---- .../Presentation/Livewire/⚡form.blade.php | 2 +- .../Livewire/⚡reset-password.blade.php | 37 ++++++++--- config/auth.php | 9 +++ ...014_create_password_setup_tokens_table.php | 25 ++++++++ docs/maarittely.md | 2 + lang/fi/users.php | 6 +- .../Modules/Users/CreateAdminCommandTest.php | 4 +- .../Modules/Users/PasswordResetTest.php | 64 +++++++++++++++++++ .../Modules/Users/UserManagementTest.php | 8 +-- 14 files changed, 223 insertions(+), 35 deletions(-) create mode 100644 app/Modules/Users/Infrastructure/Auth/PasswordLinkMail.php create mode 100644 app/Modules/Users/Infrastructure/Auth/PasswordSetupLinkNotification.php create mode 100644 database/migrations/2026_11_23_154014_create_password_setup_tokens_table.php diff --git a/CLAUDE.md b/CLAUDE.md index 1120083..8ebf5ba 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -23,7 +23,7 @@ Read `docs/architecture.md` (Finnish) before adding or changing domain code. `ap - **Presentation** is Livewire SFC pages in `Presentation/Livewire` (`::page`), Livewire Form objects for input validation, and `Presentation/Routes/web.php`. Pages call use cases and query contracts, and turn domain exceptions into field errors with translated messages. - Modules talk only through another module's Application contracts or events, never its Infrastructure or Eloquent models. Exceptions: `App\Models\User` (Laravel's auth model, owned by `Users`) is used through `auth()`/Gate, and `Users\Domain\Enums\Role` may be used in any module's Gate rules. - **Authorization:** define abilities with `Gate::define` in the owning module's provider (`users.manage`, `customers.use`). Protect routes with `can:` and also call `$this->authorize()` in each Livewire page's `mount()` and in every action. Mark record ids on Livewire pages `#[Locked]`. -- **Login** is the `Users` module: `Auth::attemptWhen` with `CheckLoginAllowed` (active, intern's last day not passed), and the `EnsureAccountIsUsable` web middleware ends sessions of users who are no longer allowed in. Nobody handles passwords: new users and "forgot password" get the same emailed set-password link, and when an admin creates a user or asks for a new link, the link is also shown to the admin to copy. Passwords need 12+ characters with mixed case, a number and a symbol (`Password::defaults` in `UsersServiceProvider`). +- **Login** is the `Users` module: `Auth::attemptWhen` with `CheckLoginAllowed` (active, intern's last day not passed), and the `EnsureAccountIsUsable` web middleware ends sessions of users who are no longer allowed in. Nobody handles passwords: new users and "forgot password" get the same emailed set-password link, and when an admin creates a user or asks for a new link, the link is also shown to the admin to copy. Admin links use the `admin_links` broker (own table, valid 72 h); forgot-password links use the default broker (60 min); the reset page accepts both, and using or issuing a link ends the user's earlier links. `AuthenticateSession` ends a user's other sessions when the password changes. Passwords need 12+ characters with mixed case, a number and a symbol (`Password::defaults` in `UsersServiceProvider`). - `tests/Unit/ArchitectureTest.php` enforces these rules for every module. Domain and Application files declare `strict_types=1`. Test domain rules and use cases in `tests/Unit` without Laravel (fakes in `tests/Fakes`), and repositories and pages in `tests/Feature`. - Generate module files with Artisan, then edit them: `php artisan make:class Modules////` for classes, `make:test --pest [--unit] Modules//Test` for tests, `make:migration` for migrations. Add `declare(strict_types=1);` to Domain and Application files. - When writing PHP through a bash heredoc, `\\` can collapse to `\`, and `"App\Modules\{$x}"` then stops interpolating. Write PHP files with the Write tool. diff --git a/app/Modules/Users/Infrastructure/Auth/LaravelPasswordLinkSender.php b/app/Modules/Users/Infrastructure/Auth/LaravelPasswordLinkSender.php index de421a0..3a4292c 100644 --- a/app/Modules/Users/Infrastructure/Auth/LaravelPasswordLinkSender.php +++ b/app/Modules/Users/Infrastructure/Auth/LaravelPasswordLinkSender.php @@ -12,13 +12,21 @@ use LogicException; use Symfony\Component\Mailer\Exception\TransportExceptionInterface; /** - * Uses Laravel's password reset tokens and notification, which the Users - * module provider words as a "set your password" email. + * Uses Laravel's password reset tokens. Forgot-password links use the + * default broker (60 minutes); links made by an admin use the admin_links + * broker, which has its own table and a longer expiry. */ class LaravelPasswordLinkSender implements PasswordLinkSender { + public const string ADMIN_BROKER = 'admin_links'; + public function __construct(private PasswordBroker $passwords) {} + public static function adminLinkHours(): int + { + return intdiv((int) config('auth.passwords.'.self::ADMIN_BROKER.'.expire'), 60); + } + public function sendSetupLink(EmailAddress $email): bool { try { @@ -37,7 +45,9 @@ class LaravelPasswordLinkSender implements PasswordLinkSender $user = User::query()->where('email', $email->value)->first() ?? throw new LogicException('A set-password link was asked for an unknown user.'); - $token = Password::createToken($user); + // The new link replaces every earlier link of the user. + Password::broker()->deleteToken($user); + $token = Password::broker(self::ADMIN_BROKER)->createToken($user); $url = route('password.reset', [ 'token' => $token, @@ -45,7 +55,7 @@ class LaravelPasswordLinkSender implements PasswordLinkSender ]); try { - $user->sendPasswordResetNotification($token); + $user->notify(new PasswordSetupLinkNotification($token)); $emailSent = true; } catch (TransportExceptionInterface $exception) { // The admin still gets the link to hand over another way. diff --git a/app/Modules/Users/Infrastructure/Auth/PasswordLinkMail.php b/app/Modules/Users/Infrastructure/Auth/PasswordLinkMail.php new file mode 100644 index 0000000..8ba5f61 --- /dev/null +++ b/app/Modules/Users/Infrastructure/Auth/PasswordLinkMail.php @@ -0,0 +1,28 @@ +subject(__('users.password_mail.subject')) + ->greeting(__('users.password_mail.greeting')) + ->line(__('users.password_mail.intro')) + ->action(__('users.password_mail.action'), route('password.reset', [ + 'token' => $token, + 'email' => $user->getEmailForPasswordReset(), + ])) + ->line($expiryLine) + ->line(__('users.password_mail.ignore')) + ->salutation(config('app.name')); + } +} diff --git a/app/Modules/Users/Infrastructure/Auth/PasswordSetupLinkNotification.php b/app/Modules/Users/Infrastructure/Auth/PasswordSetupLinkNotification.php new file mode 100644 index 0000000..f564c47 --- /dev/null +++ b/app/Modules/Users/Infrastructure/Auth/PasswordSetupLinkNotification.php @@ -0,0 +1,31 @@ + + */ + public function via(object $notifiable): array + { + return ['mail']; + } + + public function toMail(CanResetPassword $notifiable): MailMessage + { + return PasswordLinkMail::build($notifiable, $this->token, __('users.password_mail.expires_hours', [ + 'count' => LaravelPasswordLinkSender::adminLinkHours(), + ])); + } +} diff --git a/app/Modules/Users/Infrastructure/Providers/UsersServiceProvider.php b/app/Modules/Users/Infrastructure/Providers/UsersServiceProvider.php index 9d36af6..578cc6f 100644 --- a/app/Modules/Users/Infrastructure/Providers/UsersServiceProvider.php +++ b/app/Modules/Users/Infrastructure/Providers/UsersServiceProvider.php @@ -8,14 +8,17 @@ use App\Modules\Users\Application\Contracts\PasswordLinkSender; use App\Modules\Users\Application\Contracts\UserAccountQueries; use App\Modules\Users\Domain\Contracts\UserAccountRepository; use App\Modules\Users\Infrastructure\Auth\LaravelPasswordLinkSender; +use App\Modules\Users\Infrastructure\Auth\PasswordLinkMail; use App\Modules\Users\Infrastructure\Persistence\Repositories\EloquentUserAccountQueries; use App\Modules\Users\Infrastructure\Persistence\Repositories\EloquentUserAccountRepository; use App\Modules\Users\Infrastructure\SystemClock; use App\Modules\Users\Presentation\Console\CreateAdminCommand; use App\Modules\Users\Presentation\Http\Middleware\EnsureAccountIsUsable; use Illuminate\Auth\Notifications\ResetPassword; +use Illuminate\Contracts\Auth\CanResetPassword; use Illuminate\Notifications\Messages\MailMessage; use Illuminate\Routing\Router; +use Illuminate\Session\Middleware\AuthenticateSession; use Illuminate\Support\Facades\Gate; use Illuminate\Support\ServiceProvider; use Illuminate\Validation\Rules\Password; @@ -53,6 +56,9 @@ class UsersServiceProvider extends ServiceProvider $router->pushMiddlewareToGroup('web', EnsureAccountIsUsable::class); + // Ends the user's other sessions when their password changes. + $router->pushMiddlewareToGroup('web', AuthenticateSession::class); + if ($this->app->runningInConsole()) { $this->commands([CreateAdminCommand::class]); } @@ -61,16 +67,10 @@ class UsersServiceProvider extends ServiceProvider Password::defaults(fn () => Password::min(12)->mixedCase()->numbers()->symbols()); - ResetPassword::toMailUsing(fn (object $notifiable, string $token): MailMessage => (new MailMessage) - ->subject(__('users.password_mail.subject')) - ->greeting(__('users.password_mail.greeting')) - ->line(__('users.password_mail.intro')) - ->action(__('users.password_mail.action'), route('password.reset', [ - 'token' => $token, - 'email' => $notifiable->getEmailForPasswordReset(), - ])) - ->line(__('users.password_mail.expires', ['count' => config('auth.passwords.users.expire')])) - ->line(__('users.password_mail.ignore')) - ->salutation(config('app.name'))); + ResetPassword::toMailUsing(fn (CanResetPassword $notifiable, string $token): MailMessage => PasswordLinkMail::build( + $notifiable, + $token, + __('users.password_mail.expires', ['count' => config('auth.passwords.users.expire')]), + )); } } diff --git a/app/Modules/Users/Presentation/Livewire/⚡form.blade.php b/app/Modules/Users/Presentation/Livewire/⚡form.blade.php index 6b1dfd9..8f108bd 100644 --- a/app/Modules/Users/Presentation/Livewire/⚡form.blade.php +++ b/app/Modules/Users/Presentation/Livewire/⚡form.blade.php @@ -204,7 +204,7 @@ new class extends Component Str::lower(trim($this->email)), - 'password' => $this->password, - 'password_confirmation' => $this->password_confirmation, - 'token' => $this->token, - ], - function ($user, string $password): void { + $credentials = [ + 'email' => Str::lower(trim($this->email)), + 'password' => $this->password, + 'password_confirmation' => $this->password_confirmation, + 'token' => $this->token, + ]; + + // A forgot-password link (60 min) or a link made by an admin (72 h); + // each kind has its own broker. Using a link ends every other link. + foreach (self::BROKERS as $broker) { + $status = Password::broker($broker)->reset($credentials, function ($user, string $password): void { + foreach (self::BROKERS as $anyBroker) { + Password::broker($anyBroker)->deleteToken($user); + } + $user->forceFill(['password' => $password, 'remember_token' => Str::random(60)])->save(); event(new PasswordReset($user)); - }, - ); + }); + + if ($status !== Password::INVALID_TOKEN) { + break; + } + } if ($status !== Password::PASSWORD_RESET) { $this->reset('password', 'password_confirmation'); diff --git a/config/auth.php b/config/auth.php index d7568ff..4c216ed 100644 --- a/config/auth.php +++ b/config/auth.php @@ -99,6 +99,15 @@ return [ 'expire' => 60, 'throttle' => 60, ], + + // Set-password links made by an admin, who may hand them over by + // hand. Own table, so they never overwrite forgot-password tokens. + 'admin_links' => [ + 'provider' => 'users', + 'table' => 'password_setup_tokens', + 'expire' => 72 * 60, + 'throttle' => 0, + ], ], /* diff --git a/database/migrations/2026_11_23_154014_create_password_setup_tokens_table.php b/database/migrations/2026_11_23_154014_create_password_setup_tokens_table.php new file mode 100644 index 0000000..5677228 --- /dev/null +++ b/database/migrations/2026_11_23_154014_create_password_setup_tokens_table.php @@ -0,0 +1,25 @@ +string('email')->primary(); + $table->string('token'); + $table->timestamp('created_at')->nullable(); + }); + } + + public function down(): void + { + Schema::dropIfExists('password_setup_tokens'); + } +}; diff --git a/docs/maarittely.md b/docs/maarittely.md index 1de2b4b..d88e7df 100644 --- a/docs/maarittely.md +++ b/docs/maarittely.md @@ -80,6 +80,8 @@ Nimi, sähköposti, rooli (yksi per käyttäjä, *K13*), aktiivinen, harjoitteli - **Uusi käyttäjä**: pääkäyttäjä luo käyttäjän; linkki lähetetään sähköpostiin ja näytetään pääkäyttäjälle kopioitavana, jotta hän voi toimittaa sen muuta kautta. - **Pääkäyttäjän luoma nollauslinkki**: sama kuin edellä olemassa olevalle käyttäjälle. - **Unohtuiko salasana** -linkki kirjautumissivulla: käyttäjä tilaa linkin sähköpostiinsa. Sivu ei paljasta, onko osoite olemassa. +- Pääkäyttäjän luoma linkki on voimassa 72 tuntia, "Unohtuiko salasana" -linkki 60 minuuttia. Linkki on kertakäyttöinen, ja uusi linkki mitätöi aiemmat. +- Kun salasana vaihdetaan, käyttäjän muut istunnot (muut laitteet, "muista minut") päättyvät. - Ei-aktiivinen käyttäjä ja harjoittelija päättymispäivän jälkeen eivät voi kirjautua, ja heidän voimassa olevat istuntonsa päättyvät. ## 4. Asiakas *(K16, K17)* diff --git a/lang/fi/users.php b/lang/fi/users.php index e750fde..5ad8d8c 100644 --- a/lang/fi/users.php +++ b/lang/fi/users.php @@ -23,10 +23,11 @@ return [ 'link_mail_failed' => 'Uusi linkki luotu, mutta sen lähetys sähköpostiin epäonnistui. Kopioi linkki alta ja toimita se käyttäjälle.', 'setup_link' => [ 'label' => 'Salasanan asetuslinkki', - 'hint' => 'Linkki on kertakäyttöinen ja voimassa :count minuuttia. Toimita se vain käyttäjälle itselleen.', + 'hint' => 'Linkki on kertakäyttöinen ja voimassa :count tuntia. Toimita se vain käyttäjälle itselleen.', 'copy' => 'Kopioi linkki', 'copied' => 'Linkki kopioitu leikepöydälle.', - 'copy_failed' => 'Kopiointi ei onnistunut. Linkki on valittuna: kopioi se näppäinyhdistelmällä Ctrl+C.', ], + 'copy_failed' => 'Kopiointi ei onnistunut. Linkki on valittuna: kopioi se näppäinyhdistelmällä Ctrl+C.', + ], 'fields' => [ 'name' => 'Nimi', @@ -77,6 +78,7 @@ return [ 'intro' => 'Voit asettaa salasanan toiminnanohjausjärjestelmän käyttäjätunnuksellesi alla olevasta painikkeesta.', 'action' => 'Aseta salasana', 'expires' => 'Linkki on voimassa :count minuuttia.', + 'expires_hours' => 'Linkki on voimassa :count tuntia.', 'ignore' => 'Jos et odottanut tätä viestiä, sinun ei tarvitse tehdä mitään.', ], ]; diff --git a/tests/Feature/Modules/Users/CreateAdminCommandTest.php b/tests/Feature/Modules/Users/CreateAdminCommandTest.php index 6a79d98..193e532 100644 --- a/tests/Feature/Modules/Users/CreateAdminCommandTest.php +++ b/tests/Feature/Modules/Users/CreateAdminCommandTest.php @@ -2,7 +2,7 @@ use App\Models\User; use App\Modules\Users\Domain\Enums\Role; -use Illuminate\Auth\Notifications\ResetPassword; +use App\Modules\Users\Infrastructure\Auth\PasswordSetupLinkNotification; use Illuminate\Foundation\Testing\RefreshDatabase; use Illuminate\Support\Facades\Notification; @@ -20,7 +20,7 @@ it('creates an admin, emails a set-password link and prints it', function () { expect($admin->role)->toBe(Role::Admin) ->and($admin->email)->toBe('anna@example.test'); - Notification::assertSentTo($admin, ResetPassword::class); + Notification::assertSentTo($admin, PasswordSetupLinkNotification::class); }); it('fails for an email address that is in use', function () { diff --git a/tests/Feature/Modules/Users/PasswordResetTest.php b/tests/Feature/Modules/Users/PasswordResetTest.php index 269806e..fc8f574 100644 --- a/tests/Feature/Modules/Users/PasswordResetTest.php +++ b/tests/Feature/Modules/Users/PasswordResetTest.php @@ -6,6 +6,8 @@ use Illuminate\Foundation\Testing\RefreshDatabase; use Illuminate\Support\Facades\Hash; use Illuminate\Support\Facades\Notification; use Illuminate\Support\Facades\Password; +use Illuminate\Support\Str; +use Livewire\Features\SupportTesting\Testable; use Livewire\Livewire; uses(RefreshDatabase::class); @@ -123,3 +125,65 @@ it('rejects a short password and an invalid link', function () { expect(Hash::check('password', $user->fresh()->password))->toBeTrue(); }); + +/** + * Sets the user's password through the reset page with the given token. + */ +function setPasswordWithToken(string $token, string $email = 'eero@example.test'): Testable +{ + return Livewire::test('users::reset-password', ['token' => $token]) + ->set('email', $email) + ->set('password', 'Uusi-salasana-123') + ->set('password_confirmation', 'Uusi-salasana-123') + ->call('resetPassword'); +} + +it('accepts a link made by an admin for 72 hours, but a forgot-password link only for 60 minutes', function (string $broker, int $minutes, bool $valid) { + $user = User::factory()->create(['email' => 'eero@example.test']); + $token = Password::broker($broker)->createToken($user); + + $this->travel($minutes)->minutes(); + + $reset = setPasswordWithToken($token); + + $valid ? $reset->assertHasNoErrors() : $reset->assertHasErrors(['email']); + expect(Hash::check('Uusi-salasana-123', $user->fresh()->password))->toBe($valid); +})->with([ + 'admin link after 2 hours' => ['admin_links', 120, true], + 'admin link after 73 hours' => ['admin_links', 73 * 60, false], + 'forgot-password link after 59 minutes' => ['users', 59, true], + 'forgot-password link after 61 minutes' => ['users', 61, false], +]); + +it('ends earlier links when an admin makes a new one, and every link when one is used', function () { + Notification::fake(); + $admin = User::factory()->admin()->create(); + $user = User::factory()->create(['email' => 'eero@example.test']); + $forgotToken = Password::createToken($user); + + $page = Livewire::actingAs($admin)->test('users::form', ['user' => $user->id])->call('sendPasswordLink'); + $adminToken = Str::between($page->get('setupLink'), '/reset-password/', '?'); + + expect(Password::tokenExists($user, $forgotToken))->toBeFalse(); + + auth()->logout(); + setPasswordWithToken($adminToken)->assertHasNoErrors(); + expect(Password::broker('admin_links')->tokenExists($user, $adminToken))->toBeFalse(); + + $newForgotToken = Password::createToken($user); + $newAdminToken = Password::broker('admin_links')->createToken($user); + setPasswordWithToken($newForgotToken)->assertHasNoErrors(); + + expect(Password::broker('admin_links')->tokenExists($user, $newAdminToken))->toBeFalse(); +}); + +it('ends the other sessions of a user whose password changes', function () { + $user = User::factory()->create(['email' => 'eero@example.test']); + + $this->actingAs($user)->get(route('home'))->assertOk(); + + $user->forceFill(['password' => 'Uusi-salasana-123'])->save(); + + $this->get(route('home'))->assertRedirect(route('login')); + $this->assertGuest(); +}); diff --git a/tests/Feature/Modules/Users/UserManagementTest.php b/tests/Feature/Modules/Users/UserManagementTest.php index 997d68a..b29de36 100644 --- a/tests/Feature/Modules/Users/UserManagementTest.php +++ b/tests/Feature/Modules/Users/UserManagementTest.php @@ -2,7 +2,7 @@ use App\Models\User; use App\Modules\Users\Domain\Enums\Role; -use Illuminate\Auth\Notifications\ResetPassword; +use App\Modules\Users\Infrastructure\Auth\PasswordSetupLinkNotification; use Illuminate\Foundation\Testing\RefreshDatabase; use Illuminate\Support\Facades\Notification; use Illuminate\Support\Facades\Password; @@ -68,7 +68,7 @@ it('creates an intern, emails a set-password link and shows it to copy', functio ->and($intern->employment_ends_on?->toDateString())->toBe('2027-05-31') ->and($intern->supervisor_id)->toBe($supervisor->id); - Notification::assertSentTo($intern, ResetPassword::class, function (ResetPassword $notification) use ($component) { + Notification::assertSentTo($intern, PasswordSetupLinkNotification::class, function (PasswordSetupLinkNotification $notification) use ($component) { return str_contains($component->get('setupLink'), '/reset-password/'.$notification->token); }); }); @@ -154,8 +154,8 @@ it('makes a new set-password link on the edit page, also right after an earlier $token = Str::between($component->get('setupLink'), '/reset-password/', '?'); - Notification::assertSentToTimes($user, ResetPassword::class, 2); - expect(Password::tokenExists($user, $token))->toBeTrue(); + Notification::assertSentToTimes($user, PasswordSetupLinkNotification::class, 2); + expect(Password::broker('admin_links')->tokenExists($user, $token))->toBeTrue(); }); it('does not let the set-password link be changed in the browser', function () {