From 8c7cb9e3b4b94084e9908877e32ced4407ae378c Mon Sep 17 00:00:00 2001 From: Petri Saarinen Date: Sun, 22 Nov 2026 11:03:00 +0200 Subject: [PATCH] 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 --- CLAUDE.md | 9 +- app/Models/User.php | 28 ++- .../Providers/CustomersServiceProvider.php | 10 +- .../Presentation/Livewire/⚡form.blade.php | 9 + .../Presentation/Livewire/⚡index.blade.php | 7 +- .../Customers/Presentation/Routes/web.php | 2 +- .../Users/Application/Contracts/Clock.php | 15 ++ .../Contracts/PasswordLinkSender.php | 19 +++ .../Contracts/UserAccountQueries.php | 31 ++++ .../Application/DTOs/UserAccountData.php | 43 +++++ .../Users/Application/DTOs/UserOption.php | 16 ++ .../Users/Application/DTOs/UserSummary.php | 27 +++ .../UseCases/CheckLoginAllowed.php | 25 +++ .../UseCases/CreateUserAccount.php | 61 +++++++ .../UseCases/EmploymentEndDate.php | 31 ++++ .../UseCases/SendPasswordSetupLink.php | 32 ++++ .../UseCases/UpdateUserAccount.php | 57 +++++++ .../Contracts/UserAccountRepository.php | 23 +++ .../Users/Domain/Entities/UserAccount.php | 155 +++++++++++++++++ app/Modules/Users/Domain/Enums/Role.php | 31 ++++ .../Domain/Exceptions/EmailAlreadyInUse.php | 15 ++ .../InternRequiresEndDateAndSupervisor.php | 15 ++ .../Domain/Exceptions/InvalidEmailAddress.php | 15 ++ .../Domain/Exceptions/InvalidPersonName.php | 15 ++ .../Domain/Exceptions/InvalidSupervisor.php | 15 ++ .../Exceptions/LastAdminCannotBeRemoved.php | 15 ++ .../Domain/Exceptions/UserAccountNotFound.php | 15 ++ .../Users/Domain/Services/SupervisorRule.php | 39 +++++ .../Domain/ValueObjects/EmailAddress.php | 34 ++++ .../Users/Domain/ValueObjects/PersonName.php | 25 +++ .../Auth/LaravelPasswordLinkSender.php | 21 +++ .../EloquentUserAccountQueries.php | 66 +++++++ .../EloquentUserAccountRepository.php | 74 ++++++++ .../Providers/UsersServiceProvider.php | 76 +++++++++ .../Users/Infrastructure/SystemClock.php | 17 ++ .../Console/CreateAdminCommand.php | 39 +++++ .../Http/Controllers/LogoutController.php | 19 +++ .../Http/Middleware/EnsureAccountIsUsable.php | 33 ++++ .../Presentation/Livewire/Forms/UserForm.php | 118 +++++++++++++ .../Livewire/⚡forgot-password.blade.php | 55 ++++++ .../Presentation/Livewire/⚡form.blade.php | 161 ++++++++++++++++++ .../Presentation/Livewire/⚡index.blade.php | 131 ++++++++++++++ .../Presentation/Livewire/⚡login.blade.php | 108 ++++++++++++ .../Livewire/⚡reset-password.blade.php | 105 ++++++++++++ app/Modules/Users/Presentation/Routes/web.php | 23 +++ bootstrap/app.php | 3 +- bootstrap/providers.php | 2 + config/app.php | 7 + database/factories/UserFactory.php | 42 +++++ ..._role_and_access_fields_to_users_table.php | 32 ++++ docs/architecture.md | 23 ++- lang/fi.json | 4 +- lang/fi/auth.php | 35 ++++ lang/fi/layout.php | 11 ++ lang/fi/passwords.php | 9 + lang/fi/users.php | 73 ++++++++ resources/views/layouts/app.blade.php | 35 +++- routes/web.php | 30 +--- tests/Browser/AccessibilityTest.php | 18 +- tests/Browser/CustomersAccessibilityTest.php | 3 +- tests/Browser/UsersAccessibilityTest.php | 80 +++++++++ tests/Fakes/FakeClock.php | 16 ++ tests/Fakes/FakePasswordLinkSender.php | 21 +++ tests/Fakes/InMemoryUserAccountRepository.php | 59 +++++++ tests/Feature/ExampleTest.php | 6 +- tests/Feature/HomePageTest.php | 14 +- tests/Feature/LocalTestLoginTest.php | 10 -- .../Modules/Customers/CustomerAccessTest.php | 30 ++++ .../Modules/Users/CreateAdminCommandTest.php | 32 ++++ tests/Feature/Modules/Users/LoginTest.php | 118 +++++++++++++ .../Modules/Users/PasswordResetTest.php | 91 ++++++++++ .../Modules/Users/UserManagementTest.php | 143 ++++++++++++++++ tests/Unit/ArchitectureTest.php | 4 +- .../Application/UserAccountUseCasesTest.php | 111 ++++++++++++ .../Modules/Users/Domain/UserAccountTest.php | 74 ++++++++ .../Modules/Users/Domain/ValueObjectsTest.php | 24 +++ 76 files changed, 2978 insertions(+), 62 deletions(-) create mode 100644 app/Modules/Users/Application/Contracts/Clock.php create mode 100644 app/Modules/Users/Application/Contracts/PasswordLinkSender.php create mode 100644 app/Modules/Users/Application/Contracts/UserAccountQueries.php create mode 100644 app/Modules/Users/Application/DTOs/UserAccountData.php create mode 100644 app/Modules/Users/Application/DTOs/UserOption.php create mode 100644 app/Modules/Users/Application/DTOs/UserSummary.php create mode 100644 app/Modules/Users/Application/UseCases/CheckLoginAllowed.php create mode 100644 app/Modules/Users/Application/UseCases/CreateUserAccount.php create mode 100644 app/Modules/Users/Application/UseCases/EmploymentEndDate.php create mode 100644 app/Modules/Users/Application/UseCases/SendPasswordSetupLink.php create mode 100644 app/Modules/Users/Application/UseCases/UpdateUserAccount.php create mode 100644 app/Modules/Users/Domain/Contracts/UserAccountRepository.php create mode 100644 app/Modules/Users/Domain/Entities/UserAccount.php create mode 100644 app/Modules/Users/Domain/Enums/Role.php create mode 100644 app/Modules/Users/Domain/Exceptions/EmailAlreadyInUse.php create mode 100644 app/Modules/Users/Domain/Exceptions/InternRequiresEndDateAndSupervisor.php create mode 100644 app/Modules/Users/Domain/Exceptions/InvalidEmailAddress.php create mode 100644 app/Modules/Users/Domain/Exceptions/InvalidPersonName.php create mode 100644 app/Modules/Users/Domain/Exceptions/InvalidSupervisor.php create mode 100644 app/Modules/Users/Domain/Exceptions/LastAdminCannotBeRemoved.php create mode 100644 app/Modules/Users/Domain/Exceptions/UserAccountNotFound.php create mode 100644 app/Modules/Users/Domain/Services/SupervisorRule.php create mode 100644 app/Modules/Users/Domain/ValueObjects/EmailAddress.php create mode 100644 app/Modules/Users/Domain/ValueObjects/PersonName.php create mode 100644 app/Modules/Users/Infrastructure/Auth/LaravelPasswordLinkSender.php create mode 100644 app/Modules/Users/Infrastructure/Persistence/Repositories/EloquentUserAccountQueries.php create mode 100644 app/Modules/Users/Infrastructure/Persistence/Repositories/EloquentUserAccountRepository.php create mode 100644 app/Modules/Users/Infrastructure/Providers/UsersServiceProvider.php create mode 100644 app/Modules/Users/Infrastructure/SystemClock.php create mode 100644 app/Modules/Users/Presentation/Console/CreateAdminCommand.php create mode 100644 app/Modules/Users/Presentation/Http/Controllers/LogoutController.php create mode 100644 app/Modules/Users/Presentation/Http/Middleware/EnsureAccountIsUsable.php create mode 100644 app/Modules/Users/Presentation/Livewire/Forms/UserForm.php create mode 100644 app/Modules/Users/Presentation/Livewire/⚡forgot-password.blade.php create mode 100644 app/Modules/Users/Presentation/Livewire/⚡form.blade.php create mode 100644 app/Modules/Users/Presentation/Livewire/⚡index.blade.php create mode 100644 app/Modules/Users/Presentation/Livewire/⚡login.blade.php create mode 100644 app/Modules/Users/Presentation/Livewire/⚡reset-password.blade.php create mode 100644 app/Modules/Users/Presentation/Routes/web.php create mode 100644 database/migrations/2026_11_22_084628_add_role_and_access_fields_to_users_table.php create mode 100644 lang/fi/auth.php create mode 100644 lang/fi/layout.php create mode 100644 lang/fi/passwords.php create mode 100644 lang/fi/users.php create mode 100644 tests/Browser/UsersAccessibilityTest.php create mode 100644 tests/Fakes/FakeClock.php create mode 100644 tests/Fakes/FakePasswordLinkSender.php create mode 100644 tests/Fakes/InMemoryUserAccountRepository.php delete mode 100644 tests/Feature/LocalTestLoginTest.php create mode 100644 tests/Feature/Modules/Customers/CustomerAccessTest.php create mode 100644 tests/Feature/Modules/Users/CreateAdminCommandTest.php create mode 100644 tests/Feature/Modules/Users/LoginTest.php create mode 100644 tests/Feature/Modules/Users/PasswordResetTest.php create mode 100644 tests/Feature/Modules/Users/UserManagementTest.php create mode 100644 tests/Unit/Modules/Users/Application/UserAccountUseCasesTest.php create mode 100644 tests/Unit/Modules/Users/Domain/UserAccountTest.php create mode 100644 tests/Unit/Modules/Users/Domain/ValueObjectsTest.php diff --git a/CLAUDE.md b/CLAUDE.md index 7294db9..5632507 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -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` (`::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. diff --git a/app/Models/User.php b/app/Models/User.php index f6ba1d2..38fc83e 100644 --- a/app/Models/User.php +++ b/app/Models/User.php @@ -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 */ use HasFactory, Notifiable; + /** + * @return BelongsTo + */ + 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', ]; } } diff --git a/app/Modules/Customers/Infrastructure/Providers/CustomersServiceProvider.php b/app/Modules/Customers/Infrastructure/Providers/CustomersServiceProvider.php index 20da0e0..8a87d30 100644 --- a/app/Modules/Customers/Infrastructure/Providers/CustomersServiceProvider.php +++ b/app/Modules/Customers/Infrastructure/Providers/CustomersServiceProvider.php @@ -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); } } diff --git a/app/Modules/Customers/Presentation/Livewire/⚡form.blade.php b/app/Modules/Customers/Presentation/Livewire/⚡form.blade.php index c508164..b621041 100644 --- a/app/Modules/Customers/Presentation/Livewire/⚡form.blade.php +++ b/app/Modules/Customers/Presentation/Livewire/⚡form.blade.php @@ -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); diff --git a/app/Modules/Customers/Presentation/Livewire/⚡index.blade.php b/app/Modules/Customers/Presentation/Livewire/⚡index.blade.php index 7dcb908..a5c72df 100644 --- a/app/Modules/Customers/Presentation/Livewire/⚡index.blade.php +++ b/app/Modules/Customers/Presentation/Livewire/⚡index.blade.php @@ -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()]) }} - @if ($this->customers->isEmpty()) + @if ($this->customers->total() === 0) {{ __('customers.empty') }} @else diff --git a/app/Modules/Customers/Presentation/Routes/web.php b/app/Modules/Customers/Presentation/Routes/web.php index 326b79d..15d79d0 100644 --- a/app/Modules/Customers/Presentation/Routes/web.php +++ b/app/Modules/Customers/Presentation/Routes/web.php @@ -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 () { diff --git a/app/Modules/Users/Application/Contracts/Clock.php b/app/Modules/Users/Application/Contracts/Clock.php new file mode 100644 index 0000000..0353c9b --- /dev/null +++ b/app/Modules/Users/Application/Contracts/Clock.php @@ -0,0 +1,15 @@ + + */ + public function paginate(?string $search, int $perPage = 25): LengthAwarePaginator; + + /** + * Active management and employee users who can supervise an intern. + * + * @return list + */ + public function supervisorOptions(?int $exceptUserId = null): array; +} diff --git a/app/Modules/Users/Application/DTOs/UserAccountData.php b/app/Modules/Users/Application/DTOs/UserAccountData.php new file mode 100644 index 0000000..834d484 --- /dev/null +++ b/app/Modules/Users/Application/DTOs/UserAccountData.php @@ -0,0 +1,43 @@ +users->findById($userId)?->canLogInOn($this->clock->today()) ?? false; + } +} diff --git a/app/Modules/Users/Application/UseCases/CreateUserAccount.php b/app/Modules/Users/Application/UseCases/CreateUserAccount.php new file mode 100644 index 0000000..62b77fb --- /dev/null +++ b/app/Modules/Users/Application/UseCases/CreateUserAccount.php @@ -0,0 +1,61 @@ +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; + } +} diff --git a/app/Modules/Users/Application/UseCases/EmploymentEndDate.php b/app/Modules/Users/Application/UseCases/EmploymentEndDate.php new file mode 100644 index 0000000..8a93843 --- /dev/null +++ b/app/Modules/Users/Application/UseCases/EmploymentEndDate.php @@ -0,0 +1,31 @@ +format('Y-m-d') !== $date) { + throw new InvalidArgumentException("Invalid employment end date [{$date}], expected Y-m-d."); + } + + return $parsed; + } +} diff --git a/app/Modules/Users/Application/UseCases/SendPasswordSetupLink.php b/app/Modules/Users/Application/UseCases/SendPasswordSetupLink.php new file mode 100644 index 0000000..9123891 --- /dev/null +++ b/app/Modules/Users/Application/UseCases/SendPasswordSetupLink.php @@ -0,0 +1,32 @@ +users->findById($userId) ?? throw new UserAccountNotFound($userId); + + return $this->passwordLinks->sendSetupLink($user->email()); + } +} diff --git a/app/Modules/Users/Application/UseCases/UpdateUserAccount.php b/app/Modules/Users/Application/UseCases/UpdateUserAccount.php new file mode 100644 index 0000000..a030794 --- /dev/null +++ b/app/Modules/Users/Application/UseCases/UpdateUserAccount.php @@ -0,0 +1,57 @@ +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); + }); + } +} diff --git a/app/Modules/Users/Domain/Contracts/UserAccountRepository.php b/app/Modules/Users/Domain/Contracts/UserAccountRepository.php new file mode 100644 index 0000000..cf53f63 --- /dev/null +++ b/app/Modules/Users/Domain/Contracts/UserAccountRepository.php @@ -0,0 +1,23 @@ +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; + } + } +} diff --git a/app/Modules/Users/Domain/Enums/Role.php b/app/Modules/Users/Domain/Enums/Role.php new file mode 100644 index 0000000..f879b83 --- /dev/null +++ b/app/Modules/Users/Domain/Enums/Role.php @@ -0,0 +1,31 @@ +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; + } + } +} diff --git a/app/Modules/Users/Domain/ValueObjects/EmailAddress.php b/app/Modules/Users/Domain/ValueObjects/EmailAddress.php new file mode 100644 index 0000000..34e95d4 --- /dev/null +++ b/app/Modules/Users/Domain/ValueObjects/EmailAddress.php @@ -0,0 +1,34 @@ + 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; + } +} diff --git a/app/Modules/Users/Domain/ValueObjects/PersonName.php b/app/Modules/Users/Domain/ValueObjects/PersonName.php new file mode 100644 index 0000000..b10d113 --- /dev/null +++ b/app/Modules/Users/Domain/ValueObjects/PersonName.php @@ -0,0 +1,25 @@ + self::MAX_LENGTH) { + throw new InvalidPersonName; + } + + $this->value = $value; + } +} diff --git a/app/Modules/Users/Infrastructure/Auth/LaravelPasswordLinkSender.php b/app/Modules/Users/Infrastructure/Auth/LaravelPasswordLinkSender.php new file mode 100644 index 0000000..1d4cf17 --- /dev/null +++ b/app/Modules/Users/Infrastructure/Auth/LaravelPasswordLinkSender.php @@ -0,0 +1,21 @@ +passwords->sendResetLink(['email' => $email->value]) === PasswordBroker::RESET_LINK_SENT; + } +} diff --git a/app/Modules/Users/Infrastructure/Persistence/Repositories/EloquentUserAccountQueries.php b/app/Modules/Users/Infrastructure/Persistence/Repositories/EloquentUserAccountQueries.php new file mode 100644 index 0000000..a6e2ead --- /dev/null +++ b/app/Modules/Users/Infrastructure/Persistence/Repositories/EloquentUserAccountQueries.php @@ -0,0 +1,66 @@ +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, + ); + } +} diff --git a/app/Modules/Users/Infrastructure/Persistence/Repositories/EloquentUserAccountRepository.php b/app/Modules/Users/Infrastructure/Persistence/Repositories/EloquentUserAccountRepository.php new file mode 100644 index 0000000..aa9729c --- /dev/null +++ b/app/Modules/Users/Infrastructure/Persistence/Repositories/EloquentUserAccountRepository.php @@ -0,0 +1,74 @@ +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, + ); + } +} diff --git a/app/Modules/Users/Infrastructure/Providers/UsersServiceProvider.php b/app/Modules/Users/Infrastructure/Providers/UsersServiceProvider.php new file mode 100644 index 0000000..55182ce --- /dev/null +++ b/app/Modules/Users/Infrastructure/Providers/UsersServiceProvider.php @@ -0,0 +1,76 @@ + + */ + 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'))); + } +} diff --git a/app/Modules/Users/Infrastructure/SystemClock.php b/app/Modules/Users/Infrastructure/SystemClock.php new file mode 100644 index 0000000..5366fe8 --- /dev/null +++ b/app/Modules/Users/Infrastructure/SystemClock.php @@ -0,0 +1,17 @@ +timezone)->startOfDay()->toDateTimeImmutable(); + } +} diff --git a/app/Modules/Users/Presentation/Console/CreateAdminCommand.php b/app/Modules/Users/Presentation/Console/CreateAdminCommand.php new file mode 100644 index 0000000..7b629d4 --- /dev/null +++ b/app/Modules/Users/Presentation/Console/CreateAdminCommand.php @@ -0,0 +1,39 @@ +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; + } +} diff --git a/app/Modules/Users/Presentation/Http/Controllers/LogoutController.php b/app/Modules/Users/Presentation/Http/Controllers/LogoutController.php new file mode 100644 index 0000000..ab9c825 --- /dev/null +++ b/app/Modules/Users/Presentation/Http/Controllers/LogoutController.php @@ -0,0 +1,19 @@ +logout(); + $request->session()->invalidate(); + $request->session()->regenerateToken(); + + return redirect()->route('login')->with('status', __('auth.logged_out')); + } +} diff --git a/app/Modules/Users/Presentation/Http/Middleware/EnsureAccountIsUsable.php b/app/Modules/Users/Presentation/Http/Middleware/EnsureAccountIsUsable.php new file mode 100644 index 0000000..d00849a --- /dev/null +++ b/app/Modules/Users/Presentation/Http/Middleware/EnsureAccountIsUsable.php @@ -0,0 +1,33 @@ +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); + } +} diff --git a/app/Modules/Users/Presentation/Livewire/Forms/UserForm.php b/app/Modules/Users/Presentation/Livewire/Forms/UserForm.php new file mode 100644 index 0000000..0776b7e --- /dev/null +++ b/app/Modules/Users/Presentation/Livewire/Forms/UserForm.php @@ -0,0 +1,118 @@ +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> + */ + 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 + */ + 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'), + ]; + } +} diff --git a/app/Modules/Users/Presentation/Livewire/⚡forgot-password.blade.php b/app/Modules/Users/Presentation/Livewire/⚡forgot-password.blade.php new file mode 100644 index 0000000..8a953ec --- /dev/null +++ b/app/Modules/Users/Presentation/Livewire/⚡forgot-password.blade.php @@ -0,0 +1,55 @@ +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')); + } +}; +?> + +
+ {{ __('auth.forgot_title') }} + +
+ @if ($linkRequested) + + @endif +
+ + {{ __('auth.forgot_intro') }} + +
+ + +
+ {{ __('auth.forgot_submit') }} + {{ __('auth.back_to_login') }} +
+ +
diff --git a/app/Modules/Users/Presentation/Livewire/⚡form.blade.php b/app/Modules/Users/Presentation/Livewire/⚡form.blade.php new file mode 100644 index 0000000..cae56b7 --- /dev/null +++ b/app/Modules/Users/Presentation/Livewire/⚡form.blade.php @@ -0,0 +1,161 @@ +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 + */ + #[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')); + } +}; +?> + +
+ + {{ __($userId === null ? 'users.create_title' : 'users.edit_title') }} + + +
+ + + + + + @foreach (Role::cases() as $role) + + {{ __('users.roles.'.$role->value) }} + + @endforeach + + + @if ($form->isIntern()) + + + + @foreach ($this->supervisorOptions as $option) + + {{ $option->name }} + + @endforeach + + @endif + + + +
+ {{ __('users.save') }} + {{ __('users.cancel') }} +
+ + + @if ($userId !== null) +
+ {{ __('users.send_link') }} + +
+ @if ($linkStatus !== '') + {{ $linkStatus }} + @endif +
+
+ @endif +
diff --git a/app/Modules/Users/Presentation/Livewire/⚡index.blade.php b/app/Modules/Users/Presentation/Livewire/⚡index.blade.php new file mode 100644 index 0000000..46bf5e8 --- /dev/null +++ b/app/Modules/Users/Presentation/Livewire/⚡index.blade.php @@ -0,0 +1,131 @@ +userQueries = $userQueries; + } + + public function mount(): void + { + $this->authorize('users.manage'); + } + + public function updatedSearch(): void + { + $this->resetPage(); + } + + /** + * @return LengthAwarePaginator + */ + #[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')); + } +}; +?> + +
+
+ {{ __('users.title') }} + + + {{ __('users.new') }} + +
+ + @if (session('status')) + + @endif + + + + + {{ trans_choice('users.result_count', $this->users->total(), ['count' => $this->users->total()]) }} + + + @if ($this->users->total() === 0) + {{ __('users.empty') }} + @else + + + {{ __('users.fields.name') }} + {{ __('users.fields.email') }} + {{ __('users.fields.role') }} + {{ __('users.fields.status') }} + {{ __('users.edit') }} + + + + @foreach ($this->users as $user) + + {{ $user->name }} + {{ $user->email }} + + {{ __('users.roles.'.$user->role->value) }} + @if ($user->supervisorName) + + {{ __('users.fields.supervisor') }}: {{ $user->supervisorName }} + + @endif + + {{ $this->statusOf($user) }} + + + {{ __('users.edit') }}: {{ $user->name }} + + + + @endforeach + + + @endif +
diff --git a/app/Modules/Users/Presentation/Livewire/⚡login.blade.php b/app/Modules/Users/Presentation/Livewire/⚡login.blade.php new file mode 100644 index 0000000..d127441 --- /dev/null +++ b/app/Modules/Users/Presentation/Livewire/⚡login.blade.php @@ -0,0 +1,108 @@ +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')); + } +}; +?> + +
+ {{ __('auth.login_title') }} + + @if (session('status')) + + @endif + +
+ + + + + + +
+ {{ __('auth.login') }} + {{ __('auth.forgot_password') }} +
+ +
diff --git a/app/Modules/Users/Presentation/Livewire/⚡reset-password.blade.php b/app/Modules/Users/Presentation/Livewire/⚡reset-password.blade.php new file mode 100644 index 0000000..12e86a9 --- /dev/null +++ b/app/Modules/Users/Presentation/Livewire/⚡reset-password.blade.php @@ -0,0 +1,105 @@ +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')); + } +}; +?> + +
+ {{ __('auth.reset_title') }} + + {{ __('auth.reset_intro') }} + +
+ + + + + + + {{ __('auth.reset_submit') }} + +
diff --git a/app/Modules/Users/Presentation/Routes/web.php b/app/Modules/Users/Presentation/Routes/web.php new file mode 100644 index 0000000..bdbde47 --- /dev/null +++ b/app/Modules/Users/Presentation/Routes/web.php @@ -0,0 +1,23 @@ +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'); + }); +}); diff --git a/bootstrap/app.php b/bootstrap/app.php index 1085719..1eb0fd8 100644 --- a/bootstrap/app.php +++ b/bootstrap/app.php @@ -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( diff --git a/bootstrap/providers.php b/bootstrap/providers.php index 395442f..e8402d3 100644 --- a/bootstrap/providers.php +++ b/bootstrap/providers.php @@ -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, ]; diff --git a/config/app.php b/config/app.php index dfa47ba..5cdc28a 100644 --- a/config/app.php +++ b/config/app.php @@ -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 diff --git a/database/factories/UserFactory.php b/database/factories/UserFactory.php index c4ceb07..7f952ff 100644 --- a/database/factories/UserFactory.php +++ b/database/factories/UserFactory.php @@ -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]); + } } diff --git a/database/migrations/2026_11_22_084628_add_role_and_access_fields_to_users_table.php b/database/migrations/2026_11_22_084628_add_role_and_access_fields_to_users_table.php new file mode 100644 index 0000000..87dc6c2 --- /dev/null +++ b/database/migrations/2026_11_22_084628_add_role_and_access_fields_to_users_table.php @@ -0,0 +1,32 @@ +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']); + }); + } +}; diff --git a/docs/architecture.md b/docs/architecture.md index 2c44ef2..79bf089 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -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" osoite@example.fi`. Kun `MAIL_MAILER=log`, linkki löytyy tiedostosta `storage/logs/laravel.log`. diff --git a/lang/fi.json b/lang/fi.json index f6547b4..296a8bd 100644 --- a/lang/fi.json +++ b/lang/fi.json @@ -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:" } diff --git a/lang/fi/auth.php b/lang/fi/auth.php new file mode 100644 index 0000000..253b412 --- /dev/null +++ b/lang/fi/auth.php @@ -0,0 +1,35 @@ + '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ä.', +]; diff --git a/lang/fi/layout.php b/lang/fi/layout.php new file mode 100644 index 0000000..d7af331 --- /dev/null +++ b/lang/fi/layout.php @@ -0,0 +1,11 @@ + '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', +]; diff --git a/lang/fi/passwords.php b/lang/fi/passwords.php new file mode 100644 index 0000000..76851eb --- /dev/null +++ b/lang/fi/passwords.php @@ -0,0 +1,9 @@ + '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.', +]; diff --git a/lang/fi/users.php b/lang/fi/users.php new file mode 100644 index 0000000..011fb28 --- /dev/null +++ b/lang/fi/users.php @@ -0,0 +1,73 @@ + '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.', + ], +]; diff --git a/resources/views/layouts/app.blade.php b/resources/views/layouts/app.blade.php index 20c6d03..47d5c65 100644 --- a/resources/views/layouts/app.blade.php +++ b/resources/views/layouts/app.blade.php @@ -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') }} + @auth +
+
+ + {{ config('app.name') }} + + + + + {{ __('layout.customers') }} + + + @can('users.manage') + + {{ __('layout.users') }} + + @endcan + + +
+ {{ __('layout.signed_in_as', ['name' => auth()->user()->name]) }} + +
+ @csrf + + {{ __('layout.logout') }} + +
+
+
+
+ @endauth +
{{ $slot }}
diff --git a/routes/web.php b/routes/web.php index 955af75..df4abcd 100644 --- a/routes/web.php +++ b/routes/web.php @@ -1,33 +1,5 @@ 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' => 'testikayttaja@example.test'], - ['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'); diff --git a/tests/Browser/AccessibilityTest.php b/tests/Browser/AccessibilityTest.php index 0754bb4..3cb4196 100644 --- a/tests/Browser/AccessibilityTest.php +++ b/tests/Browser/AccessibilityTest.php @@ -1,5 +1,14 @@ 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'); +}); diff --git a/tests/Browser/CustomersAccessibilityTest.php b/tests/Browser/CustomersAccessibilityTest.php index 0e0b4e0..b73e962 100644 --- a/tests/Browser/CustomersAccessibilityTest.php +++ b/tests/Browser/CustomersAccessibilityTest.php @@ -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') diff --git a/tests/Browser/UsersAccessibilityTest.php b/tests/Browser/UsersAccessibilityTest.php new file mode 100644 index 0000000..0f85960 --- /dev/null +++ b/tests/Browser/UsersAccessibilityTest.php @@ -0,0 +1,80 @@ + ['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' => 'eero@example.test']) + : 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"]', 'eero@example.test') + ->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' => 'eero@example.test']); + + 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"]', 'eero@example.test') + ->type('[wire\\:model="password"]', 'password') + ->keys('[wire\\:model="password"]', 'Enter') + ->assertPathIs('/') + ->assertSee('Kirjaudu ulos'); +}); diff --git a/tests/Fakes/FakeClock.php b/tests/Fakes/FakeClock.php new file mode 100644 index 0000000..463b5a2 --- /dev/null +++ b/tests/Fakes/FakeClock.php @@ -0,0 +1,16 @@ +today; + } +} diff --git a/tests/Fakes/FakePasswordLinkSender.php b/tests/Fakes/FakePasswordLinkSender.php new file mode 100644 index 0000000..69f1557 --- /dev/null +++ b/tests/Fakes/FakePasswordLinkSender.php @@ -0,0 +1,21 @@ + + */ + public array $sentTo = []; + + public function sendSetupLink(EmailAddress $email): bool + { + $this->sentTo[] = $email->value; + + return true; + } +} diff --git a/tests/Fakes/InMemoryUserAccountRepository.php b/tests/Fakes/InMemoryUserAccountRepository.php new file mode 100644 index 0000000..c2034ee --- /dev/null +++ b/tests/Fakes/InMemoryUserAccountRepository.php @@ -0,0 +1,59 @@ + + */ + 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, + )); + } +} diff --git a/tests/Feature/ExampleTest.php b/tests/Feature/ExampleTest.php index 8fdc86b..b74d4a6 100644 --- a/tests/Feature/ExampleTest.php +++ b/tests/Feature/ExampleTest.php @@ -1,7 +1,5 @@ get('/'); - - $response->assertStatus(200); +test('the application sends guests to the login page', function () { + $this->get('/')->assertRedirect(route('login')); }); diff --git a/tests/Feature/HomePageTest.php b/tests/Feature/HomePageTest.php index 317dd1f..0d3b706 100644 --- a/tests/Feature/HomePageTest.php +++ b/tests/Feature/HomePageTest.php @@ -1,13 +1,23 @@ 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 () { diff --git a/tests/Feature/LocalTestLoginTest.php b/tests/Feature/LocalTestLoginTest.php deleted file mode 100644 index 808a16b..0000000 --- a/tests/Feature/LocalTestLoginTest.php +++ /dev/null @@ -1,10 +0,0 @@ -environment())->not->toBe('local') - ->and(Route::has('login'))->toBeFalse(); - - $this->get('/dev/login')->assertNotFound(); -}); diff --git a/tests/Feature/Modules/Customers/CustomerAccessTest.php b/tests/Feature/Modules/Customers/CustomerAccessTest.php new file mode 100644 index 0000000..c586b33 --- /dev/null +++ b/tests/Feature/Modules/Customers/CustomerAccessTest.php @@ -0,0 +1,30 @@ +{$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); diff --git a/tests/Feature/Modules/Users/CreateAdminCommandTest.php b/tests/Feature/Modules/Users/CreateAdminCommandTest.php new file mode 100644 index 0000000..5d86295 --- /dev/null +++ b/tests/Feature/Modules/Users/CreateAdminCommandTest.php @@ -0,0 +1,32 @@ +artisan('users:create-admin', ['name' => 'Anna Admin', 'email' => 'Anna@Example.test']) + ->assertSuccessful(); + + $admin = User::query()->sole(); + + expect($admin->role)->toBe(Role::Admin) + ->and($admin->email)->toBe('anna@example.test'); + + Notification::assertSentTo($admin, ResetPassword::class); +}); + +it('fails for an email address that is in use', function () { + User::factory()->create(['email' => 'anna@example.test']); + + $this->artisan('users:create-admin', ['name' => 'Anna Admin', 'email' => 'anna@example.test']) + ->assertFailed(); + + expect(User::query()->count())->toBe(1); +}); diff --git a/tests/Feature/Modules/Users/LoginTest.php b/tests/Feature/Modules/Users/LoginTest.php new file mode 100644 index 0000000..a51a26f --- /dev/null +++ b/tests/Feature/Modules/Users/LoginTest.php @@ -0,0 +1,118 @@ +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' => 'eero@example.test']); + + $this->get(route('customers.index'))->assertRedirect(route('login')); + + $this->get(route('login'))->assertOk()->assertSee('Kirjaudu sisään'); + + Livewire::test('users::login') + ->set('email', ' Eero@Example.TEST ') + ->set('password', 'password') + ->call('login') + ->assertHasNoErrors() + ->assertRedirect(route('customers.index')); + + $this->assertAuthenticatedAs($user); +}); + +it('rejects a wrong password', function () { + User::factory()->create(['email' => 'eero@example.test']); + + Livewire::test('users::login') + ->set('email', 'eero@example.test') + ->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('eero@example.test|127.0.0.1'); + User::factory()->create(['email' => 'eero@example.test']); + + $login = Livewire::test('users::login')->set('email', 'eero@example.test'); + + 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')); +}); diff --git a/tests/Feature/Modules/Users/PasswordResetTest.php b/tests/Feature/Modules/Users/PasswordResetTest.php new file mode 100644 index 0000000..d20d983 --- /dev/null +++ b/tests/Feature/Modules/Users/PasswordResetTest.php @@ -0,0 +1,91 @@ +create(['email' => 'eero@example.test']); + + $this->get(route('password.request'))->assertOk(); + + Livewire::test('users::forgot-password') + ->set('email', 'Eero@example.test') + ->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', 'tuntematon@example.test') + ->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' => 'eero@example.test']); + $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', 'eero@example.test') + ->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' => 'eero@example.test']); + + Livewire::test('users::reset-password', ['token' => 'väärä']) + ->set('email', 'eero@example.test') + ->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(); +}); diff --git a/tests/Feature/Modules/Users/UserManagementTest.php b/tests/Feature/Modules/Users/UserManagementTest.php new file mode 100644 index 0000000..f5723c0 --- /dev/null +++ b/tests/Feature/Modules/Users/UserManagementTest.php @@ -0,0 +1,143 @@ +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', 'Ida@Example.test') + ->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', 'ida@example.test')->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', 'ida@example.test') + ->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', 'ida@example.test') + ->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' => 'eero@example.test']); + + Livewire::actingAs($this->admin) + ->test('users::form', ['user' => $user->id]) + ->call('sendPasswordLink') + ->assertSee('Lähetimme linkin salasanan asettamiseen osoitteeseen eero@example.test.'); + + 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(); +}); diff --git a/tests/Unit/ArchitectureTest.php b/tests/Unit/ArchitectureTest.php index a9b6584..f0a9330 100644 --- a/tests/Unit/ArchitectureTest.php +++ b/tests/Unit/ArchitectureTest.php @@ -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])); diff --git a/tests/Unit/Modules/Users/Application/UserAccountUseCasesTest.php b/tests/Unit/Modules/Users/Application/UserAccountUseCasesTest.php new file mode 100644 index 0000000..13f82c4 --- /dev/null +++ b/tests/Unit/Modules/Users/Application/UserAccountUseCasesTest.php @@ -0,0 +1,111 @@ +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('anna@example.test'), Role::Admin))->id(); + $this->employeeId = $this->users->save(UserAccount::register(new PersonName('Eero Työntekijä'), new EmailAddress('eero@example.test'), 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', 'Maija@Example.test', Role::Employee)); + + expect($this->users->findById($userId)?->email()->value)->toBe('maija@example.test') + ->and($this->passwordLinks->sentTo)->toBe(['maija@example.test']); +}); + +it('creates an intern with an end date and a supervisor', function () { + $userId = $this->createUser->execute(new UserAccountData('Ida', 'ida@example.test', 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('pois@example.test'), Role::Employee, false, null, null))->id(), + }; + + $this->createUser->execute(new UserAccountData('Ida', 'ida@example.test', 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', 'EERO@example.test', 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', 'anna@example.test', $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('toinen@example.test'), Role::Admin)); + + $this->updateUser->execute($this->adminId, new UserAccountData('Anna Admin', 'anna@example.test', 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', 'x@example.test', 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(['eero@example.test']); +}); + +it('checks whether a user may log in today', function () { + $internId = $this->createUser->execute(new UserAccountData('Ida', 'ida@example.test', 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' => 'ida@example.test', '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); +}); diff --git a/tests/Unit/Modules/Users/Domain/UserAccountTest.php b/tests/Unit/Modules/Users/Domain/UserAccountTest.php new file mode 100644 index 0000000..b3c654c --- /dev/null +++ b/tests/Unit/Modules/Users/Domain/UserAccountTest.php @@ -0,0 +1,74 @@ +id())->toBeNull() + ->and($user->isActive())->toBeTrue() + ->and($user->email()->value)->toBe('eero@example.test'); +}); + +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('ida@example.test'), 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('eero@example.test'), 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('eero@example.test'), Role::Admin, false, null, null); + + expect($user->canLogInOn(new DateTimeImmutable('2026-01-01')))->toBeFalse() + ->and($user->isActiveAdmin())->toBeFalse(); +}); diff --git a/tests/Unit/Modules/Users/Domain/ValueObjectsTest.php b/tests/Unit/Modules/Users/Domain/ValueObjectsTest.php new file mode 100644 index 0000000..dc177fa --- /dev/null +++ b/tests/Unit/Modules/Users/Domain/ValueObjectsTest.php @@ -0,0 +1,24 @@ +value)->toBe('maija.meikalainen@example.fi'); +}); + +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]); +});