Add structured specification and show set-password links to admins

The customer answered the open questions in määrittely.txt. Collect the
answers into docs/maarittely.md: roles and permission table, money
visibility, customer job fields and enum keys, Kanban, tasks, time
entries, expenses, pricing, Fennoa billing export, data model, revised
phases with phase 1 in detail, and remaining open questions. CLAUDE.md
now points to it.

Apply the answers that change the Users module:
- Passwords need 12+ characters with mixed case, a number and a symbol,
  with a Finnish message for each rule.
- When an admin creates a user or asks for a new link, the set-password
  link is emailed and also shown to the admin to copy, even if the email
  fails. The link lives only in the page state. users:create-admin
  prints it too. Self-service "forgot password" stays as it was.
- The copy field uses x-input + x-button with a status message, because
  x-clipboard has an unlabelled input and a changing button name.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
2026-11-23 17:22:43 +02:00
co-authored by Claude Opus 5.5
parent cfbabcd268
commit 246e806c1c
22 changed files with 793 additions and 134 deletions
@@ -4,17 +4,26 @@ declare(strict_types=1);
namespace App\Modules\Users\Application\Contracts;
use App\Modules\Users\Application\DTOs\IssuedSetupLink;
use App\Modules\Users\Domain\ValueObjects\EmailAddress;
/**
* Emails a link for setting a new password. New users get the same link
* to set their first password.
* Makes and emails links for setting a new password. New users get the same
* link to set their first password.
*/
interface PasswordLinkSender
{
/**
* Emails a link when a user asks for one on the login page.
*
* @return bool False when the link was not sent: one was sent to this
* address too recently, or the mail could not be delivered.
*/
public function sendSetupLink(EmailAddress $email): bool;
/**
* Makes a new link for an admin to copy and also emails it to the user.
* Not throttled, and it replaces any earlier link of the user.
*/
public function issueSetupLink(EmailAddress $email): IssuedSetupLink;
}
@@ -5,13 +5,13 @@ declare(strict_types=1);
namespace App\Modules\Users\Application\DTOs;
/**
* Result of creating a user. The user exists even when the set-password
* link could not be sent; it can then be resent from the edit page.
* Result of creating a user, with the set-password link for the admin.
* The user exists even when the link could not be emailed.
*/
final readonly class CreatedUserAccount
{
public function __construct(
public int $userId,
public bool $setupLinkSent,
public IssuedSetupLink $setupLink,
) {}
}
@@ -0,0 +1,17 @@
<?php
declare(strict_types=1);
namespace App\Modules\Users\Application\DTOs;
/**
* A set-password link made for an admin to hand over. The same link is
* emailed to the user; the admin can copy it when the email does not arrive.
*/
final readonly class IssuedSetupLink
{
public function __construct(
public string $url,
public bool $emailSent,
) {}
}
@@ -17,8 +17,9 @@ use App\Modules\Users\Domain\ValueObjects\EmailAddress;
use App\Modules\Users\Domain\ValueObjects\PersonName;
/**
* Creates a user and emails a link for setting the first password, so
* nobody handles the password in plain text.
* Creates a user and makes a link for setting the first password, which is
* emailed and returned for the admin to copy, so nobody handles the
* password in plain text.
*/
final class CreateUserAccount
{
@@ -53,6 +54,6 @@ final class CreateUserAccount
return (int) $this->users->save($user)->id();
});
return new CreatedUserAccount($userId, $this->passwordLinks->sendSetupLink($user->email()));
return new CreatedUserAccount($userId, $this->passwordLinks->issueSetupLink($user->email()));
}
}
@@ -5,11 +5,13 @@ declare(strict_types=1);
namespace App\Modules\Users\Application\UseCases;
use App\Modules\Users\Application\Contracts\PasswordLinkSender;
use App\Modules\Users\Application\DTOs\IssuedSetupLink;
use App\Modules\Users\Domain\Contracts\UserAccountRepository;
use App\Modules\Users\Domain\Exceptions\UserAccountNotFound;
/**
* An admin sends a user a link for setting a new password.
* An admin makes a user a new link for setting the password. The link is
* emailed to the user and returned for the admin to copy.
*/
final class SendPasswordSetupLink
{
@@ -19,14 +21,12 @@ final class SendPasswordSetupLink
) {}
/**
* @return bool False when a link was sent to the user too recently.
*
* @throws UserAccountNotFound
*/
public function execute(int $userId): bool
public function execute(int $userId): IssuedSetupLink
{
$user = $this->users->findById($userId) ?? throw new UserAccountNotFound($userId);
return $this->passwordLinks->sendSetupLink($user->email());
return $this->passwordLinks->issueSetupLink($user->email());
}
}
@@ -2,14 +2,18 @@
namespace App\Modules\Users\Infrastructure\Auth;
use App\Models\User;
use App\Modules\Users\Application\Contracts\PasswordLinkSender;
use App\Modules\Users\Application\DTOs\IssuedSetupLink;
use App\Modules\Users\Domain\ValueObjects\EmailAddress;
use Illuminate\Contracts\Auth\PasswordBroker;
use Illuminate\Support\Facades\Password;
use LogicException;
use Symfony\Component\Mailer\Exception\TransportExceptionInterface;
/**
* Sends Laravel's password reset notification, which the Users module
* provider words as a "set your password" email.
* Uses Laravel's password reset tokens and notification, which the Users
* module provider words as a "set your password" email.
*/
class LaravelPasswordLinkSender implements PasswordLinkSender
{
@@ -27,4 +31,28 @@ class LaravelPasswordLinkSender implements PasswordLinkSender
return false;
}
}
public function issueSetupLink(EmailAddress $email): IssuedSetupLink
{
$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);
$url = route('password.reset', [
'token' => $token,
'email' => $user->getEmailForPasswordReset(),
]);
try {
$user->sendPasswordResetNotification($token);
$emailSent = true;
} catch (TransportExceptionInterface $exception) {
// The admin still gets the link to hand over another way.
report($exception);
$emailSent = false;
}
return new IssuedSetupLink($url, $emailSent);
}
}
@@ -59,7 +59,7 @@ class UsersServiceProvider extends ServiceProvider
Gate::define('users.manage', fn (User $user): bool => $user->role->canManageUsers());
Password::defaults(fn () => Password::min(12));
Password::defaults(fn () => Password::min(12)->mixedCase()->numbers()->symbols());
ResetPassword::toMailUsing(fn (object $notifiable, string $token): MailMessage => (new MailMessage)
->subject(__('users.password_mail.subject'))
@@ -11,7 +11,7 @@ use Illuminate\Console\Attributes\Signature;
use Illuminate\Console\Command;
#[Signature('users:create-admin {name : Full name} {email : Login email address}')]
#[Description('Create an admin user and email them a link for setting their password')]
#[Description('Create an admin user, email them a link for setting their password and print the link')]
class CreateAdminCommand extends Command
{
public function handle(CreateUserAccount $createUserAccount): int
@@ -28,17 +28,13 @@ class CreateAdminCommand extends Command
return self::FAILURE;
}
if (! $created->setupLinkSent) {
$this->components->warn('Admin created, but the set-password email could not be sent (see the log). Fix the mail settings and use "Unohditko salasanan?" on the login page.');
return self::SUCCESS;
if ($created->setupLink->emailSent) {
$this->components->info('Admin created. A link for setting the password was emailed to '.$this->argument('email').'.');
} else {
$this->components->warn('Admin created, but the set-password email could not be sent (see the log).');
}
$this->components->info('Admin created. A link for setting the password was emailed to '.$this->argument('email').'.');
if (config('mail.default') === 'log') {
$this->components->warn('MAIL_MAILER=log: find the link in storage/logs/laravel.log.');
}
$this->components->twoColumnDetail('Set-password link', $created->setupLink->url);
return self::SUCCESS;
}
@@ -25,6 +25,13 @@ new class extends Component
public string $linkStatus = '';
/**
* The latest set-password link, shown to the admin to copy. It lives only
* in this page's state, never in the session or the database.
*/
#[Locked]
public string $setupLink = '';
public function mount(UserAccountQueries $userQueries, ?int $user = null): void
{
$this->authorize('users.manage');
@@ -55,14 +62,11 @@ new class extends Component
$this->authorize('users.manage');
$data = $this->form->toData();
$created = null;
try {
if ($this->userId === null) {
$created = $createUser->execute($data);
session()->flash('status', __(
$created->setupLinkSent ? 'users.created' : 'users.created_link_failed',
['name' => $data->name],
));
} else {
$updateUser->execute($this->userId, $data);
session()->flash('status', __('users.updated', ['name' => $data->name]));
@@ -75,6 +79,20 @@ new class extends Component
return;
}
if ($created !== null) {
// Stay on the page so the admin can copy the link; it becomes
// the new user's edit page.
$this->userId = $created->userId;
$this->setupLink = $created->setupLink->url;
$this->linkStatus = __(
$created->setupLink->emailSent ? 'users.created' : 'users.created_link_failed',
['name' => $data->name, 'email' => $data->email],
);
$this->js('history.replaceState(history.state, "", '.json_encode(route('users.edit', $created->userId)).')');
return;
}
$this->redirectRoute('users.index', navigate: true);
}
@@ -85,14 +103,15 @@ new class extends Component
abort_if($this->userId === null, 404);
try {
$sent = $sendLink->execute($this->userId);
$link = $sendLink->execute($this->userId);
} catch (UserAccountNotFound) {
abort(404);
}
$this->linkStatus = $sent
$this->setupLink = $link->url;
$this->linkStatus = $link->emailSent
? __('users.link_sent', ['email' => $this->form->email])
: __('users.link_throttled');
: __('users.link_mail_failed');
}
public function render(): mixed
@@ -155,13 +174,48 @@ new class extends Component
@if ($userId !== null)
<div class="space-y-3 border-t border-zinc-200 pt-6 dark:border-zinc-700">
<x-button wire:click="sendPasswordLink" subtle color="black" icon="envelope" :text="__('users.send_link')" />
<x-button wire:click="sendPasswordLink" subtle color="black" icon="link" :text="__('users.send_link')" />
<div role="status" aria-live="polite">
@if ($linkStatus !== '')
<p class="text-sm">{{ $linkStatus }}</p>
@endif
</div>
@if ($setupLink !== '')
<div
wire:key="setup-link-{{ md5($setupLink) }}"
x-data="{
message: '',
async copyLink() {
try {
await navigator.clipboard.writeText($refs.setupLink.value);
this.message = @js(__('users.setup_link.copied'));
} catch (error) {
$refs.setupLink.focus();
$refs.setupLink.select();
this.message = @js(__('users.setup_link.copy_failed'));
}
},
}"
class="space-y-3"
>
{{-- Without wire:model, TallStackUI ties the label to the input only through an explicit id. --}}
<x-input
id="setup-link"
:label="__('users.setup_link.label')"
:hint="__('users.setup_link.hint', ['count' => config('auth.passwords.users.expire')])"
:value="$setupLink"
x-ref="setupLink"
x-on:focus="$el.select()"
readonly
/>
<x-button x-on:click="copyLink()" subtle color="black" icon="clipboard-document" :text="__('users.setup_link.copy')" />
<p role="status" aria-live="polite" class="text-sm" x-text="message"></p>
</div>
@endif
</div>
@endif
</div>
@@ -37,6 +37,9 @@ new class extends Component
'password.required' => __('auth.password_required'),
'password.confirmed' => __('auth.password_mismatch'),
'password.min' => __('auth.password_too_short', ['min' => 12]),
'password.password.mixed' => __('auth.password_needs_mixed_case'),
'password.password.numbers' => __('auth.password_needs_number'),
'password.password.symbols' => __('auth.password_needs_symbol'),
],
);