Add login, password reset and user management (Users module)

New Users module with the four layers:
- Domain: Role enum, UserAccount entity (intern needs end date and
  supervisor, login allowed until the end of the last day), email and
  name value objects, SupervisorRule, last-admin protection.
- Application: CreateUserAccount (emails a set-password link),
  UpdateUserAccount, SendPasswordSetupLink, CheckLoginAllowed, query
  contract and Clock (business time zone Europe/Helsinki).
- Infrastructure: users table gets role, is_active, employment_ends_on
  and supervisor_id; Eloquent repository and queries; Password broker
  link sender with a Finnish email; Gate users.manage.
- Presentation: Livewire login (rate limited), forgot and reset
  password pages, logout, EnsureAccountIsUsable middleware that ends
  sessions of deactivated users, admin-only user list and form, and
  users:create-admin command.

Also:
- Layout gets a labelled main menu, the signed-in user and logout.
- Remove the local /dev/login; guests are redirected to /login.
- Customers: customers.use ability (no subcontractors), authorization
  in mount and save, locked customerId, 404 for a missing customer,
  empty-state check uses the total count.
- Architecture test lets module providers register their own
  Presentation classes; docs and CLAUDE.md updated.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
2026-11-22 11:03:00 +02:00
co-authored by Claude Opus 5.5
parent 73d535278d
commit 8c7cb9e3b4
76 changed files with 2978 additions and 62 deletions
@@ -0,0 +1,118 @@
<?php
namespace App\Modules\Users\Presentation\Livewire\Forms;
use App\Modules\Shared\Domain\Exceptions\DomainException;
use App\Modules\Users\Application\DTOs\UserAccountData;
use App\Modules\Users\Application\DTOs\UserSummary;
use App\Modules\Users\Domain\Enums\Role;
use App\Modules\Users\Domain\Exceptions\EmailAlreadyInUse;
use App\Modules\Users\Domain\Exceptions\InternRequiresEndDateAndSupervisor;
use App\Modules\Users\Domain\Exceptions\InvalidEmailAddress;
use App\Modules\Users\Domain\Exceptions\InvalidPersonName;
use App\Modules\Users\Domain\Exceptions\InvalidSupervisor;
use App\Modules\Users\Domain\Exceptions\LastAdminCannotBeRemoved;
use Illuminate\Validation\Rule;
use Livewire\Form;
/**
* User details form shared by the create and edit pages. Validates the
* shape of the input; business rules come from the Domain and are shown as
* field errors by showDomainError().
*/
class UserForm extends Form
{
public string $name = '';
public string $email = '';
public string $role = Role::Employee->value;
public bool $active = true;
public string $employment_ends_on = '';
public string $supervisor_id = '';
public function fillFromSummary(UserSummary $user): void
{
$this->name = $user->name;
$this->email = $user->email;
$this->role = $user->role->value;
$this->active = $user->active;
$this->employment_ends_on = $user->employmentEndsOn ?? '';
$this->supervisor_id = $user->supervisorId === null ? '' : (string) $user->supervisorId;
}
public function isIntern(): bool
{
return $this->role === Role::Intern->value;
}
public function toData(): UserAccountData
{
$this->validate();
return UserAccountData::fromArray([
'name' => $this->name,
'email' => $this->email,
'role' => $this->role,
'active' => $this->active,
'employment_ends_on' => $this->isIntern() ? $this->employment_ends_on : null,
'supervisor_id' => $this->isIntern() ? $this->supervisor_id : null,
]);
}
/**
* Shows a broken business rule as an error on the field it concerns.
*/
public function showDomainError(DomainException $exception): void
{
[$field, $key] = match ($exception::class) {
InvalidPersonName::class => ['name', 'users.errors.invalid_name'],
InvalidEmailAddress::class => ['email', 'users.errors.invalid_email'],
EmailAlreadyInUse::class => ['email', 'users.errors.email_taken'],
InternRequiresEndDateAndSupervisor::class => ['supervisor_id', 'users.errors.supervisor_required'],
InvalidSupervisor::class => ['supervisor_id', 'users.errors.invalid_supervisor'],
LastAdminCannotBeRemoved::class => ['role', 'users.errors.last_admin'],
default => throw $exception,
};
$this->addError($field, __($key));
}
/**
* @return array<string, array<int, mixed>>
*/
protected function rules(): array
{
return [
'name' => ['required', 'string', 'max:255'],
'email' => ['required', 'string', 'email:filter', 'max:255'],
'role' => ['required', Rule::enum(Role::class)],
'active' => ['boolean'],
'employment_ends_on' => [Rule::requiredIf($this->isIntern()), 'nullable', 'date_format:Y-m-d'],
'supervisor_id' => [Rule::requiredIf($this->isIntern()), 'nullable', 'integer'],
];
}
/**
* @return array<string, string>
*/
protected function messages(): array
{
return [
'name.required' => __('users.errors.name_required'),
'name.max' => __('users.errors.invalid_name'),
'email.required' => __('users.errors.email_required'),
'email.email' => __('users.errors.invalid_email'),
'email.max' => __('users.errors.invalid_email'),
'role.required' => __('users.errors.role_required'),
'role.enum' => __('users.errors.role_required'),
'employment_ends_on.required' => __('users.errors.end_date_required'),
'employment_ends_on.date_format' => __('users.errors.end_date_invalid'),
'supervisor_id.required' => __('users.errors.supervisor_required'),
'supervisor_id.integer' => __('users.errors.invalid_supervisor'),
];
}
}
@@ -0,0 +1,55 @@
<?php
use App\Modules\Users\Application\Contracts\PasswordLinkSender;
use App\Modules\Users\Domain\ValueObjects\EmailAddress;
use Livewire\Component;
new class extends Component
{
public string $email = '';
public bool $linkRequested = false;
/**
* Shows the same message whether or not the address has an account, so
* the page cannot be used to find out which addresses are in use.
*/
public function sendLink(PasswordLinkSender $passwordLinks): void
{
$this->validate(
['email' => ['required', 'string', 'email:filter', 'max:255']],
['email.required' => __('auth.email_required'), 'email.email' => __('auth.email_invalid'), 'email.max' => __('auth.email_invalid')],
);
$passwordLinks->sendSetupLink(new EmailAddress($this->email));
$this->linkRequested = true;
}
public function render(): mixed
{
return $this->view()->title(__('auth.forgot_title'));
}
};
?>
<div class="mx-auto max-w-md space-y-6 p-4 sm:p-6 sm:pt-16">
<flux:heading size="xl" level="1">{{ __('auth.forgot_title') }}</flux:heading>
<div role="status" aria-live="polite">
@if ($linkRequested)
<flux:callout variant="success" icon="envelope" :heading="__('auth.forgot_sent')" />
@endif
</div>
<flux:text>{{ __('auth.forgot_intro') }}</flux:text>
<form wire:submit="sendLink" class="space-y-6" novalidate>
<flux:input wire:model="email" type="email" :label="__('auth.email')" autocomplete="username" required />
<div class="flex flex-wrap items-center justify-between gap-4">
<flux:button type="submit" variant="primary">{{ __('auth.forgot_submit') }}</flux:button>
<flux:link :href="route('login')" wire:navigate>{{ __('auth.back_to_login') }}</flux:link>
</div>
</form>
</div>
@@ -0,0 +1,161 @@
<?php
use App\Modules\Shared\Domain\Exceptions\DomainException;
use App\Modules\Users\Application\Contracts\UserAccountQueries;
use App\Modules\Users\Application\DTOs\UserOption;
use App\Modules\Users\Application\UseCases\CreateUserAccount;
use App\Modules\Users\Application\UseCases\SendPasswordSetupLink;
use App\Modules\Users\Application\UseCases\UpdateUserAccount;
use App\Modules\Users\Domain\Enums\Role;
use App\Modules\Users\Domain\Exceptions\UserAccountNotFound;
use App\Modules\Users\Presentation\Livewire\Forms\UserForm;
use Livewire\Attributes\Computed;
use Livewire\Attributes\Locked;
use Livewire\Component;
/**
* Create page (no route parameter) and edit page (with {user}).
*/
new class extends Component
{
#[Locked]
public ?int $userId = null;
public UserForm $form;
public string $linkStatus = '';
public function mount(UserAccountQueries $userQueries, ?int $user = null): void
{
$this->authorize('users.manage');
if ($user === null) {
return;
}
$summary = $userQueries->findSummary($user);
abort_if($summary === null, 404);
$this->userId = $summary->id;
$this->form->fillFromSummary($summary);
}
/**
* @return list<UserOption>
*/
#[Computed]
public function supervisorOptions(): array
{
return app(UserAccountQueries::class)->supervisorOptions($this->userId);
}
public function save(CreateUserAccount $createUser, UpdateUserAccount $updateUser): void
{
$this->authorize('users.manage');
$data = $this->form->toData();
try {
if ($this->userId === null) {
$createUser->execute($data);
session()->flash('status', __('users.created', ['name' => $data->name]));
} else {
$updateUser->execute($this->userId, $data);
session()->flash('status', __('users.updated', ['name' => $data->name]));
}
} catch (UserAccountNotFound) {
abort(404);
} catch (DomainException $exception) {
$this->form->showDomainError($exception);
return;
}
$this->redirectRoute('users.index', navigate: true);
}
public function sendPasswordLink(SendPasswordSetupLink $sendLink): void
{
$this->authorize('users.manage');
abort_if($this->userId === null, 404);
try {
$sent = $sendLink->execute($this->userId);
} catch (UserAccountNotFound) {
abort(404);
}
$this->linkStatus = $sent
? __('users.link_sent', ['email' => $this->form->email])
: __('users.link_throttled');
}
public function render(): mixed
{
return $this->view()->title(__($this->userId === null ? 'users.create_title' : 'users.edit_title'));
}
};
?>
<div class="mx-auto max-w-2xl space-y-6 p-4 sm:p-6">
<flux:heading size="xl" level="1">
{{ __($userId === null ? 'users.create_title' : 'users.edit_title') }}
</flux:heading>
<form wire:submit="save" class="space-y-6" novalidate>
<flux:input wire:model="form.name" :label="__('users.fields.name')" autocomplete="off" required />
<flux:input wire:model="form.email" type="email" :label="__('users.fields.email')" autocomplete="off" required />
<flux:select wire:model.live="form.role" :label="__('users.fields.role')">
@foreach (Role::cases() as $role)
<flux:select.option wire:key="role-{{ $role->value }}" :value="$role->value">
{{ __('users.roles.'.$role->value) }}
</flux:select.option>
@endforeach
</flux:select>
@if ($form->isIntern())
<flux:input
wire:model="form.employment_ends_on"
type="date"
:label="__('users.fields.employment_ends_on')"
:description="__('users.fields.employment_ends_on_description')"
required
/>
<flux:select wire:model="form.supervisor_id" :label="__('users.fields.supervisor')" :placeholder="__('users.fields.supervisor_placeholder')">
@foreach ($this->supervisorOptions as $option)
<flux:select.option wire:key="supervisor-{{ $option->id }}" :value="(string) $option->id">
{{ $option->name }}
</flux:select.option>
@endforeach
</flux:select>
@endif
<flux:checkbox
wire:model="form.active"
:label="__('users.fields.active')"
:description="__('users.fields.active_description')"
/>
<div class="flex flex-wrap gap-3">
<flux:button type="submit" variant="primary">{{ __('users.save') }}</flux:button>
<flux:button :href="route('users.index')" wire:navigate variant="ghost">{{ __('users.cancel') }}</flux:button>
</div>
</form>
@if ($userId !== null)
<div class="space-y-3 border-t border-zinc-200 pt-6 dark:border-zinc-700">
<flux:button wire:click="sendPasswordLink" icon="envelope">{{ __('users.send_link') }}</flux:button>
<div role="status" aria-live="polite">
@if ($linkStatus !== '')
<flux:text>{{ $linkStatus }}</flux:text>
@endif
</div>
</div>
@endif
</div>
@@ -0,0 +1,131 @@
<?php
use App\Modules\Users\Application\Contracts\UserAccountQueries;
use App\Modules\Users\Application\DTOs\UserSummary;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Illuminate\Support\Carbon;
use Livewire\Attributes\Computed;
use Livewire\Attributes\Url;
use Livewire\Component;
use Livewire\WithPagination;
new class extends Component
{
use WithPagination;
#[Url(as: 'q', except: '')]
public string $search = '';
protected UserAccountQueries $userQueries;
public function boot(UserAccountQueries $userQueries): void
{
$this->userQueries = $userQueries;
}
public function mount(): void
{
$this->authorize('users.manage');
}
public function updatedSearch(): void
{
$this->resetPage();
}
/**
* @return LengthAwarePaginator<int, UserSummary>
*/
#[Computed]
public function users(): LengthAwarePaginator
{
return $this->userQueries->paginate($this->search);
}
public function statusOf(UserSummary $user): string
{
if (! $user->active) {
return __('users.status.inactive');
}
if ($user->employmentEndsOn === null) {
return __('users.status.active');
}
$endsOn = Carbon::parse($user->employmentEndsOn);
$today = now(config('app.business_timezone'))->toDateString();
return __($user->employmentEndsOn < $today ? 'users.status.ended_on' : 'users.status.ends_on', [
'date' => $endsOn->format('j.n.Y'),
]);
}
public function render(): mixed
{
return $this->view()->title(__('users.title'));
}
};
?>
<div class="mx-auto max-w-5xl space-y-6 p-4 sm:p-6">
<div class="flex flex-wrap items-center justify-between gap-4">
<flux:heading size="xl" level="1">{{ __('users.title') }}</flux:heading>
<flux:button :href="route('users.create')" wire:navigate variant="primary" icon="plus">
{{ __('users.new') }}
</flux:button>
</div>
@if (session('status'))
<flux:callout variant="success" icon="check-circle" role="status" :heading="session('status')" />
@endif
<flux:input
wire:model.live.debounce.300ms="search"
type="search"
icon="magnifying-glass"
:label="__('users.search')"
:description="__('users.search_description')"
/>
<flux:text role="status" aria-live="polite" aria-atomic="true">
{{ trans_choice('users.result_count', $this->users->total(), ['count' => $this->users->total()]) }}
</flux:text>
@if ($this->users->total() === 0)
<flux:text>{{ __('users.empty') }}</flux:text>
@else
<flux:table :paginate="$this->users">
<flux:table.columns>
<flux:table.column>{{ __('users.fields.name') }}</flux:table.column>
<flux:table.column>{{ __('users.fields.email') }}</flux:table.column>
<flux:table.column>{{ __('users.fields.role') }}</flux:table.column>
<flux:table.column>{{ __('users.fields.status') }}</flux:table.column>
<flux:table.column><span class="sr-only">{{ __('users.edit') }}</span></flux:table.column>
</flux:table.columns>
<flux:table.rows>
@foreach ($this->users as $user)
<flux:table.row wire:key="user-{{ $user->id }}">
<flux:table.cell variant="strong">{{ $user->name }}</flux:table.cell>
<flux:table.cell>{{ $user->email }}</flux:table.cell>
<flux:table.cell>
{{ __('users.roles.'.$user->role->value) }}
@if ($user->supervisorName)
<span class="block text-xs text-zinc-600 dark:text-zinc-300">
{{ __('users.fields.supervisor') }}: {{ $user->supervisorName }}
</span>
@endif
</flux:table.cell>
<flux:table.cell>{{ $this->statusOf($user) }}</flux:table.cell>
<flux:table.cell align="end">
<flux:link :href="route('users.edit', $user->id)" wire:navigate>
{{ __('users.edit') }}<span class="sr-only">: {{ $user->name }}</span>
</flux:link>
</flux:table.cell>
</flux:table.row>
@endforeach
</flux:table.rows>
</flux:table>
@endif
</div>
@@ -0,0 +1,108 @@
<?php
use App\Modules\Users\Application\UseCases\CheckLoginAllowed;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\RateLimiter;
use Illuminate\Support\Str;
use Illuminate\Validation\ValidationException;
use Livewire\Component;
new class extends Component
{
public const int MAX_ATTEMPTS_PER_MINUTE = 5;
public string $email = '';
public string $password = '';
public bool $remember = false;
public function login(CheckLoginAllowed $checkLoginAllowed): void
{
$this->email = trim($this->email);
$this->validate(
['email' => ['required', 'string', 'email'], 'password' => ['required', 'string']],
[
'email.required' => __('auth.email_required'),
'email.email' => __('auth.email_invalid'),
'password.required' => __('auth.password_required'),
],
);
$email = Str::lower(trim($this->email));
$throttleKey = Str::transliterate($email.'|'.request()->ip());
if (RateLimiter::tooManyAttempts($throttleKey, self::MAX_ATTEMPTS_PER_MINUTE)) {
throw ValidationException::withMessages([
'email' => __('auth.throttle', ['seconds' => RateLimiter::availableIn($throttleKey)]),
]);
}
$accountDisabled = false;
$signedIn = Auth::attemptWhen(
['email' => $email, 'password' => $this->password],
function ($user) use ($checkLoginAllowed, &$accountDisabled): bool {
$accountDisabled = ! $checkLoginAllowed->execute($user->getAuthIdentifier());
return ! $accountDisabled;
},
$this->remember,
);
if (! $signedIn) {
RateLimiter::hit($throttleKey);
$this->reset('password');
throw ValidationException::withMessages([
'email' => __($accountDisabled ? 'auth.account_disabled' : 'auth.failed'),
]);
}
RateLimiter::clear($throttleKey);
session()->regenerate();
$this->redirectIntended(route('home'));
}
public function render(): mixed
{
return $this->view()->title(__('auth.login_title'));
}
};
?>
<div class="mx-auto max-w-md space-y-6 p-4 sm:p-6 sm:pt-16">
<flux:heading size="xl" level="1">{{ __('auth.login_title') }}</flux:heading>
@if (session('status'))
<flux:callout variant="success" icon="information-circle" role="status" :heading="session('status')" />
@endif
<form wire:submit="login" class="space-y-6" novalidate>
<flux:input
wire:model="email"
type="email"
:label="__('auth.email')"
autocomplete="username"
required
/>
<flux:input
wire:model="password"
type="password"
:label="__('auth.password_label')"
autocomplete="current-password"
viewable
required
/>
<flux:checkbox wire:model="remember" :label="__('auth.remember')" />
<div class="flex flex-wrap items-center justify-between gap-4">
<flux:button type="submit" variant="primary">{{ __('auth.login') }}</flux:button>
<flux:link :href="route('password.request')" wire:navigate>{{ __('auth.forgot_password') }}</flux:link>
</div>
</form>
</div>
@@ -0,0 +1,105 @@
<?php
use Illuminate\Auth\Events\PasswordReset;
use Illuminate\Support\Facades\Password;
use Illuminate\Support\Str;
use Illuminate\Validation\Rules\Password as PasswordRule;
use Livewire\Attributes\Locked;
use Livewire\Component;
new class extends Component
{
#[Locked]
public string $token = '';
public string $email = '';
public string $password = '';
public string $password_confirmation = '';
public function mount(string $token): void
{
$this->token = $token;
$this->email = (string) request()->query('email', '');
}
public function resetPassword(): void
{
$this->validate(
[
'email' => ['required', 'string', 'email'],
'password' => ['required', 'string', 'confirmed', PasswordRule::defaults()],
],
[
'email.required' => __('auth.email_required'),
'email.email' => __('auth.email_invalid'),
'password.required' => __('auth.password_required'),
'password.confirmed' => __('auth.password_mismatch'),
'password.min' => __('auth.password_too_short', ['min' => 12]),
],
);
$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 {
$user->forceFill(['password' => $password, 'remember_token' => Str::random(60)])->save();
event(new PasswordReset($user));
},
);
if ($status !== Password::PASSWORD_RESET) {
$this->reset('password', 'password_confirmation');
$this->addError('email', __($status));
return;
}
session()->flash('status', __($status));
$this->redirectRoute('login');
}
public function render(): mixed
{
return $this->view()->title(__('auth.reset_title'));
}
};
?>
<div class="mx-auto max-w-md space-y-6 p-4 sm:p-6 sm:pt-16">
<flux:heading size="xl" level="1">{{ __('auth.reset_title') }}</flux:heading>
<flux:text>{{ __('auth.reset_intro') }}</flux:text>
<form wire:submit="resetPassword" class="space-y-6" novalidate>
<flux:input wire:model="email" type="email" :label="__('auth.email')" autocomplete="username" required />
<flux:input
wire:model="password"
type="password"
:label="__('auth.new_password')"
:description="__('auth.password_rules')"
autocomplete="new-password"
viewable
required
/>
<flux:input
wire:model="password_confirmation"
type="password"
:label="__('auth.confirm_password')"
autocomplete="new-password"
viewable
required
/>
<flux:button type="submit" variant="primary">{{ __('auth.reset_submit') }}</flux:button>
</form>
</div>