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
+7 -2
View File
@@ -4,7 +4,7 @@ This file provides guidance to Claude Code (claude.ai/code) when working with co
## Project
An ERP / work-management system (*toiminnanohjausjärjestelmä*) for a small (5–10 person) Finnish media/marketing company. Stack: Laravel 13, Livewire 4 (single-file components), Flux UI 2 free edition, Tailwind 4, Vite 8, Pest, Larastan. Domain code lives in modules under `app/Modules` (so far `Shared` and `Customers`); `/` is still a temporary Livewire demo page (`resources/views/pages/⚡home.blade.php`, layout `resources/views/layouts/app.blade.php`). There is no login yet, so module pages sit behind `auth` and are reachable only in tests (`actingAs`).
An ERP / work-management system (*toiminnanohjausjärjestelmä*) for a small (5–10 person) Finnish media/marketing company. Stack: Laravel 13, Livewire 4 (single-file components), Flux UI 2 free edition, Tailwind 4, Vite 8, Pest, Larastan. Domain code lives in modules under `app/Modules` (so far `Shared`, `Users` and `Customers`); `/` is still a temporary Livewire demo page behind login (`resources/views/pages/⚡home.blade.php`, layout `resources/views/layouts/app.blade.php`, which has the main menu and logout for signed-in users).
- **The specification is `määrittely.txt`** (Finnish). It defines users/roles, customer jobs (*asiakastyö*) and their fields and enums, time tracking, expenses, Kanban tasks, the service unit → service → work task hierarchy, and billing-material export. It ends with Claude's open questions and a proposed phased plan. Read it before designing any domain feature.
- **Language rule:** code (identifiers, tables, columns, enum keys) is in English; the specification and the UI are in Finnish. Keep UI strings in translation files from the start.
@@ -21,7 +21,9 @@ Read `docs/architecture.md` (Finnish) before adding or changing domain code. `ap
- **Application** holds one use case per class (`execute()`), `final readonly` DTOs, and query contracts that return DTOs. It never touches Eloquent, `Illuminate\Database`, facades or HTTP. Wrap writes in `Shared\Application\Contracts\TransactionManager` and publish events through `EventDispatcher` (dispatched after commit).
- **Infrastructure** has Eloquent models named `…Model`, repository and query implementations, and the module's service provider (bindings, routes, `Livewire::addNamespace`), which is registered in `bootstrap/providers.php`. Migrations and factories stay in `database/`.
- **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.
- 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.
- `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`.
- When writing PHP through a bash heredoc, `\\` can collapse to `\`, and `"App\Modules\{$x}"` then stops interpolating. Write PHP files with the Write tool.
@@ -50,8 +52,11 @@ php artisan test --compact # full suite (composer test also clears config first
php artisan test --compact --filter=testName
vendor/bin/pint --dirty --format agent
composer analyse # Larastan level 6 (Blade SFCs excluded)
php artisan users:create-admin "Name" email@example.fi # first admin; emails a set-password link
```
- Locally `MAIL_MAILER=log`: emails, including set-password links, are written to `storage/logs/laravel.log`.
- Runs under XAMPP: Apache on port 8080 serves the app at `http://localhost:8080/toiminnanohjaus/public` (this is `APP_URL`). The database is XAMPP MariaDB 10.11 `toiminnanohjaus` (root, no password).
- Tests use in-memory SQLite with array cache/session/mail and the sync queue. `phpunit.xml` sets `APP_URL=http://localhost`, because the subfolder `APP_URL` makes test requests 404.
- Browser tests (`tests/Browser`, Pest browser plugin with Playwright Chromium) run against built assets, so run `npm run build` first. Run only them with `php artisan test --compact tests/Browser`. They need PHP's `sockets` extension (enabled in `C:\xampp\php\php.ini`). In the plugin's `click`/`keys` methods, a selector is treated as CSS only if it starts with `#`, `.` or `[`, or contains a CSS combinator (`html > body`). Otherwise it is matched as visible text, so `button` or `main button` time out.
+27 -1
View File
@@ -3,20 +3,43 @@
namespace App\Models;
// use Illuminate\Contracts\Auth\MustVerifyEmail;
use App\Modules\Users\Domain\Enums\Role;
use Database\Factories\UserFactory;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Attributes\Hidden;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use Illuminate\Support\Carbon;
#[Fillable(['name', 'email', 'password'])]
/**
* Laravel's authentication model. It belongs to the Users module's
* Infrastructure layer; other modules use it only through auth() and Gate.
*
* @property int $id
* @property string $name
* @property string $email
* @property Role $role
* @property bool $is_active
* @property Carbon|null $employment_ends_on
* @property int|null $supervisor_id
*/
#[Fillable(['name', 'email', 'password', 'role', 'is_active', 'employment_ends_on', 'supervisor_id'])]
#[Hidden(['password', 'remember_token'])]
class User extends Authenticatable
{
/** @use HasFactory<UserFactory> */
use HasFactory, Notifiable;
/**
* @return BelongsTo<User, $this>
*/
public function supervisor(): BelongsTo
{
return $this->belongsTo(User::class, 'supervisor_id');
}
/**
* Get the attributes that should be cast.
*
@@ -27,6 +50,9 @@ class User extends Authenticatable
return [
'email_verified_at' => 'datetime',
'password' => 'hashed',
'role' => Role::class,
'is_active' => 'boolean',
'employment_ends_on' => 'date',
];
}
}
@@ -2,16 +2,19 @@
namespace App\Modules\Customers\Infrastructure\Providers;
use App\Models\User;
use App\Modules\Customers\Application\Contracts\CustomerQueries;
use App\Modules\Customers\Domain\Contracts\CustomerRepository;
use App\Modules\Customers\Infrastructure\Persistence\Repositories\EloquentCustomerQueries;
use App\Modules\Customers\Infrastructure\Persistence\Repositories\EloquentCustomerRepository;
use App\Modules\Users\Domain\Enums\Role;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\ServiceProvider;
use Livewire\Livewire;
/**
* Wires the Customers module into Laravel: contract bindings, routes and
* the `customers::` Livewire namespace.
* Wires the Customers module into Laravel: contract bindings, routes, the
* `customers::` Livewire namespace and the `customers.use` ability.
*/
class CustomersServiceProvider extends ServiceProvider
{
@@ -32,5 +35,8 @@ class CustomersServiceProvider extends ServiceProvider
if (! $this->app->routesAreCached()) {
$this->loadRoutesFrom($presentationPath.'/Routes/web.php');
}
// Subcontractors see only the customer jobs assigned to them, not the customer register.
Gate::define('customers.use', fn (User $user): bool => $user->role !== Role::Subcontractor);
}
}
@@ -4,8 +4,10 @@ use App\Modules\Customers\Application\Contracts\CustomerQueries;
use App\Modules\Customers\Application\UseCases\RegisterCustomer;
use App\Modules\Customers\Application\UseCases\UpdateCustomer;
use App\Modules\Customers\Domain\Enums\CustomerType;
use App\Modules\Customers\Domain\Exceptions\CustomerNotFound;
use App\Modules\Customers\Presentation\Livewire\Forms\CustomerForm;
use App\Modules\Shared\Domain\Exceptions\DomainException;
use Livewire\Attributes\Locked;
use Livewire\Component;
/**
@@ -13,12 +15,15 @@ use Livewire\Component;
*/
new class extends Component
{
#[Locked]
public ?int $customerId = null;
public CustomerForm $form;
public function mount(CustomerQueries $customerQueries, ?int $customer = null): void
{
$this->authorize('customers.use');
if ($customer === null) {
return;
}
@@ -33,6 +38,8 @@ new class extends Component
public function save(RegisterCustomer $registerCustomer, UpdateCustomer $updateCustomer): void
{
$this->authorize('customers.use');
$data = $this->form->toData();
try {
@@ -43,6 +50,8 @@ new class extends Component
$updateCustomer->execute($this->customerId, $data);
session()->flash('status', __('customers.updated', ['name' => $data->name]));
}
} catch (CustomerNotFound) {
abort(404);
} catch (DomainException $exception) {
$this->form->showDomainError($exception);
@@ -22,6 +22,11 @@ new class extends Component
$this->customerQueries = $customerQueries;
}
public function mount(): void
{
$this->authorize('customers.use');
}
public function updatedSearch(): void
{
$this->resetPage();
@@ -68,7 +73,7 @@ new class extends Component
{{ trans_choice('customers.result_count', $this->customers->total(), ['count' => $this->customers->total()]) }}
</flux:text>
@if ($this->customers->isEmpty())
@if ($this->customers->total() === 0)
<flux:text>{{ __('customers.empty') }}</flux:text>
@else
<flux:table :paginate="$this->customers">
@@ -2,7 +2,7 @@
use Illuminate\Support\Facades\Route;
Route::middleware(['web', 'auth'])
Route::middleware(['web', 'auth', 'can:customers.use'])
->prefix('customers')
->name('customers.')
->group(function () {
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace App\Modules\Users\Application\Contracts;
use DateTimeImmutable;
interface Clock
{
/**
* The current day in the company's time zone.
*/
public function today(): DateTimeImmutable;
}
@@ -0,0 +1,19 @@
<?php
declare(strict_types=1);
namespace App\Modules\Users\Application\Contracts;
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.
*/
interface PasswordLinkSender
{
/**
* @return bool False when a link was sent to this address too recently.
*/
public function sendSetupLink(EmailAddress $email): bool;
}
@@ -0,0 +1,31 @@
<?php
declare(strict_types=1);
namespace App\Modules\Users\Application\Contracts;
use App\Modules\Users\Application\DTOs\UserOption;
use App\Modules\Users\Application\DTOs\UserSummary;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
/**
* Read side of the Users module.
*/
interface UserAccountQueries
{
public function findSummary(int $id): ?UserSummary;
/**
* Users ordered by name, filtered by a name or email fragment.
*
* @return LengthAwarePaginator<int, UserSummary>
*/
public function paginate(?string $search, int $perPage = 25): LengthAwarePaginator;
/**
* Active management and employee users who can supervise an intern.
*
* @return list<UserOption>
*/
public function supervisorOptions(?int $exceptUserId = null): array;
}
@@ -0,0 +1,43 @@
<?php
declare(strict_types=1);
namespace App\Modules\Users\Application\DTOs;
use App\Modules\Users\Domain\Enums\Role;
/**
* Input for creating a user or changing a user's details.
*/
final readonly class UserAccountData
{
/**
* @param string|null $employmentEndsOn Date as Y-m-d.
*/
public function __construct(
public string $name,
public string $email,
public Role $role,
public bool $active = true,
public ?string $employmentEndsOn = null,
public ?int $supervisorId = null,
) {}
/**
* @param array{name: string, email: string, role: string|Role, active?: bool, employment_ends_on?: string|null, supervisor_id?: int|string|null} $data
*/
public static function fromArray(array $data): self
{
$endsOn = trim((string) ($data['employment_ends_on'] ?? ''));
$supervisorId = $data['supervisor_id'] ?? null;
return new self(
name: $data['name'],
email: $data['email'],
role: $data['role'] instanceof Role ? $data['role'] : Role::from($data['role']),
active: $data['active'] ?? true,
employmentEndsOn: $endsOn === '' ? null : $endsOn,
supervisorId: $supervisorId === null || $supervisorId === '' ? null : (int) $supervisorId,
);
}
}
@@ -0,0 +1,16 @@
<?php
declare(strict_types=1);
namespace App\Modules\Users\Application\DTOs;
/**
* A user as a choice in a select list.
*/
final readonly class UserOption
{
public function __construct(
public int $id,
public string $name,
) {}
}
@@ -0,0 +1,27 @@
<?php
declare(strict_types=1);
namespace App\Modules\Users\Application\DTOs;
use App\Modules\Users\Domain\Enums\Role;
/**
* Read model of a user for lists and forms.
*/
final readonly class UserSummary
{
/**
* @param string|null $employmentEndsOn Date as Y-m-d.
*/
public function __construct(
public int $id,
public string $name,
public string $email,
public Role $role,
public bool $active,
public ?string $employmentEndsOn,
public ?int $supervisorId,
public ?string $supervisorName,
) {}
}
@@ -0,0 +1,25 @@
<?php
declare(strict_types=1);
namespace App\Modules\Users\Application\UseCases;
use App\Modules\Users\Application\Contracts\Clock;
use App\Modules\Users\Domain\Contracts\UserAccountRepository;
/**
* Whether a user may sign in or keep using the system today: active, and
* an intern's last day not passed.
*/
final class CheckLoginAllowed
{
public function __construct(
private UserAccountRepository $users,
private Clock $clock,
) {}
public function execute(int $userId): bool
{
return $this->users->findById($userId)?->canLogInOn($this->clock->today()) ?? false;
}
}
@@ -0,0 +1,61 @@
<?php
declare(strict_types=1);
namespace App\Modules\Users\Application\UseCases;
use App\Modules\Shared\Application\Contracts\TransactionManager;
use App\Modules\Users\Application\Contracts\PasswordLinkSender;
use App\Modules\Users\Application\DTOs\UserAccountData;
use App\Modules\Users\Domain\Contracts\UserAccountRepository;
use App\Modules\Users\Domain\Entities\UserAccount;
use App\Modules\Users\Domain\Exceptions\EmailAlreadyInUse;
use App\Modules\Users\Domain\Exceptions\InvalidSupervisor;
use App\Modules\Users\Domain\Services\SupervisorRule;
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.
*/
final class CreateUserAccount
{
public function __construct(
private UserAccountRepository $users,
private SupervisorRule $supervisorRule,
private TransactionManager $transactions,
private PasswordLinkSender $passwordLinks,
) {}
/**
* @return int The new user's id.
*
* @throws EmailAlreadyInUse
* @throws InvalidSupervisor
*/
public function execute(UserAccountData $data): int
{
$user = UserAccount::register(
new PersonName($data->name),
new EmailAddress($data->email),
$data->role,
EmploymentEndDate::parse($data->employmentEndsOn),
$data->supervisorId,
);
$userId = $this->transactions->run(function () use ($user): int {
if ($this->users->isEmailTaken($user->email())) {
throw new EmailAlreadyInUse;
}
$this->supervisorRule->ensureValidFor($user);
return (int) $this->users->save($user)->id();
});
$this->passwordLinks->sendSetupLink($user->email());
return $userId;
}
}
@@ -0,0 +1,31 @@
<?php
declare(strict_types=1);
namespace App\Modules\Users\Application\UseCases;
use DateTimeImmutable;
use InvalidArgumentException;
/**
* Turns the Y-m-d date of a UserAccountData into a date object.
*
* @internal Shared by the user use cases.
*/
final class EmploymentEndDate
{
public static function parse(?string $date): ?DateTimeImmutable
{
if ($date === null) {
return null;
}
$parsed = DateTimeImmutable::createFromFormat('!Y-m-d', $date);
if ($parsed === false || $parsed->format('Y-m-d') !== $date) {
throw new InvalidArgumentException("Invalid employment end date [{$date}], expected Y-m-d.");
}
return $parsed;
}
}
@@ -0,0 +1,32 @@
<?php
declare(strict_types=1);
namespace App\Modules\Users\Application\UseCases;
use App\Modules\Users\Application\Contracts\PasswordLinkSender;
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.
*/
final class SendPasswordSetupLink
{
public function __construct(
private UserAccountRepository $users,
private PasswordLinkSender $passwordLinks,
) {}
/**
* @return bool False when a link was sent to the user too recently.
*
* @throws UserAccountNotFound
*/
public function execute(int $userId): bool
{
$user = $this->users->findById($userId) ?? throw new UserAccountNotFound($userId);
return $this->passwordLinks->sendSetupLink($user->email());
}
}
@@ -0,0 +1,57 @@
<?php
declare(strict_types=1);
namespace App\Modules\Users\Application\UseCases;
use App\Modules\Shared\Application\Contracts\TransactionManager;
use App\Modules\Users\Application\DTOs\UserAccountData;
use App\Modules\Users\Domain\Contracts\UserAccountRepository;
use App\Modules\Users\Domain\Exceptions\EmailAlreadyInUse;
use App\Modules\Users\Domain\Exceptions\InvalidSupervisor;
use App\Modules\Users\Domain\Exceptions\LastAdminCannotBeRemoved;
use App\Modules\Users\Domain\Exceptions\UserAccountNotFound;
use App\Modules\Users\Domain\Services\SupervisorRule;
use App\Modules\Users\Domain\ValueObjects\EmailAddress;
use App\Modules\Users\Domain\ValueObjects\PersonName;
final class UpdateUserAccount
{
public function __construct(
private UserAccountRepository $users,
private SupervisorRule $supervisorRule,
private TransactionManager $transactions,
) {}
/**
* @throws UserAccountNotFound
* @throws EmailAlreadyInUse
* @throws InvalidSupervisor
* @throws LastAdminCannotBeRemoved
*/
public function execute(int $userId, UserAccountData $data): void
{
$name = new PersonName($data->name);
$email = new EmailAddress($data->email);
$endsOn = EmploymentEndDate::parse($data->employmentEndsOn);
$this->transactions->run(function () use ($userId, $data, $name, $email, $endsOn): void {
$user = $this->users->findById($userId) ?? throw new UserAccountNotFound($userId);
$wasActiveAdmin = $user->isActiveAdmin();
if ($this->users->isEmailTaken($email, $userId)) {
throw new EmailAlreadyInUse;
}
$user->changeDetails($name, $email, $data->role, $data->active, $endsOn, $data->supervisorId);
if ($wasActiveAdmin && ! $user->isActiveAdmin() && $this->users->countActiveAdmins($userId) === 0) {
throw new LastAdminCannotBeRemoved;
}
$this->supervisorRule->ensureValidFor($user);
$this->users->save($user);
});
}
}
@@ -0,0 +1,23 @@
<?php
declare(strict_types=1);
namespace App\Modules\Users\Domain\Contracts;
use App\Modules\Users\Domain\Entities\UserAccount;
use App\Modules\Users\Domain\ValueObjects\EmailAddress;
interface UserAccountRepository
{
public function findById(int $id): ?UserAccount;
/**
* Inserts a new user or updates a stored one, and returns the stored
* user (a new one gets its id here).
*/
public function save(UserAccount $user): UserAccount;
public function isEmailTaken(EmailAddress $email, ?int $exceptUserId = null): bool;
public function countActiveAdmins(?int $exceptUserId = null): int;
}
@@ -0,0 +1,155 @@
<?php
declare(strict_types=1);
namespace App\Modules\Users\Domain\Entities;
use App\Modules\Users\Domain\Enums\Role;
use App\Modules\Users\Domain\Exceptions\InternRequiresEndDateAndSupervisor;
use App\Modules\Users\Domain\Exceptions\InvalidSupervisor;
use App\Modules\Users\Domain\ValueObjects\EmailAddress;
use App\Modules\Users\Domain\ValueObjects\PersonName;
use DateTimeImmutable;
/**
* A person who can sign in to the system.
*
* Interns have an employment end date (their last day with access) and a
* supervisor. Other roles have neither: they are cleared on a role change.
*/
final class UserAccount
{
private function __construct(
private ?int $id,
private PersonName $name,
private EmailAddress $email,
private Role $role,
private bool $active,
private ?DateTimeImmutable $employmentEndsOn,
private ?int $supervisorId,
) {
$this->applyRoleRules();
}
/**
* A new, active user that is not stored yet, so it has no id.
*/
public static function register(
PersonName $name,
EmailAddress $email,
Role $role,
?DateTimeImmutable $employmentEndsOn = null,
?int $supervisorId = null,
): self {
return new self(null, $name, $email, $role, true, $employmentEndsOn, $supervisorId);
}
/**
* Rebuilds a stored user. Used only by repositories.
*/
public static function reconstitute(
int $id,
PersonName $name,
EmailAddress $email,
Role $role,
bool $active,
?DateTimeImmutable $employmentEndsOn,
?int $supervisorId,
): self {
return new self($id, $name, $email, $role, $active, $employmentEndsOn, $supervisorId);
}
public function changeDetails(
PersonName $name,
EmailAddress $email,
Role $role,
bool $active,
?DateTimeImmutable $employmentEndsOn,
?int $supervisorId,
): void {
$changed = clone $this;
$changed->name = $name;
$changed->email = $email;
$changed->role = $role;
$changed->active = $active;
$changed->employmentEndsOn = $employmentEndsOn;
$changed->supervisorId = $supervisorId;
$changed->applyRoleRules();
foreach (get_object_vars($changed) as $property => $value) {
$this->{$property} = $value;
}
}
/**
* Whether the user may sign in on the given day. An intern's end date
* is the last day with access.
*/
public function canLogInOn(DateTimeImmutable $day): bool
{
if (! $this->active) {
return false;
}
return $this->employmentEndsOn === null
|| $day->format('Y-m-d') <= $this->employmentEndsOn->format('Y-m-d');
}
public function isActiveAdmin(): bool
{
return $this->active && $this->role === Role::Admin;
}
public function id(): ?int
{
return $this->id;
}
public function name(): PersonName
{
return $this->name;
}
public function email(): EmailAddress
{
return $this->email;
}
public function role(): Role
{
return $this->role;
}
public function isActive(): bool
{
return $this->active;
}
public function employmentEndsOn(): ?DateTimeImmutable
{
return $this->employmentEndsOn;
}
public function supervisorId(): ?int
{
return $this->supervisorId;
}
private function applyRoleRules(): void
{
if ($this->role !== Role::Intern) {
$this->employmentEndsOn = null;
$this->supervisorId = null;
return;
}
if ($this->employmentEndsOn === null || $this->supervisorId === null) {
throw new InternRequiresEndDateAndSupervisor;
}
if ($this->id !== null && $this->supervisorId === $this->id) {
throw new InvalidSupervisor;
}
}
}
+31
View File
@@ -0,0 +1,31 @@
<?php
declare(strict_types=1);
namespace App\Modules\Users\Domain\Enums;
/**
* User roles. Other modules may use this enum in their authorization
* rules: it is the one published Domain type of the Users module.
*/
enum Role: string
{
case Admin = 'admin';
case Management = 'management';
case Employee = 'employee';
case Intern = 'intern';
case Subcontractor = 'subcontractor';
public function canManageUsers(): bool
{
return $this === self::Admin;
}
/**
* Whether a user with this role can be an intern's supervisor.
*/
public function canSupervise(): bool
{
return $this === self::Management || $this === self::Employee;
}
}
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace App\Modules\Users\Domain\Exceptions;
use App\Modules\Shared\Domain\Exceptions\DomainException;
final class EmailAlreadyInUse extends DomainException
{
public function __construct()
{
parent::__construct('The email address already belongs to another user.');
}
}
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace App\Modules\Users\Domain\Exceptions;
use App\Modules\Shared\Domain\Exceptions\DomainException;
final class InternRequiresEndDateAndSupervisor extends DomainException
{
public function __construct()
{
parent::__construct('An intern must have an employment end date and a supervisor.');
}
}
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace App\Modules\Users\Domain\Exceptions;
use App\Modules\Shared\Domain\Exceptions\DomainException;
final class InvalidEmailAddress extends DomainException
{
public function __construct()
{
parent::__construct('The email address is not valid.');
}
}
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace App\Modules\Users\Domain\Exceptions;
use App\Modules\Shared\Domain\Exceptions\DomainException;
final class InvalidPersonName extends DomainException
{
public function __construct()
{
parent::__construct('The name must be 1–255 characters.');
}
}
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace App\Modules\Users\Domain\Exceptions;
use App\Modules\Shared\Domain\Exceptions\DomainException;
final class InvalidSupervisor extends DomainException
{
public function __construct()
{
parent::__construct('The supervisor must be an active management or employee user other than the intern.');
}
}
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace App\Modules\Users\Domain\Exceptions;
use App\Modules\Shared\Domain\Exceptions\DomainException;
final class LastAdminCannotBeRemoved extends DomainException
{
public function __construct()
{
parent::__construct('The last active admin cannot be deactivated or given another role.');
}
}
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace App\Modules\Users\Domain\Exceptions;
use App\Modules\Shared\Domain\Exceptions\DomainException;
final class UserAccountNotFound extends DomainException
{
public function __construct(public readonly int $userId)
{
parent::__construct("User {$userId} was not found.");
}
}
@@ -0,0 +1,39 @@
<?php
declare(strict_types=1);
namespace App\Modules\Users\Domain\Services;
use App\Modules\Users\Domain\Contracts\UserAccountRepository;
use App\Modules\Users\Domain\Entities\UserAccount;
use App\Modules\Users\Domain\Exceptions\InvalidSupervisor;
/**
* An intern's supervisor must be another active management or employee
* user. Needs the repository, so it cannot live in the entity.
*/
final class SupervisorRule
{
public function __construct(private UserAccountRepository $users) {}
/**
* @throws InvalidSupervisor
*/
public function ensureValidFor(UserAccount $user): void
{
$supervisorId = $user->supervisorId();
if ($supervisorId === null) {
return;
}
$supervisor = $this->users->findById($supervisorId);
if ($supervisor === null
|| $supervisor->id() === $user->id()
|| ! $supervisor->isActive()
|| ! $supervisor->role()->canSupervise()) {
throw new InvalidSupervisor;
}
}
}
@@ -0,0 +1,34 @@
<?php
declare(strict_types=1);
namespace App\Modules\Users\Domain\ValueObjects;
use App\Modules\Users\Domain\Exceptions\InvalidEmailAddress;
/**
* Login email address, stored in lower case so it is unique regardless
* of how it was typed.
*/
final readonly class EmailAddress
{
public const int MAX_LENGTH = 255;
public string $value;
public function __construct(string $value)
{
$value = mb_strtolower(trim($value));
if (mb_strlen($value) > self::MAX_LENGTH || filter_var($value, FILTER_VALIDATE_EMAIL) === false) {
throw new InvalidEmailAddress;
}
$this->value = $value;
}
public function equals(self $other): bool
{
return $this->value === $other->value;
}
}
@@ -0,0 +1,25 @@
<?php
declare(strict_types=1);
namespace App\Modules\Users\Domain\ValueObjects;
use App\Modules\Users\Domain\Exceptions\InvalidPersonName;
final readonly class PersonName
{
public const int MAX_LENGTH = 255;
public string $value;
public function __construct(string $value)
{
$value = trim(preg_replace('/\s+/u', ' ', $value) ?? $value);
if ($value === '' || mb_strlen($value) > self::MAX_LENGTH) {
throw new InvalidPersonName;
}
$this->value = $value;
}
}
@@ -0,0 +1,21 @@
<?php
namespace App\Modules\Users\Infrastructure\Auth;
use App\Modules\Users\Application\Contracts\PasswordLinkSender;
use App\Modules\Users\Domain\ValueObjects\EmailAddress;
use Illuminate\Contracts\Auth\PasswordBroker;
/**
* Sends Laravel's password reset notification, which the Users module
* provider words as a "set your password" email.
*/
class LaravelPasswordLinkSender implements PasswordLinkSender
{
public function __construct(private PasswordBroker $passwords) {}
public function sendSetupLink(EmailAddress $email): bool
{
return $this->passwords->sendResetLink(['email' => $email->value]) === PasswordBroker::RESET_LINK_SENT;
}
}
@@ -0,0 +1,66 @@
<?php
namespace App\Modules\Users\Infrastructure\Persistence\Repositories;
use App\Models\User;
use App\Modules\Users\Application\Contracts\UserAccountQueries;
use App\Modules\Users\Application\DTOs\UserOption;
use App\Modules\Users\Application\DTOs\UserSummary;
use App\Modules\Users\Domain\Enums\Role;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Illuminate\Database\Eloquent\Builder;
class EloquentUserAccountQueries implements UserAccountQueries
{
public function findSummary(int $id): ?UserSummary
{
$model = User::query()->with('supervisor:id,name')->find($id);
return $model === null ? null : $this->toSummary($model);
}
public function paginate(?string $search, int $perPage = 25): LengthAwarePaginator
{
$search = trim((string) $search);
return User::query()
->with('supervisor:id,name')
->when($search !== '', function (Builder $query) use ($search): void {
$pattern = '%'.addcslashes($search, '%_\\').'%';
$query->where(fn (Builder $query) => $query
->where('name', 'like', $pattern)
->orWhere('email', 'like', $pattern));
})
->orderBy('name')
->paginate($perPage)
->through(fn (User $model): UserSummary => $this->toSummary($model));
}
public function supervisorOptions(?int $exceptUserId = null): array
{
return User::query()
->whereIn('role', array_filter(Role::cases(), fn (Role $role): bool => $role->canSupervise()))
->where('is_active', true)
->when($exceptUserId !== null, fn (Builder $query) => $query->whereKeyNot($exceptUserId))
->orderBy('name')
->get(['id', 'name'])
->map(fn (User $model): UserOption => new UserOption($model->id, $model->name))
->values()
->all();
}
private function toSummary(User $model): UserSummary
{
return new UserSummary(
id: $model->id,
name: $model->name,
email: $model->email,
role: $model->role,
active: $model->is_active,
employmentEndsOn: $model->employment_ends_on?->toDateString(),
supervisorId: $model->supervisor_id,
supervisorName: $model->supervisor?->name,
);
}
}
@@ -0,0 +1,74 @@
<?php
namespace App\Modules\Users\Infrastructure\Persistence\Repositories;
use App\Models\User;
use App\Modules\Users\Domain\Contracts\UserAccountRepository;
use App\Modules\Users\Domain\Entities\UserAccount;
use App\Modules\Users\Domain\Enums\Role;
use App\Modules\Users\Domain\ValueObjects\EmailAddress;
use App\Modules\Users\Domain\ValueObjects\PersonName;
use DateTimeImmutable;
use Illuminate\Support\Str;
class EloquentUserAccountRepository implements UserAccountRepository
{
public function findById(int $id): ?UserAccount
{
$model = User::query()->find($id);
return $model === null ? null : $this->toEntity($model);
}
public function save(UserAccount $user): UserAccount
{
if ($user->id() === null) {
$model = new User;
// Nobody knows this password: the user sets their own through the emailed link.
$model->password = Str::random(64);
} else {
$model = User::query()->findOrFail($user->id());
}
$model->fill([
'name' => $user->name()->value,
'email' => $user->email()->value,
'role' => $user->role(),
'is_active' => $user->isActive(),
'employment_ends_on' => $user->employmentEndsOn()?->format('Y-m-d'),
'supervisor_id' => $user->supervisorId(),
])->save();
return $this->toEntity($model->refresh());
}
public function isEmailTaken(EmailAddress $email, ?int $exceptUserId = null): bool
{
return User::query()
->where('email', $email->value)
->when($exceptUserId !== null, fn ($query) => $query->whereKeyNot($exceptUserId))
->exists();
}
public function countActiveAdmins(?int $exceptUserId = null): int
{
return User::query()
->where('role', Role::Admin)
->where('is_active', true)
->when($exceptUserId !== null, fn ($query) => $query->whereKeyNot($exceptUserId))
->count();
}
private function toEntity(User $model): UserAccount
{
return UserAccount::reconstitute(
$model->id,
new PersonName($model->name),
new EmailAddress($model->email),
$model->role,
$model->is_active,
$model->employment_ends_on === null ? null : DateTimeImmutable::createFromInterface($model->employment_ends_on),
$model->supervisor_id,
);
}
}
@@ -0,0 +1,76 @@
<?php
namespace App\Modules\Users\Infrastructure\Providers;
use App\Models\User;
use App\Modules\Users\Application\Contracts\Clock;
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\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\Notifications\Messages\MailMessage;
use Illuminate\Routing\Router;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\ServiceProvider;
use Illuminate\Validation\Rules\Password;
use Livewire\Livewire;
/**
* Wires the Users module into Laravel. As the module's composition root it
* may register the module's Presentation classes (command, middleware).
*/
class UsersServiceProvider extends ServiceProvider
{
/**
* @var array<class-string, class-string>
*/
public array $bindings = [
UserAccountRepository::class => EloquentUserAccountRepository::class,
UserAccountQueries::class => EloquentUserAccountQueries::class,
PasswordLinkSender::class => LaravelPasswordLinkSender::class,
];
public function register(): void
{
$this->app->bind(Clock::class, fn () => new SystemClock(config('app.business_timezone')));
}
public function boot(Router $router): void
{
$presentationPath = dirname(__DIR__, 2).'/Presentation';
Livewire::addNamespace('users', viewPath: $presentationPath.'/Livewire');
if (! $this->app->routesAreCached()) {
$this->loadRoutesFrom($presentationPath.'/Routes/web.php');
}
$router->pushMiddlewareToGroup('web', EnsureAccountIsUsable::class);
if ($this->app->runningInConsole()) {
$this->commands([CreateAdminCommand::class]);
}
Gate::define('users.manage', fn (User $user): bool => $user->role->canManageUsers());
Password::defaults(fn () => Password::min(12));
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')));
}
}
@@ -0,0 +1,17 @@
<?php
namespace App\Modules\Users\Infrastructure;
use App\Modules\Users\Application\Contracts\Clock;
use DateTimeImmutable;
use Illuminate\Support\Facades\Date;
class SystemClock implements Clock
{
public function __construct(private string $timezone) {}
public function today(): DateTimeImmutable
{
return Date::now($this->timezone)->startOfDay()->toDateTimeImmutable();
}
}
@@ -0,0 +1,39 @@
<?php
namespace App\Modules\Users\Presentation\Console;
use App\Modules\Shared\Domain\Exceptions\DomainException;
use App\Modules\Users\Application\DTOs\UserAccountData;
use App\Modules\Users\Application\UseCases\CreateUserAccount;
use App\Modules\Users\Domain\Enums\Role;
use Illuminate\Console\Attributes\Description;
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')]
class CreateAdminCommand extends Command
{
public function handle(CreateUserAccount $createUserAccount): int
{
try {
$createUserAccount->execute(new UserAccountData(
name: (string) $this->argument('name'),
email: (string) $this->argument('email'),
role: Role::Admin,
));
} catch (DomainException $exception) {
$this->components->error($exception->getMessage());
return self::FAILURE;
}
$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.');
}
return self::SUCCESS;
}
}
@@ -0,0 +1,19 @@
<?php
namespace App\Modules\Users\Presentation\Http\Controllers;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
class LogoutController
{
public function __invoke(Request $request): RedirectResponse
{
Auth::guard('web')->logout();
$request->session()->invalidate();
$request->session()->regenerateToken();
return redirect()->route('login')->with('status', __('auth.logged_out'));
}
}
@@ -0,0 +1,33 @@
<?php
namespace App\Modules\Users\Presentation\Http\Middleware;
use App\Modules\Users\Application\UseCases\CheckLoginAllowed;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Symfony\Component\HttpFoundation\Response;
/**
* Ends the session of a signed-in user who has been deactivated or whose
* internship has ended since they signed in.
*/
class EnsureAccountIsUsable
{
public function __construct(private CheckLoginAllowed $checkLoginAllowed) {}
public function handle(Request $request, Closure $next): Response
{
$userId = Auth::id();
if ($userId !== null && ! $this->checkLoginAllowed->execute((int) $userId)) {
Auth::guard('web')->logout();
$request->session()->invalidate();
$request->session()->regenerateToken();
return redirect()->route('login')->with('status', __('auth.account_disabled'));
}
return $next($request);
}
}
@@ -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>
@@ -0,0 +1,23 @@
<?php
use App\Modules\Users\Presentation\Http\Controllers\LogoutController;
use Illuminate\Support\Facades\Route;
Route::middleware(['web', 'guest'])->group(function () {
Route::livewire('/login', 'users::login')->name('login');
Route::livewire('/forgot-password', 'users::forgot-password')->name('password.request');
Route::livewire('/reset-password/{token}', 'users::reset-password')->name('password.reset');
});
Route::middleware(['web', 'auth'])->group(function () {
Route::post('/logout', LogoutController::class)->name('logout');
Route::middleware('can:users.manage')
->prefix('users')
->name('users.')
->group(function () {
Route::livewire('/', 'users::index')->name('index');
Route::livewire('/create', 'users::form')->name('create');
Route::livewire('/{user}/edit', 'users::form')->whereNumber('user')->name('edit');
});
});
+2 -1
View File
@@ -12,7 +12,8 @@ return Application::configure(basePath: dirname(__DIR__))
health: '/up',
)
->withMiddleware(function (Middleware $middleware): void {
//
$middleware->redirectGuestsTo(fn () => route('login'));
$middleware->redirectUsersTo(fn () => route('home'));
})
->withExceptions(function (Exceptions $exceptions): void {
$exceptions->shouldRenderJsonWhen(
+2
View File
@@ -2,10 +2,12 @@
use App\Modules\Customers\Infrastructure\Providers\CustomersServiceProvider;
use App\Modules\Shared\Infrastructure\Providers\SharedServiceProvider;
use App\Modules\Users\Infrastructure\Providers\UsersServiceProvider;
use App\Providers\AppServiceProvider;
return [
AppServiceProvider::class,
SharedServiceProvider::class,
UsersServiceProvider::class,
CustomersServiceProvider::class,
];
+7
View File
@@ -67,6 +67,13 @@ return [
'timezone' => 'UTC',
/*
| The company's local time zone. Calendar days that matter to the
| business, such as an intern's last day, are counted in it.
*/
'business_timezone' => env('APP_BUSINESS_TIMEZONE', 'Europe/Helsinki'),
/*
|--------------------------------------------------------------------------
| Application Locale Configuration
+42
View File
@@ -3,6 +3,7 @@
namespace Database\Factories;
use App\Models\User;
use App\Modules\Users\Domain\Enums\Role;
use Illuminate\Database\Eloquent\Factories\Factory;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Str;
@@ -30,6 +31,10 @@ class UserFactory extends Factory
'email_verified_at' => now(),
'password' => static::$password ??= Hash::make('password'),
'remember_token' => Str::random(10),
'role' => Role::Employee,
'is_active' => true,
'employment_ends_on' => null,
'supervisor_id' => null,
];
}
@@ -42,4 +47,41 @@ class UserFactory extends Factory
'email_verified_at' => null,
]);
}
public function admin(): static
{
return $this->state(fn (): array => ['role' => Role::Admin]);
}
public function management(): static
{
return $this->state(fn (): array => ['role' => Role::Management]);
}
public function employee(): static
{
return $this->state(fn (): array => ['role' => Role::Employee]);
}
public function subcontractor(): static
{
return $this->state(fn (): array => ['role' => Role::Subcontractor]);
}
/**
* An intern whose last day is the given date (default: in a month).
*/
public function intern(?string $employmentEndsOn = null, ?User $supervisor = null): static
{
return $this->state(fn (): array => [
'role' => Role::Intern,
'employment_ends_on' => $employmentEndsOn ?? now()->addMonth()->toDateString(),
'supervisor_id' => $supervisor?->id ?? User::factory(),
]);
}
public function inactive(): static
{
return $this->state(fn (): array => ['is_active' => false]);
}
}
@@ -0,0 +1,32 @@
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::table('users', function (Blueprint $table) {
$table->string('role', 20)->default('employee')->after('email');
$table->boolean('is_active')->default(true)->after('role');
$table->date('employment_ends_on')->nullable()->after('is_active');
$table->foreignId('supervisor_id')->nullable()->after('employment_ends_on')->constrained('users')->nullOnDelete();
});
}
/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::table('users', function (Blueprint $table) {
$table->dropConstrainedForeignId('supervisor_id');
$table->dropColumn(['role', 'is_active', 'employment_ends_on']);
});
}
};
+19 -4
View File
@@ -16,7 +16,7 @@ Esimerkkinä koko dokumentissa on `Customers`-moduuli (`app/Modules/Customers`),
```
app/
├── Models/User.php # Laravelin auth-käyttäjä (siirtyy moduuliin käyttäjä- ja roolityön yhteydessä)
├── Models/User.php # Laravelin auth-malli; kuuluu Users-moduulin Infrastructure-kerrokseen (ks. luku 13)
├── Providers/AppServiceProvider.php
└── Modules/
├── Shared/ # vain aidosti yhteiset, vakaat käsitteet
@@ -26,6 +26,7 @@ app/
│ ├── Persistence/LaravelTransactionManager.php
│ ├── Events/LaravelEventDispatcher.php
│ └── Providers/SharedServiceProvider.php
├── Users/ # käyttäjät, roolit, kirjautuminen (ks. luku 13)
└── Customers/
├── Domain/
│ ├── Entities/Customer.php
@@ -105,10 +106,15 @@ Käyttöliittymä. Tässä projektissa se on **Livewire 4 single-file -komponent
| Presentation | Application, Domain | toisten moduulien Infrastructure/Presentation |
| Application | Domain, Shared Application Contracts | Infrastructure, Presentation, Eloquent, DB, Facades, HTTP |
| Domain | vain oma Domain ja Shared Domain | Application, Infrastructure, Presentation, kaikki `Illuminate`/`Livewire` |
| Infrastructure | Domain, Application, Laravel | Presentation |
| Infrastructure | Domain, Application, Laravel | Presentation (paitsi `Infrastructure/Providers`) |
Moduuli ei koskaan käytä toisen moduulin Infrastructure- tai Presentation-kerrosta.
Kaksi tarkoituksellista poikkeusta:
- **Service Provider on moduulin kokoamispiste.** Se saa rekisteröidä moduulin omat Presentation-luokat (Artisan-komennot, middlewaret), joten arkkitehtuuritesti ohittaa `Infrastructure/Providers`-kansion Infrastructure→Presentation-säännössä.
- **`Users\Domain\Enums\Role` on julkinen.** Muut moduulit saavat käyttää sitä valtuutussäännöissään (Gate), koska roolit koskevat koko järjestelmää. Muita Users-moduulin Domain-luokkia ne eivät käytä.
Säännöt valvotaan automaattisesti:
- **`tests/Unit/ArchitectureTest.php`** (Pest arch) käy läpi jokaisen `app/Modules`-hakemiston ja tarkistaa yllä olevat säännöt, `declare(strict_types=1)`:n Domainissa ja Applicationissa sekä DTO:iden readonly-luonteen. Uusi moduuli tulee mukaan ilman muutoksia.
@@ -154,7 +160,7 @@ Kiertäviä riippuvuuksia (A käyttää B:n rajapintaa ja B A:n) vältetään: t
| Validointivirhe | Livewire Form (`validate()`) | Livewire näyttää kenttävirheen |
| Domain-poikkeus | Domain / Use Case | Presentation muuntaa kenttävirheeksi tai ilmoitukseksi käännösavaimella |
| Ei löydy | Kyselyrajapinta palauttaa `null` | Presentation: `abort(404)` |
| Valtuutus | Policy / Gate (tulee roolityön myötä) | 403 |
| Valtuutus | Gate (`users.manage`, `customers.use`): reitin `can:`-middleware ja `authorize()` komponentin `mount`- ja toimintometodeissa | 403 |
| Infrastruktuurivirhe | Tietokanta, API | Laravelin virheenkäsittelijä ja loki |
Try/catch-lohkoja ei laiteta joka metodiin. Virhe käsitellään siellä, missä tiedetään, mitä sille tehdään.
@@ -205,4 +211,13 @@ Esimerkki: vaiheen 1 `CustomerJobs` (asiakastyöt).
| Moduulikohtaiset migraatiot | `database/migrations` | Laravelin normaalit hakemistot säilytetään. |
| Application ei riipu Laravelista | Sallittu: `Illuminate\Contracts\Pagination` | Sivutus ilman omaa abstraktiota (ks. luku 3). |
| Entiteetti kerää tapahtumansa | Use case julkaisee tapahtuman tallennuksen jälkeen | Uusi entiteetti saa id:n vasta tallennuksessa, ja tapahtuma tarvitsee id:n. Tämä on yksinkertaisempaa kuin tapahtumien keruumekanismi. |
| `App\Models\User` | Ennallaan | Siirretään omaan moduuliin käyttäjä-, rooli- ja kirjautumistyön yhteydessä. |
| Eloquent-mallit moduulin Infrastructure-kansiossa | `App\Models\User` pysyy paikallaan | Laravelin autentikointi, `config/auth.php`, factoryt ja testit odottavat sitä. Se on Users-moduulin persistenssimalli (luku 13). |
## 13. Users-moduuli ja kirjautuminen
- **Roolit** (`Role`): pääkäyttäjä, johto, työntekijä, harjoittelija ja alihankkija. Vain pääkäyttäjä hallitsee käyttäjiä (`users.manage`). Alihankkijat eivät käytä asiakasrekisteriä (`customers.use`).
- **`UserAccount`-entiteetti** on liiketoimintanäkymä käyttäjään, ja `App\Models\User` on sen tallennusmalli. Harjoittelijalla on aina viimeinen päivä ja vastuuhenkilö (aktiivinen johto tai työntekijä). Muilla rooleilla niitä ei ole. Viimeistä aktiivista pääkäyttäjää ei voi poistaa käytöstä eikä vaihtaa toiseen rooliin.
- **Kirjautuminen** käyttää Laravelin `Auth::attemptWhen`ia. Ehtona on `CheckLoginAllowed`: käyttäjä on aktiivinen eikä harjoittelijan viimeinen päivä ole mennyt. Päivä lasketaan aikavyöhykkeessä `config('app.business_timezone')` (oletus `Europe/Helsinki`). Yrityksiä saa 5 minuutissa sähköposti+IP-paria kohden.
- **`EnsureAccountIsUsable`-middleware** tarkistaa saman ehdon jokaisessa web-pyynnössä. Kun pääkäyttäjä poistaa käyttäjän käytöstä tai harjoittelu päättyy, istunto katkeaa heti.
- **Salasanat:** kukaan ei käsittele niitä selväkielisinä. Uusi käyttäjä ja "Unohditko salasanan?" saavat saman "Aseta salasana" -sähköpostin (Laravelin Password broker, linkki voimassa 60 min). Salasanassa on oltava vähintään 12 merkkiä.
- **Ensimmäinen pääkäyttäjä:** `php artisan users:create-admin "Nimi" [email protected]`. Kun `MAIL_MAILER=log`, linkki löytyy tiedostosta `storage/logs/laravel.log`.
+3 -1
View File
@@ -2,5 +2,7 @@
"Showing": "Tulokset",
"to": "–",
"of": "/",
"results": "kpl"
"results": "kpl",
"All rights reserved.": "Kaikki oikeudet pidätetään.",
"If you're having trouble clicking the \":actionText\" button, copy and paste the URL below\ninto your web browser:": "Jos \":actionText\"-painike ei toimi, kopioi alla oleva osoite selaimesi osoiteriville:"
}
+35
View File
@@ -0,0 +1,35 @@
<?php
return [
'failed' => 'Sähköposti tai salasana on väärin.',
'password' => 'Salasana on väärin.',
'throttle' => 'Liian monta kirjautumisyritystä. Yritä uudelleen :seconds sekunnin kuluttua.',
'account_disabled' => 'Käyttöoikeutesi on päättynyt. Ota yhteyttä pääkäyttäjään.',
'logged_out' => 'Olet kirjautunut ulos.',
'login_title' => 'Kirjaudu sisään',
'login' => 'Kirjaudu',
'email' => 'Sähköposti',
'password_label' => 'Salasana',
'remember' => 'Muista minut tällä laitteella',
'forgot_password' => 'Unohditko salasanan?',
'forgot_title' => 'Salasanan asettaminen',
'forgot_intro' => 'Anna käyttäjätunnuksesi sähköpostiosoite. Lähetämme siihen linkin, jolla voit asettaa uuden salasanan.',
'forgot_submit' => 'Lähetä linkki',
'forgot_sent' => 'Jos osoitteella on käyttäjätunnus, lähetimme siihen linkin salasanan asettamiseen.',
'back_to_login' => 'Takaisin kirjautumiseen',
'reset_title' => 'Aseta salasana',
'reset_intro' => 'Valitse uusi salasana. Sen jälkeen voit kirjautua sisään.',
'new_password' => 'Uusi salasana',
'confirm_password' => 'Uusi salasana uudelleen',
'password_rules' => 'Vähintään 12 merkkiä.',
'reset_submit' => 'Tallenna salasana',
'email_required' => 'Anna sähköpostiosoite.',
'email_invalid' => 'Sähköpostiosoite ei ole kelvollinen.',
'password_required' => 'Anna salasana.',
'password_mismatch' => 'Salasanat eivät täsmää.',
'password_too_short' => 'Salasanassa on oltava vähintään :min merkkiä.',
];
+11
View File
@@ -0,0 +1,11 @@
<?php
return [
'skip_to_content' => 'Siirry pääsisältöön',
'main_menu' => 'Päävalikko',
'home' => 'Etusivu',
'customers' => 'Asiakkaat',
'users' => 'Käyttäjät',
'signed_in_as' => 'Kirjautuneena: :name',
'logout' => 'Kirjaudu ulos',
];
+9
View File
@@ -0,0 +1,9 @@
<?php
return [
'reset' => 'Salasana on tallennettu. Voit nyt kirjautua sisään.',
'sent' => 'Lähetimme linkin salasanan asettamiseen.',
'throttled' => 'Odota hetki ennen kuin pyydät uuden linkin.',
'token' => 'Linkki on vanhentunut tai virheellinen. Pyydä uusi linkki.',
'user' => 'Linkki on vanhentunut tai virheellinen. Pyydä uusi linkki.',
];
+73
View File
@@ -0,0 +1,73 @@
<?php
return [
'title' => 'Käyttäjät',
'create_title' => 'Uusi käyttäjä',
'edit_title' => 'Muokkaa käyttäjää',
'new' => 'Uusi käyttäjä',
'edit' => 'Muokkaa',
'save' => 'Tallenna',
'cancel' => 'Peruuta',
'search' => 'Hae käyttäjää',
'search_description' => 'Hae nimellä tai sähköpostilla.',
'empty' => 'Käyttäjiä ei löytynyt.',
'result_count' => '{0} Ei käyttäjiä|{1} :count käyttäjä|[2,*] :count käyttäjää',
'created' => 'Käyttäjä :name lisätty. Lähetimme hänelle linkin salasanan asettamiseen.',
'updated' => 'Käyttäjän :name tiedot tallennettu.',
'send_link' => 'Lähetä salasanan asetuslinkki',
'link_sent' => 'Lähetimme linkin salasanan asettamiseen osoitteeseen :email.',
'link_throttled' => 'Linkki lähetettiin juuri. Odota hetki ennen kuin lähetät uuden.',
'fields' => [
'name' => 'Nimi',
'email' => 'Sähköposti',
'role' => 'Rooli',
'status' => 'Tila',
'active' => 'Aktiivinen',
'active_description' => 'Ei-aktiivinen käyttäjä ei voi kirjautua. Hänen tietonsa säilyvät.',
'employment_ends_on' => 'Harjoittelun viimeinen päivä',
'employment_ends_on_description' => 'Harjoittelija voi kirjautua tämän päivän loppuun asti.',
'supervisor' => 'Vastuuhenkilö',
'supervisor_placeholder' => 'Valitse vastuuhenkilö',
],
'roles' => [
'admin' => 'Pääkäyttäjä',
'management' => 'Johto',
'employee' => 'Työntekijä',
'intern' => 'Harjoittelija',
'subcontractor' => 'Alihankkija',
],
'status' => [
'active' => 'Aktiivinen',
'inactive' => 'Ei käytössä',
'ends_on' => 'Päättyy :date',
'ended_on' => 'Päättyi :date',
],
'errors' => [
'name_required' => 'Anna nimi.',
'invalid_name' => 'Nimen pituus voi olla enintään 255 merkkiä.',
'email_required' => 'Anna sähköpostiosoite.',
'invalid_email' => 'Sähköpostiosoite ei ole kelvollinen.',
'email_taken' => 'Tällä sähköpostiosoitteella on jo käyttäjä.',
'role_required' => 'Valitse rooli.',
'end_date_required' => 'Anna harjoittelun viimeinen päivä.',
'end_date_invalid' => 'Päivämäärä ei ole kelvollinen.',
'supervisor_required' => 'Valitse harjoittelijalle vastuuhenkilö.',
'invalid_supervisor' => 'Vastuuhenkilön on oltava aktiivinen johdon tai työntekijän roolissa oleva käyttäjä.',
'last_admin' => 'Viimeistä aktiivista pääkäyttäjää ei voi poistaa käytöstä eikä vaihtaa toiseen rooliin.',
],
'password_mail' => [
'subject' => 'Aseta salasana',
'greeting' => 'Hei!',
'intro' => 'Voit asettaa salasanan toiminnanohjausjärjestelmän käyttäjätunnuksellesi alla olevasta painikkeesta.',
'action' => 'Aseta salasana',
'expires' => 'Linkki on voimassa :count minuuttia.',
'ignore' => 'Jos et odottanut tätä viestiä, sinun ei tarvitse tehdä mitään.',
],
];
+34 -1
View File
@@ -19,9 +19,42 @@
href="#main-content"
class="sr-only focus:not-sr-only focus:fixed focus:start-4 focus:top-4 focus:z-50 focus:rounded-md focus:bg-white focus:px-4 focus:py-2 focus:text-zinc-900 focus:shadow-lg focus:outline-2 focus:outline-offset-2 focus:outline-blue-700"
>
Siirry pääsisältöön
{{ __('layout.skip_to_content') }}
</a>
@auth
<header class="border-b border-zinc-200 dark:border-zinc-700">
<div class="mx-auto flex max-w-5xl flex-wrap items-center gap-x-6 gap-y-2 px-4 py-3 sm:px-6">
<flux:link :href="route('home')" wire:navigate variant="subtle" class="font-semibold">
{{ config('app.name') }}
</flux:link>
<flux:navbar :aria-label="__('layout.main_menu')" class="flex-1 py-0">
<flux:navbar.item :href="route('customers.index')" :current="request()->routeIs('customers.*')" wire:navigate>
{{ __('layout.customers') }}
</flux:navbar.item>
@can('users.manage')
<flux:navbar.item :href="route('users.index')" :current="request()->routeIs('users.*')" wire:navigate>
{{ __('layout.users') }}
</flux:navbar.item>
@endcan
</flux:navbar>
<div class="flex flex-wrap items-center gap-3">
<flux:text size="sm">{{ __('layout.signed_in_as', ['name' => auth()->user()->name]) }}</flux:text>
<form method="POST" action="{{ route('logout') }}">
@csrf
<flux:button type="submit" variant="ghost" size="sm" icon="arrow-right-start-on-rectangle">
{{ __('layout.logout') }}
</flux:button>
</form>
</div>
</div>
</header>
@endauth
<main id="main-content" tabindex="-1" class="focus:outline-none">
{{ $slot }}
</main>
+1 -29
View File
@@ -1,33 +1,5 @@
<?php
use App\Models\User;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Route;
use Illuminate\Support\Str;
Route::livewire('/', 'pages::home')->name('home');
/*
|--------------------------------------------------------------------------
| Local test login
|--------------------------------------------------------------------------
|
| Temporary stand-in for the real login, which arrives in phase 1. Exists
| only when APP_ENV=local: it signs in a test user and returns to the page
| that asked for login. Named "login" so the auth middleware redirects here.
| Remove it when the real login page is built.
|
*/
if (app()->environment('local')) {
Route::get('/dev/login', function () {
$user = User::query()->firstOrCreate(
['email' => '[email protected]'],
['name' => 'Testikäyttäjä', 'password' => Str::password()],
);
Auth::login($user);
request()->session()->regenerate();
return redirect()->intended(route('customers.index'));
})->middleware('web')->name('login');
}
Route::livewire('/', 'pages::home')->middleware('auth')->name('home');
+17 -1
View File
@@ -1,5 +1,14 @@
<?php
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
uses(RefreshDatabase::class);
beforeEach(function () {
$this->actingAs(User::factory()->admin()->create());
});
it('has no accessibility issues on the home page', function (string $device, string $colorScheme) {
$page = visit(route('home'));
@@ -21,8 +30,15 @@ it('can be operated with the keyboard alone', function () {
$page->keys('html > body', 'Tab')
->assertScript('document.activeElement.textContent.trim()', 'Siirry pääsisältöön')
->keys('a[href="#main-content"]', 'Tab')
->keys('a[href="#main-content"]', 'Enter')
->keys('#main-content', 'Tab')
->assertScript('document.activeElement.textContent.trim()', 'Lisää klikkaus')
->keys('#main-content button', 'Enter')
->assertSeeIn('[role="status"]', 'Klikattu 1 kertaa');
});
it('reaches the main menu with the keyboard', function () {
visit(route('home'))
->keys('html > body', ['Tab', 'Tab', 'Tab'])
->assertScript('document.activeElement.closest("nav")?.getAttribute("aria-label")', 'Päävalikko');
});
+2 -1
View File
@@ -46,7 +46,8 @@ it('creates a customer with the keyboard alone', function () {
visit(route('customers.create'))
->keys('html > body', 'Tab')
->assertScript('document.activeElement.textContent.trim()', 'Siirry pääsisältöön')
->keys('a[href="#main-content"]', 'Tab')
->keys('a[href="#main-content"]', 'Enter')
->keys('#main-content', 'Tab')
->assertScript('document.activeElement.getAttribute("wire:model")', 'form.name')
->type('[wire\\:model="form.name"]', 'Mainos Oy')
->keys('[wire\\:model="form.name"]', 'Enter')
+80
View File
@@ -0,0 +1,80 @@
<?php
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Pest\Browser\Api\AwaitableWebpage;
use Pest\Browser\Api\PendingAwaitablePage;
uses(RefreshDatabase::class);
$devicesAndSchemes = [
'desktop, light' => ['desktop', 'light'],
'desktop, dark' => ['desktop', 'dark'],
'mobile, light' => ['mobile', 'light'],
'mobile, dark' => ['mobile', 'dark'],
];
/**
* @param PendingAwaitablePage|AwaitableWebpage $page
*/
function onDeviceAndScheme(mixed $page, string $device, string $colorScheme): mixed
{
$page = $device === 'mobile' ? $page->on()->mobile() : $page->on()->desktop();
return $colorScheme === 'dark' ? $page->inDarkMode() : $page->inLightMode();
}
it('has no accessibility issues on the guest pages', function (string $routeName, string $device, string $colorScheme) {
$url = $routeName === 'password.reset'
? route($routeName, ['token' => 'token', 'email' => '[email protected]'])
: route($routeName);
onDeviceAndScheme(visit($url), $device, $colorScheme)
->assertNoJavaScriptErrors()
->assertNoAccessibilityIssues(level: 2);
})->with([
'login' => 'login',
'forgot password' => 'password.request',
'reset password' => 'password.reset',
])->with($devicesAndSchemes);
it('has no accessibility issues on the user admin pages', function (string $page, string $device, string $colorScheme) {
$admin = User::factory()->admin()->create();
$intern = User::factory()->intern('2027-05-31')->create();
$this->actingAs($admin);
$url = match ($page) {
'list' => route('users.index'),
'create' => route('users.create'),
'edit intern' => route('users.edit', $intern->id),
};
onDeviceAndScheme(visit($url), $device, $colorScheme)
->assertNoJavaScriptErrors()
->assertNoAccessibilityIssues(level: 2);
})->with(['list', 'create', 'edit intern'])->with($devicesAndSchemes);
it('shows a login error without accessibility issues', function (string $colorScheme) {
$page = onDeviceAndScheme(visit(route('login')), 'desktop', $colorScheme);
$page->fill('[wire\\:model="email"]', '[email protected]')
->fill('[wire\\:model="password"]', 'väärä-salasana')
->press('Kirjaudu')
->assertSee('Sähköposti tai salasana on väärin.')
->assertNoAccessibilityIssues(level: 2);
})->with(['light', 'dark']);
it('logs in with the keyboard alone', function () {
User::factory()->create(['email' => '[email protected]']);
visit(route('login'))
->keys('html > body', 'Tab')
->keys('a[href="#main-content"]', 'Enter')
->keys('#main-content', 'Tab')
->assertScript('document.activeElement.getAttribute("wire:model")', 'email')
->type('[wire\\:model="email"]', '[email protected]')
->type('[wire\\:model="password"]', 'password')
->keys('[wire\\:model="password"]', 'Enter')
->assertPathIs('/')
->assertSee('Kirjaudu ulos');
});
+16
View File
@@ -0,0 +1,16 @@
<?php
namespace Tests\Fakes;
use App\Modules\Users\Application\Contracts\Clock;
use DateTimeImmutable;
class FakeClock implements Clock
{
public function __construct(public DateTimeImmutable $today) {}
public function today(): DateTimeImmutable
{
return $this->today;
}
}
+21
View File
@@ -0,0 +1,21 @@
<?php
namespace Tests\Fakes;
use App\Modules\Users\Application\Contracts\PasswordLinkSender;
use App\Modules\Users\Domain\ValueObjects\EmailAddress;
class FakePasswordLinkSender implements PasswordLinkSender
{
/**
* @var list<string>
*/
public array $sentTo = [];
public function sendSetupLink(EmailAddress $email): bool
{
$this->sentTo[] = $email->value;
return true;
}
}
@@ -0,0 +1,59 @@
<?php
namespace Tests\Fakes;
use App\Modules\Users\Domain\Contracts\UserAccountRepository;
use App\Modules\Users\Domain\Entities\UserAccount;
use App\Modules\Users\Domain\ValueObjects\EmailAddress;
class InMemoryUserAccountRepository implements UserAccountRepository
{
/**
* @var array<int, UserAccount>
*/
public array $users = [];
private int $nextId = 1;
public function findById(int $id): ?UserAccount
{
return isset($this->users[$id]) ? clone $this->users[$id] : null;
}
public function save(UserAccount $user): UserAccount
{
$id = $user->id() ?? $this->nextId++;
$this->users[$id] = UserAccount::reconstitute(
$id,
$user->name(),
$user->email(),
$user->role(),
$user->isActive(),
$user->employmentEndsOn(),
$user->supervisorId(),
);
return clone $this->users[$id];
}
public function isEmailTaken(EmailAddress $email, ?int $exceptUserId = null): bool
{
foreach ($this->users as $id => $user) {
if ($id !== $exceptUserId && $user->email()->equals($email)) {
return true;
}
}
return false;
}
public function countActiveAdmins(?int $exceptUserId = null): int
{
return count(array_filter(
$this->users,
fn (UserAccount $user, int $id): bool => $id !== $exceptUserId && $user->isActiveAdmin(),
ARRAY_FILTER_USE_BOTH,
));
}
}
+2 -4
View File
@@ -1,7 +1,5 @@
<?php
test('the application returns a successful response', function () {
$response = $this->get('/');
$response->assertStatus(200);
test('the application sends guests to the login page', function () {
$this->get('/')->assertRedirect(route('login'));
});
+12 -2
View File
@@ -1,13 +1,23 @@
<?php
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Livewire\Livewire;
it('renders the home page', function () {
uses(RefreshDatabase::class);
beforeEach(function () {
$this->actingAs(User::factory()->create(['name' => 'Eero Esimerkki']));
});
it('renders the home page with the main menu', function () {
$this->get(route('home'))
->assertOk()
->assertSee('Toiminnanohjaus')
->assertSee('Siirry pääsisältöön')
->assertSee('id="main-content"', false);
->assertSee('id="main-content"', false)
->assertSee('aria-label="Päävalikko"', false)
->assertSee('Kirjautuneena: Eero Esimerkki');
});
it('increments the click count', function () {
-10
View File
@@ -1,10 +0,0 @@
<?php
use Illuminate\Support\Facades\Route;
it('does not offer the local test login outside the local environment', function () {
expect(app()->environment())->not->toBe('local')
->and(Route::has('login'))->toBeFalse();
$this->get('/dev/login')->assertNotFound();
});
@@ -0,0 +1,30 @@
<?php
use App\Models\User;
use App\Modules\Customers\Infrastructure\Persistence\Eloquent\CustomerModel;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Livewire\Features\SupportLockedProperties\CannotUpdateLockedPropertyException;
use Livewire\Livewire;
uses(RefreshDatabase::class);
it('lets every role except subcontractors use the customer pages', function (string $state, int $status) {
$user = User::factory()->{$state}()->create();
$this->actingAs($user)->get(route('customers.index'))->assertStatus($status);
$this->actingAs($user)->get(route('customers.create'))->assertStatus($status);
})->with([
'admin' => ['admin', 200],
'management' => ['management', 200],
'employee' => ['employee', 200],
'intern' => ['intern', 200],
'subcontractor' => ['subcontractor', 403],
]);
it('does not let the customer id be changed in the browser', function () {
$customer = CustomerModel::factory()->create();
Livewire::actingAs(User::factory()->create())
->test('customers::form')
->set('customerId', $customer->id);
})->throws(CannotUpdateLockedPropertyException::class);
@@ -0,0 +1,32 @@
<?php
use App\Models\User;
use App\Modules\Users\Domain\Enums\Role;
use Illuminate\Auth\Notifications\ResetPassword;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Notification;
uses(RefreshDatabase::class);
it('creates an admin and emails a set-password link', function () {
Notification::fake();
$this->artisan('users:create-admin', ['name' => 'Anna Admin', 'email' => '[email protected]'])
->assertSuccessful();
$admin = User::query()->sole();
expect($admin->role)->toBe(Role::Admin)
->and($admin->email)->toBe('[email protected]');
Notification::assertSentTo($admin, ResetPassword::class);
});
it('fails for an email address that is in use', function () {
User::factory()->create(['email' => '[email protected]']);
$this->artisan('users:create-admin', ['name' => 'Anna Admin', 'email' => '[email protected]'])
->assertFailed();
expect(User::query()->count())->toBe(1);
});
+118
View File
@@ -0,0 +1,118 @@
<?php
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\RateLimiter;
use Livewire\Livewire;
uses(RefreshDatabase::class);
beforeEach(function () {
$this->travelTo(now('Europe/Helsinki')->setDate(2027, 5, 31)->setTime(12, 0));
});
it('sends guests to the login page and back where they were going', function () {
$user = User::factory()->create(['email' => '[email protected]']);
$this->get(route('customers.index'))->assertRedirect(route('login'));
$this->get(route('login'))->assertOk()->assertSee('Kirjaudu sisään');
Livewire::test('users::login')
->set('email', ' [email protected] ')
->set('password', 'password')
->call('login')
->assertHasNoErrors()
->assertRedirect(route('customers.index'));
$this->assertAuthenticatedAs($user);
});
it('rejects a wrong password', function () {
User::factory()->create(['email' => '[email protected]']);
Livewire::test('users::login')
->set('email', '[email protected]')
->set('password', 'väärä')
->call('login')
->assertHasErrors(['email'])
->assertSee('Sähköposti tai salasana on väärin.')
->assertSet('password', '');
$this->assertGuest();
});
it('does not let a deactivated user or an intern past the last day log in', function (string $state) {
$factory = User::factory();
$user = match ($state) {
'inactive' => $factory->inactive()->create(),
'intern ended yesterday' => $factory->intern('2027-05-30')->create(),
};
Livewire::test('users::login')
->set('email', $user->email)
->set('password', 'password')
->call('login')
->assertHasErrors(['email'])
->assertSee('Käyttöoikeutesi on päättynyt.');
$this->assertGuest();
})->with(['inactive', 'intern ended yesterday']);
it('lets an intern log in on the last day', function () {
$intern = User::factory()->intern('2027-05-31')->create();
Livewire::test('users::login')
->set('email', $intern->email)
->set('password', 'password')
->call('login')
->assertHasNoErrors();
$this->assertAuthenticatedAs($intern);
});
it('blocks login after five failed attempts', function () {
RateLimiter::clear('[email protected]|127.0.0.1');
User::factory()->create(['email' => '[email protected]']);
$login = Livewire::test('users::login')->set('email', '[email protected]');
foreach (range(1, 5) as $attempt) {
$login->set('password', 'väärä')->call('login');
}
$login->set('password', 'password')
->call('login')
->assertHasErrors(['email'])
->assertSee('Liian monta kirjautumisyritystä.');
$this->assertGuest();
});
it('ends the session of a user who is deactivated while signed in', function () {
$user = User::factory()->create();
$this->actingAs($user)->get(route('customers.index'))->assertOk();
$user->update(['is_active' => false]);
$this->get(route('customers.index'))
->assertRedirect(route('login'))
->assertSessionHas('status', 'Käyttöoikeutesi on päättynyt. Ota yhteyttä pääkäyttäjään.');
$this->assertGuest();
});
it('logs out', function () {
$this->actingAs(User::factory()->create())
->post(route('logout'))
->assertRedirect(route('login'));
$this->assertGuest();
});
it('sends signed-in users away from the login page', function () {
$this->actingAs(User::factory()->create())
->get(route('login'))
->assertRedirect(route('home'));
});
@@ -0,0 +1,91 @@
<?php
use App\Models\User;
use Illuminate\Auth\Notifications\ResetPassword;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Notification;
use Illuminate\Support\Facades\Password;
use Livewire\Livewire;
uses(RefreshDatabase::class);
it('emails a Finnish set-password link to a known address', function () {
Notification::fake();
$user = User::factory()->create(['email' => '[email protected]']);
$this->get(route('password.request'))->assertOk();
Livewire::test('users::forgot-password')
->set('email', '[email protected]')
->call('sendLink')
->assertHasNoErrors()
->assertSee('Jos osoitteella on käyttäjätunnus');
Notification::assertSentTo($user, ResetPassword::class, function (ResetPassword $notification) use ($user) {
$mail = $notification->toMail($user);
return $mail->subject === 'Aseta salasana'
&& str_contains($mail->actionUrl, '/reset-password/'.$notification->token);
});
});
it('renders the whole set-password email in Finnish', function () {
$user = User::factory()->create();
$html = (string) (new ResetPassword('token'))->toMail($user)->render();
expect($html)->toContain('Aseta salasana')
->toContain('kopioi alla oleva osoite')
->toContain('Kaikki oikeudet pidätetään.')
->not->toContain('All rights reserved');
});
it('shows the same message for an unknown address', function () {
Notification::fake();
Livewire::test('users::forgot-password')
->set('email', '[email protected]')
->call('sendLink')
->assertHasNoErrors()
->assertSee('Jos osoitteella on käyttäjätunnus');
Notification::assertNothingSent();
});
it('sets a new password with a valid link', function () {
$user = User::factory()->create(['email' => '[email protected]']);
$token = Password::createToken($user);
$this->get(route('password.reset', ['token' => $token, 'email' => $user->email]))
->assertOk()
->assertSee('Aseta salasana');
Livewire::test('users::reset-password', ['token' => $token])
->set('email', '[email protected]')
->set('password', 'uusi-salasana-123')
->set('password_confirmation', 'uusi-salasana-123')
->call('resetPassword')
->assertHasNoErrors()
->assertRedirect(route('login'));
expect(Hash::check('uusi-salasana-123', $user->fresh()->password))->toBeTrue();
});
it('rejects a short password and an invalid link', function () {
$user = User::factory()->create(['email' => '[email protected]']);
Livewire::test('users::reset-password', ['token' => 'väärä'])
->set('email', '[email protected]')
->set('password', 'lyhyt')
->set('password_confirmation', 'lyhyt')
->call('resetPassword')
->assertHasErrors(['password'])
->set('password', 'uusi-salasana-123')
->set('password_confirmation', 'uusi-salasana-123')
->call('resetPassword')
->assertHasErrors(['email'])
->assertSee('Linkki on vanhentunut tai virheellinen.');
expect(Hash::check('password', $user->fresh()->password))->toBeTrue();
});
@@ -0,0 +1,143 @@
<?php
use App\Models\User;
use App\Modules\Users\Domain\Enums\Role;
use Illuminate\Auth\Notifications\ResetPassword;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Notification;
use Livewire\Features\SupportLockedProperties\CannotUpdateLockedPropertyException;
use Livewire\Livewire;
uses(RefreshDatabase::class);
beforeEach(function () {
Notification::fake();
$this->admin = User::factory()->admin()->create(['name' => 'Anna Admin']);
});
it('only lets admins manage users', function (string $state, int $status) {
$user = User::factory()->{$state}()->create();
$this->actingAs($user)->get(route('users.index'))->assertStatus($status);
$this->actingAs($user)->get(route('users.create'))->assertStatus($status);
})->with([
'admin' => ['admin', 200],
'management' => ['management', 403],
'employee' => ['employee', 403],
'intern' => ['intern', 403],
'subcontractor' => ['subcontractor', 403],
]);
it('lists users with their role and status', function () {
$supervisor = User::factory()->create(['name' => 'Eero Työntekijä']);
User::factory()->intern('2027-05-31', $supervisor)->create(['name' => 'Ida Harjoittelija']);
User::factory()->inactive()->create(['name' => 'Pekka Poissa']);
$this->actingAs($this->admin)->get(route('users.index'))
->assertOk()
->assertSee('Ida Harjoittelija')
->assertSee('Harjoittelija')
->assertSee('Vastuuhenkilö: Eero Työntekijä')
->assertSee('Päättyy 31.5.2027')
->assertSee('Ei käytössä');
});
it('creates an intern and emails a set-password link', function () {
$supervisor = User::factory()->create();
Livewire::actingAs($this->admin)
->test('users::form')
->set('form.name', 'Ida Harjoittelija')
->set('form.email', '[email protected]')
->set('form.role', 'intern')
->set('form.employment_ends_on', '2027-05-31')
->set('form.supervisor_id', (string) $supervisor->id)
->call('save')
->assertHasNoErrors()
->assertRedirect(route('users.index'));
$intern = User::query()->where('email', '[email protected]')->sole();
expect($intern->role)->toBe(Role::Intern)
->and($intern->employment_ends_on?->toDateString())->toBe('2027-05-31')
->and($intern->supervisor_id)->toBe($supervisor->id);
Notification::assertSentTo($intern, ResetPassword::class);
});
it('requires an end date and a supervisor for an intern', function () {
Livewire::actingAs($this->admin)
->test('users::form')
->set('form.name', 'Ida')
->set('form.email', '[email protected]')
->set('form.role', 'intern')
->call('save')
->assertHasErrors(['form.employment_ends_on', 'form.supervisor_id'])
->assertSee('Anna harjoittelun viimeinen päivä.');
});
it('rejects an admin as an intern supervisor', function () {
Livewire::actingAs($this->admin)
->test('users::form')
->set('form.name', 'Ida')
->set('form.email', '[email protected]')
->set('form.role', 'intern')
->set('form.employment_ends_on', '2027-05-31')
->set('form.supervisor_id', (string) $this->admin->id)
->call('save')
->assertHasErrors(['form.supervisor_id']);
});
it('rejects an email address that is in use', function () {
Livewire::actingAs($this->admin)
->test('users::form')
->set('form.name', 'Toinen Anna')
->set('form.email', strtoupper($this->admin->email))
->call('save')
->assertHasErrors(['form.email'])
->assertSee('Tällä sähköpostiosoitteella on jo käyttäjä.');
});
it('deactivates a user', function () {
$user = User::factory()->create();
Livewire::actingAs($this->admin)
->test('users::form', ['user' => $user->id])
->set('form.active', false)
->call('save')
->assertHasNoErrors();
expect($user->fresh()->is_active)->toBeFalse();
});
it('does not let the last admin deactivate themselves', function () {
Livewire::actingAs($this->admin)
->test('users::form', ['user' => $this->admin->id])
->set('form.active', false)
->call('save')
->assertHasErrors(['form.role'])
->assertSee('Viimeistä aktiivista pääkäyttäjää ei voi poistaa käytöstä');
expect($this->admin->fresh()->is_active)->toBeTrue();
});
it('sends a set-password link from the edit page', function () {
$user = User::factory()->create(['email' => '[email protected]']);
Livewire::actingAs($this->admin)
->test('users::form', ['user' => $user->id])
->call('sendPasswordLink')
->assertSee('Lähetimme linkin salasanan asettamiseen osoitteeseen [email protected].');
Notification::assertSentTo($user, ResetPassword::class);
});
it('does not let the user id be changed in the browser', function () {
Livewire::actingAs($this->admin)
->test('users::form')
->set('userId', 1);
})->throws(CannotUpdateLockedPropertyException::class);
it('returns 404 for an unknown user', function () {
$this->actingAs($this->admin)->get(route('users.edit', 999))->assertNotFound();
});
+3 -1
View File
@@ -42,9 +42,11 @@ foreach ($modules as $module) {
$root.'\\Presentation',
]);
// Service providers are the module's composition root: they may register its commands and middleware.
arch("{$module}: infrastructure does not depend on presentation")
->expect($root.'\\Infrastructure')
->not->toUse($root.'\\Presentation');
->not->toUse($root.'\\Presentation')
->ignoring($root.'\\Infrastructure\\Providers');
$otherModules = array_values(array_diff($modules, [$module]));
@@ -0,0 +1,111 @@
<?php
use App\Modules\Users\Application\DTOs\UserAccountData;
use App\Modules\Users\Application\UseCases\CheckLoginAllowed;
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\Entities\UserAccount;
use App\Modules\Users\Domain\Enums\Role;
use App\Modules\Users\Domain\Exceptions\EmailAlreadyInUse;
use App\Modules\Users\Domain\Exceptions\InvalidSupervisor;
use App\Modules\Users\Domain\Exceptions\LastAdminCannotBeRemoved;
use App\Modules\Users\Domain\Exceptions\UserAccountNotFound;
use App\Modules\Users\Domain\Services\SupervisorRule;
use App\Modules\Users\Domain\ValueObjects\EmailAddress;
use App\Modules\Users\Domain\ValueObjects\PersonName;
use Tests\Fakes\FakeClock;
use Tests\Fakes\FakePasswordLinkSender;
use Tests\Fakes\FakeTransactionManager;
use Tests\Fakes\InMemoryUserAccountRepository;
beforeEach(function () {
$this->users = new InMemoryUserAccountRepository;
$this->passwordLinks = new FakePasswordLinkSender;
$supervisorRule = new SupervisorRule($this->users);
$transactions = new FakeTransactionManager;
$this->createUser = new CreateUserAccount($this->users, $supervisorRule, $transactions, $this->passwordLinks);
$this->updateUser = new UpdateUserAccount($this->users, $supervisorRule, $transactions);
$this->adminId = $this->users->save(UserAccount::register(new PersonName('Anna Admin'), new EmailAddress('[email protected]'), Role::Admin))->id();
$this->employeeId = $this->users->save(UserAccount::register(new PersonName('Eero Työntekijä'), new EmailAddress('[email protected]'), Role::Employee))->id();
});
it('creates a user and sends a link for setting the password', function () {
$userId = $this->createUser->execute(new UserAccountData('Maija Meikäläinen', '[email protected]', Role::Employee));
expect($this->users->findById($userId)?->email()->value)->toBe('[email protected]')
->and($this->passwordLinks->sentTo)->toBe(['[email protected]']);
});
it('creates an intern with an end date and a supervisor', function () {
$userId = $this->createUser->execute(new UserAccountData('Ida', '[email protected]', Role::Intern, true, '2027-05-31', $this->employeeId));
$intern = $this->users->findById($userId);
expect($intern?->employmentEndsOn()?->format('Y-m-d'))->toBe('2027-05-31')
->and($intern?->supervisorId())->toBe($this->employeeId);
});
it('rejects a supervisor who cannot supervise', function (string $case) {
$supervisorId = match ($case) {
'admin' => $this->adminId,
'unknown' => 999,
'inactive' => $this->users->save(UserAccount::reconstitute(50, new PersonName('Pois'), new EmailAddress('[email protected]'), Role::Employee, false, null, null))->id(),
};
$this->createUser->execute(new UserAccountData('Ida', '[email protected]', Role::Intern, true, '2027-05-31', $supervisorId));
})->throws(InvalidSupervisor::class)->with(['admin', 'unknown', 'inactive']);
it('rejects an email address that another user has', function () {
expect(fn () => $this->createUser->execute(new UserAccountData('Toinen Eero', '[email protected]', Role::Employee)))
->toThrow(EmailAlreadyInUse::class)
->and($this->passwordLinks->sentTo)->toBeEmpty();
});
it('does not let the last active admin be deactivated or demoted', function (bool $active, Role $role) {
$this->updateUser->execute($this->adminId, new UserAccountData('Anna Admin', '[email protected]', $role, $active));
})->throws(LastAdminCannotBeRemoved::class)->with([
'deactivated' => [false, Role::Admin],
'demoted' => [true, Role::Management],
]);
it('lets an admin be demoted when another active admin remains', function () {
$this->users->save(UserAccount::register(new PersonName('Toinen Admin'), new EmailAddress('[email protected]'), Role::Admin));
$this->updateUser->execute($this->adminId, new UserAccountData('Anna Admin', '[email protected]', Role::Management));
expect($this->users->findById($this->adminId)?->role())->toBe(Role::Management);
});
it('fails to update an unknown user', function () {
$this->updateUser->execute(999, new UserAccountData('X', '[email protected]', Role::Employee));
})->throws(UserAccountNotFound::class);
it('sends a password link to a stored user', function () {
(new SendPasswordSetupLink($this->users, $this->passwordLinks))->execute($this->employeeId);
expect($this->passwordLinks->sentTo)->toBe(['[email protected]']);
});
it('checks whether a user may log in today', function () {
$internId = $this->createUser->execute(new UserAccountData('Ida', '[email protected]', Role::Intern, true, '2027-05-31', $this->employeeId));
$clock = new FakeClock(new DateTimeImmutable('2027-05-31'));
$checkLogin = new CheckLoginAllowed($this->users, $clock);
expect($checkLogin->execute($internId))->toBeTrue()
->and($checkLogin->execute(999))->toBeFalse();
$clock->today = new DateTimeImmutable('2027-06-01');
expect($checkLogin->execute($internId))->toBeFalse();
});
it('builds input from form data', function () {
$data = UserAccountData::fromArray(['name' => 'Ida', 'email' => '[email protected]', 'role' => 'intern', 'active' => true, 'employment_ends_on' => '', 'supervisor_id' => '3']);
expect($data->role)->toBe(Role::Intern)
->and($data->employmentEndsOn)->toBeNull()
->and($data->supervisorId)->toBe(3);
});
@@ -0,0 +1,74 @@
<?php
use App\Modules\Users\Domain\Entities\UserAccount;
use App\Modules\Users\Domain\Enums\Role;
use App\Modules\Users\Domain\Exceptions\InternRequiresEndDateAndSupervisor;
use App\Modules\Users\Domain\Exceptions\InvalidSupervisor;
use App\Modules\Users\Domain\ValueObjects\EmailAddress;
use App\Modules\Users\Domain\ValueObjects\PersonName;
function makeIntern(?string $endsOn = '2027-05-31', ?int $supervisorId = 1): UserAccount
{
return UserAccount::register(
new PersonName('Ida Harjoittelija'),
new EmailAddress('[email protected]'),
Role::Intern,
$endsOn === null ? null : new DateTimeImmutable($endsOn),
$supervisorId,
);
}
it('registers an active user', function () {
$user = UserAccount::register(new PersonName('Eero Esimerkki'), new EmailAddress('[email protected]'), Role::Employee);
expect($user->id())->toBeNull()
->and($user->isActive())->toBeTrue()
->and($user->email()->value)->toBe('[email protected]');
});
it('requires an intern to have an end date and a supervisor', function (?string $endsOn, ?int $supervisorId) {
makeIntern($endsOn, $supervisorId);
})->throws(InternRequiresEndDateAndSupervisor::class)->with([
'no end date' => [null, 1],
'no supervisor' => ['2027-05-31', null],
]);
it('does not let an intern supervise themselves', function () {
$user = UserAccount::reconstitute(5, new PersonName('Ida'), new EmailAddress('[email protected]'), Role::Employee, true, null, null);
$user->changeDetails($user->name(), $user->email(), Role::Intern, true, new DateTimeImmutable('2027-05-31'), 5);
})->throws(InvalidSupervisor::class);
it('clears the end date and supervisor when an intern gets another role', function () {
$user = makeIntern();
$user->changeDetails($user->name(), $user->email(), Role::Employee, true, $user->employmentEndsOn(), $user->supervisorId());
expect($user->role())->toBe(Role::Employee)
->and($user->employmentEndsOn())->toBeNull()
->and($user->supervisorId())->toBeNull();
});
it('keeps the old details when a change breaks a rule', function () {
$user = UserAccount::register(new PersonName('Eero'), new EmailAddress('[email protected]'), Role::Employee);
expect(fn () => $user->changeDetails(new PersonName('Uusi'), $user->email(), Role::Intern, true, null, null))
->toThrow(InternRequiresEndDateAndSupervisor::class)
->and($user->name()->value)->toBe('Eero')
->and($user->role())->toBe(Role::Employee);
});
it('lets an intern log in until the end of the last day', function (string $day, bool $allowed) {
expect(makeIntern('2027-05-31')->canLogInOn(new DateTimeImmutable($day)))->toBe($allowed);
})->with([
'before' => ['2027-05-30', true],
'last day' => ['2027-05-31 23:59', true],
'day after' => ['2027-06-01', false],
]);
it('does not let an inactive user log in', function () {
$user = UserAccount::reconstitute(1, new PersonName('Eero'), new EmailAddress('[email protected]'), Role::Admin, false, null, null);
expect($user->canLogInOn(new DateTimeImmutable('2026-01-01')))->toBeFalse()
->and($user->isActiveAdmin())->toBeFalse();
});
@@ -0,0 +1,24 @@
<?php
use App\Modules\Users\Domain\Enums\Role;
use App\Modules\Users\Domain\Exceptions\InvalidEmailAddress;
use App\Modules\Users\Domain\Exceptions\InvalidPersonName;
use App\Modules\Users\Domain\ValueObjects\EmailAddress;
use App\Modules\Users\Domain\ValueObjects\PersonName;
it('normalises an email address to lower case', function () {
expect((new EmailAddress(' [email protected] '))->value)->toBe('[email protected]');
});
it('rejects an invalid email address', function (string $email) {
new EmailAddress($email);
})->throws(InvalidEmailAddress::class)->with(['', 'maija', 'maija@', '@example.fi']);
it('rejects an empty person name', function () {
new PersonName(' ');
})->throws(InvalidPersonName::class);
it('knows which roles manage users and supervise interns', function () {
expect(array_filter(Role::cases(), fn (Role $role) => $role->canManageUsers()))->toBe([Role::Admin])
->and(array_values(array_filter(Role::cases(), fn (Role $role) => $role->canSupervise())))->toBe([Role::Management, Role::Employee]);
});