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 <[email protected]>
This commit is contained in:
2026-11-23 17:42:37 +02:00
co-authored by Claude Opus 5.5
parent 9af0641e17
commit 8dfc02c4e5
14 changed files with 223 additions and 35 deletions
+1 -1
View File
@@ -23,7 +23,7 @@ Read `docs/architecture.md` (Finnish) before adding or changing domain code. `ap
- **Presentation** is Livewire SFC pages in `Presentation/Livewire` (`<module>::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/<Module>/<Layer>/<Folder>/<Name>` for classes, `make:test --pest [--unit] Modules/<Module>/<Name>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.
@@ -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.
@@ -0,0 +1,28 @@
<?php
namespace App\Modules\Users\Infrastructure\Auth;
use Illuminate\Contracts\Auth\CanResetPassword;
use Illuminate\Notifications\Messages\MailMessage;
/**
* The "set your password" email, shared by forgot-password links and links
* made by an admin. Only the expiry line differs.
*/
final class PasswordLinkMail
{
public static function build(CanResetPassword $user, string $token, string $expiryLine): MailMessage
{
return (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' => $user->getEmailForPasswordReset(),
]))
->line($expiryLine)
->line(__('users.password_mail.ignore'))
->salutation(config('app.name'));
}
}
@@ -0,0 +1,31 @@
<?php
namespace App\Modules\Users\Infrastructure\Auth;
use Illuminate\Contracts\Auth\CanResetPassword;
use Illuminate\Notifications\Messages\MailMessage;
use Illuminate\Notifications\Notification;
/**
* Emails a set-password link made by an admin. It is valid longer than a
* forgot-password link, because the admin may also hand it over by hand.
*/
class PasswordSetupLinkNotification extends Notification
{
public function __construct(public string $token) {}
/**
* @return list<string>
*/
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(),
]));
}
}
@@ -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')]),
));
}
}
@@ -204,7 +204,7 @@ new class extends Component
<x-input
id="setup-link"
:label="__('users.setup_link.label')"
:hint="__('users.setup_link.hint', ['count' => config('auth.passwords.users.expire')])"
:hint="__('users.setup_link.hint', ['count' => intdiv((int) config('auth.passwords.admin_links.expire'), 60)])"
:value="$setupLink"
x-ref="setupLink"
x-on:focus="$el.select()"
@@ -9,6 +9,12 @@ use Livewire\Component;
new class extends Component
{
/**
* Password brokers in config/auth.php: forgot-password links, then links
* made by an admin.
*/
private const array BROKERS = ['users', 'admin_links'];
#[Locked]
public string $token = '';
@@ -43,19 +49,30 @@ new class extends Component
],
);
$status = Password::reset(
[
'email' => 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');
+9
View File
@@ -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,
],
],
/*
@@ -0,0 +1,25 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Tokens of set-password links made by an admin (the admin_links broker).
*/
public function up(): void
{
Schema::create('password_setup_tokens', function (Blueprint $table) {
$table->string('email')->primary();
$table->string('token');
$table->timestamp('created_at')->nullable();
});
}
public function down(): void
{
Schema::dropIfExists('password_setup_tokens');
}
};
+2
View File
@@ -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)*
+4 -2
View File
@@ -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.',
],
];
@@ -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('[email protected]');
Notification::assertSentTo($admin, ResetPassword::class);
Notification::assertSentTo($admin, PasswordSetupLinkNotification::class);
});
it('fails for an email address that is in use', function () {
@@ -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 = '[email protected]'): 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' => '[email protected]']);
$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' => '[email protected]']);
$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' => '[email protected]']);
$this->actingAs($user)->get(route('home'))->assertOk();
$user->forceFill(['password' => 'Uusi-salasana-123'])->save();
$this->get(route('home'))->assertRedirect(route('login'));
$this->assertGuest();
});
@@ -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 () {