Fix review findings in login and user management
- Load stored users without re-checking role rules, so an intern whose supervisor was deleted no longer gets a 500 on every request; the rules apply again on the next change. - Refuse to deactivate or demote a supervisor of active interns (SupervisorHasInterns). - Lock active admin rows in the last-admin check so concurrent changes cannot remove every admin. - Creating a user survives mail failures: the error is reported and the admin is asked to resend the link (CreatedUserAccount result). - Session-ended redirect passes the reason in the URL (/login?access=ended), so Livewire requests also show it. - Same login message for a wrong password and a disabled account. - Forgot-password sends links only to users who may sign in today (RequestPasswordReset), with the same neutral message. - Use the default callout instead of the low-contrast warning variant. - Document make:class/make:test for module files in CLAUDE.md. Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
@@ -25,6 +25,7 @@ Read `docs/architecture.md` (Finnish) before adding or changing domain code. `ap
|
||||
- **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`.
|
||||
- Generate module files with Artisan, then edit them: `php artisan make:class Modules/<Module>/<Layer>/<Folder>/<Name>` for classes, `make:test --pest [--unit] Modules/<Module>/<Name>Test` for tests, `make:migration` for migrations. Add `declare(strict_types=1);` to Domain and Application files.
|
||||
- When writing PHP through a bash heredoc, `\\` can collapse to `\`, and `"App\Modules\{$x}"` then stops interpolating. Write PHP files with the Write tool.
|
||||
|
||||
## Accessibility (WCAG 2.2 AA, EN 301 549)
|
||||
@@ -38,7 +39,7 @@ Accessibility is a contractual acceptance criterion. It covers the whole UI: nav
|
||||
- The layout (`resources/views/layouts/app.blade.php`) provides a skip link and a `<main id="main-content">` landmark. Keep them, and add `<nav aria-label="…">` for navigation.
|
||||
- One `h1` per page, logical heading order, and a descriptive page `#[Title]` on every page component.
|
||||
- Data tables use `flux:table` with column headers. Icon-only buttons need an accessible name (`aria-label` or Flux `tooltip`). Decorative images get `alt=""`.
|
||||
- Contrast is at least 4.5:1 for text and 3:1 for UI components and focus indicators, in both light and dark mode. Flux's default error text (red-500) fails this, so `resources/css/app.css` overrides `[data-flux-error]`.
|
||||
- Contrast is at least 4.5:1 for text and 3:1 for UI components and focus indicators, in both light and dark mode. Flux's default error text (red-500) fails this, so `resources/css/app.css` overrides `[data-flux-error]`. `flux:callout variant="warning"` also fails in light mode (2.8:1): use the default callout with a warning icon.
|
||||
- Layouts must reflow at 320 px width and 400 % zoom without horizontal scrolling. Touch targets are at least 24×24 px.
|
||||
- Every new page gets a browser test in `tests/Browser` that uses `assertNoAccessibilityIssues(level: 2)` in light and dark mode and on desktop and mobile. See `tests/Browser/AccessibilityTest.php`. Automated axe checks catch only part of WCAG: also check new flows manually with the keyboard and a screen reader (NVDA).
|
||||
|
||||
|
||||
@@ -13,7 +13,8 @@ use App\Modules\Users\Domain\ValueObjects\EmailAddress;
|
||||
interface PasswordLinkSender
|
||||
{
|
||||
/**
|
||||
* @return bool False when a link was sent to this address too recently.
|
||||
* @return bool False when the link was not sent: one was sent to this
|
||||
* address too recently, or the mail could not be delivered.
|
||||
*/
|
||||
public function sendSetupLink(EmailAddress $email): bool;
|
||||
}
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Users\Application\DTOs;
|
||||
|
||||
/**
|
||||
* Result of creating a user. The user exists even when the set-password
|
||||
* link could not be sent; it can then be resent from the edit page.
|
||||
*/
|
||||
final readonly class CreatedUserAccount
|
||||
{
|
||||
public function __construct(
|
||||
public int $userId,
|
||||
public bool $setupLinkSent,
|
||||
) {}
|
||||
}
|
||||
@@ -6,6 +6,7 @@ namespace App\Modules\Users\Application\UseCases;
|
||||
|
||||
use App\Modules\Shared\Application\Contracts\TransactionManager;
|
||||
use App\Modules\Users\Application\Contracts\PasswordLinkSender;
|
||||
use App\Modules\Users\Application\DTOs\CreatedUserAccount;
|
||||
use App\Modules\Users\Application\DTOs\UserAccountData;
|
||||
use App\Modules\Users\Domain\Contracts\UserAccountRepository;
|
||||
use App\Modules\Users\Domain\Entities\UserAccount;
|
||||
@@ -29,12 +30,10 @@ final class CreateUserAccount
|
||||
) {}
|
||||
|
||||
/**
|
||||
* @return int The new user's id.
|
||||
*
|
||||
* @throws EmailAlreadyInUse
|
||||
* @throws InvalidSupervisor
|
||||
*/
|
||||
public function execute(UserAccountData $data): int
|
||||
public function execute(UserAccountData $data): CreatedUserAccount
|
||||
{
|
||||
$user = UserAccount::register(
|
||||
new PersonName($data->name),
|
||||
@@ -54,8 +53,6 @@ final class CreateUserAccount
|
||||
return (int) $this->users->save($user)->id();
|
||||
});
|
||||
|
||||
$this->passwordLinks->sendSetupLink($user->email());
|
||||
|
||||
return $userId;
|
||||
return new CreatedUserAccount($userId, $this->passwordLinks->sendSetupLink($user->email()));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Users\Application\UseCases;
|
||||
|
||||
use App\Modules\Users\Application\Contracts\Clock;
|
||||
use App\Modules\Users\Application\Contracts\PasswordLinkSender;
|
||||
use App\Modules\Users\Domain\Contracts\UserAccountRepository;
|
||||
use App\Modules\Users\Domain\ValueObjects\EmailAddress;
|
||||
|
||||
/**
|
||||
* A user asks for a set-password link on the login page. Only users who
|
||||
* may sign in today get one; the caller shows the same message either way,
|
||||
* so the page does not reveal which addresses exist or are disabled.
|
||||
*/
|
||||
final class RequestPasswordReset
|
||||
{
|
||||
public function __construct(
|
||||
private UserAccountRepository $users,
|
||||
private PasswordLinkSender $passwordLinks,
|
||||
private Clock $clock,
|
||||
) {}
|
||||
|
||||
public function execute(EmailAddress $email): void
|
||||
{
|
||||
$user = $this->users->findByEmail($email);
|
||||
|
||||
if ($user === null || ! $user->canLogInOn($this->clock->today())) {
|
||||
return;
|
||||
}
|
||||
|
||||
$this->passwordLinks->sendSetupLink($email);
|
||||
}
|
||||
}
|
||||
@@ -10,6 +10,7 @@ use App\Modules\Users\Domain\Contracts\UserAccountRepository;
|
||||
use App\Modules\Users\Domain\Exceptions\EmailAlreadyInUse;
|
||||
use App\Modules\Users\Domain\Exceptions\InvalidSupervisor;
|
||||
use App\Modules\Users\Domain\Exceptions\LastAdminCannotBeRemoved;
|
||||
use App\Modules\Users\Domain\Exceptions\SupervisorHasInterns;
|
||||
use App\Modules\Users\Domain\Exceptions\UserAccountNotFound;
|
||||
use App\Modules\Users\Domain\Services\SupervisorRule;
|
||||
use App\Modules\Users\Domain\ValueObjects\EmailAddress;
|
||||
@@ -28,6 +29,7 @@ final class UpdateUserAccount
|
||||
* @throws EmailAlreadyInUse
|
||||
* @throws InvalidSupervisor
|
||||
* @throws LastAdminCannotBeRemoved
|
||||
* @throws SupervisorHasInterns
|
||||
*/
|
||||
public function execute(int $userId, UserAccountData $data): void
|
||||
{
|
||||
@@ -38,6 +40,7 @@ final class UpdateUserAccount
|
||||
$this->transactions->run(function () use ($userId, $data, $name, $email, $endsOn): void {
|
||||
$user = $this->users->findById($userId) ?? throw new UserAccountNotFound($userId);
|
||||
$wasActiveAdmin = $user->isActiveAdmin();
|
||||
$couldSupervise = $user->canSuperviseInterns();
|
||||
|
||||
if ($this->users->isEmailTaken($email, $userId)) {
|
||||
throw new EmailAlreadyInUse;
|
||||
@@ -49,6 +52,14 @@ final class UpdateUserAccount
|
||||
throw new LastAdminCannotBeRemoved;
|
||||
}
|
||||
|
||||
if ($couldSupervise && ! $user->canSuperviseInterns()) {
|
||||
$internCount = $this->users->countActiveInternsSupervisedBy($userId);
|
||||
|
||||
if ($internCount > 0) {
|
||||
throw new SupervisorHasInterns($internCount);
|
||||
}
|
||||
}
|
||||
|
||||
$this->supervisorRule->ensureValidFor($user);
|
||||
|
||||
$this->users->save($user);
|
||||
|
||||
@@ -11,6 +11,8 @@ interface UserAccountRepository
|
||||
{
|
||||
public function findById(int $id): ?UserAccount;
|
||||
|
||||
public function findByEmail(EmailAddress $email): ?UserAccount;
|
||||
|
||||
/**
|
||||
* Inserts a new user or updates a stored one, and returns the stored
|
||||
* user (a new one gets its id here).
|
||||
@@ -19,5 +21,12 @@ interface UserAccountRepository
|
||||
|
||||
public function isEmailTaken(EmailAddress $email, ?int $exceptUserId = null): bool;
|
||||
|
||||
/**
|
||||
* Counts active admins other than the given user. Locks the active
|
||||
* admin rows until the transaction ends, so two concurrent changes
|
||||
* cannot both remove "the other" admin.
|
||||
*/
|
||||
public function countActiveAdmins(?int $exceptUserId = null): int;
|
||||
|
||||
public function countActiveInternsSupervisedBy(int $supervisorId): int;
|
||||
}
|
||||
|
||||
@@ -27,9 +27,7 @@ final class UserAccount
|
||||
private bool $active,
|
||||
private ?DateTimeImmutable $employmentEndsOn,
|
||||
private ?int $supervisorId,
|
||||
) {
|
||||
$this->applyRoleRules();
|
||||
}
|
||||
) {}
|
||||
|
||||
/**
|
||||
* A new, active user that is not stored yet, so it has no id.
|
||||
@@ -41,11 +39,19 @@ final class UserAccount
|
||||
?DateTimeImmutable $employmentEndsOn = null,
|
||||
?int $supervisorId = null,
|
||||
): self {
|
||||
return new self(null, $name, $email, $role, true, $employmentEndsOn, $supervisorId);
|
||||
$user = new self(null, $name, $email, $role, true, $employmentEndsOn, $supervisorId);
|
||||
$user->applyRoleRules();
|
||||
|
||||
return $user;
|
||||
}
|
||||
|
||||
/**
|
||||
* Rebuilds a stored user. Used only by repositories.
|
||||
*
|
||||
* Does not re-check the role rules: a stored row that breaks them (an
|
||||
* intern whose supervisor was deleted, say) must still load, so the user
|
||||
* can be signed in or out and an admin can correct it. The rules apply
|
||||
* again on the next changeDetails().
|
||||
*/
|
||||
public static function reconstitute(
|
||||
int $id,
|
||||
@@ -100,6 +106,15 @@ final class UserAccount
|
||||
return $this->active && $this->role === Role::Admin;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the user can be an intern's supervisor: active, in a role
|
||||
* that supervises.
|
||||
*/
|
||||
public function canSuperviseInterns(): bool
|
||||
{
|
||||
return $this->active && $this->role->canSupervise();
|
||||
}
|
||||
|
||||
public function id(): ?int
|
||||
{
|
||||
return $this->id;
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Users\Domain\Exceptions;
|
||||
|
||||
use App\Modules\Shared\Domain\Exceptions\DomainException;
|
||||
|
||||
final class SupervisorHasInterns extends DomainException
|
||||
{
|
||||
public function __construct(public readonly int $internCount)
|
||||
{
|
||||
parent::__construct("The user supervises {$internCount} active intern(s) and cannot stop being a supervisor.");
|
||||
}
|
||||
}
|
||||
@@ -31,8 +31,7 @@ final class SupervisorRule
|
||||
|
||||
if ($supervisor === null
|
||||
|| $supervisor->id() === $user->id()
|
||||
|| ! $supervisor->isActive()
|
||||
|| ! $supervisor->role()->canSupervise()) {
|
||||
|| ! $supervisor->canSuperviseInterns()) {
|
||||
throw new InvalidSupervisor;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -5,6 +5,7 @@ namespace App\Modules\Users\Infrastructure\Auth;
|
||||
use App\Modules\Users\Application\Contracts\PasswordLinkSender;
|
||||
use App\Modules\Users\Domain\ValueObjects\EmailAddress;
|
||||
use Illuminate\Contracts\Auth\PasswordBroker;
|
||||
use Symfony\Component\Mailer\Exception\TransportExceptionInterface;
|
||||
|
||||
/**
|
||||
* Sends Laravel's password reset notification, which the Users module
|
||||
@@ -16,6 +17,14 @@ class LaravelPasswordLinkSender implements PasswordLinkSender
|
||||
|
||||
public function sendSetupLink(EmailAddress $email): bool
|
||||
{
|
||||
return $this->passwords->sendResetLink(['email' => $email->value]) === PasswordBroker::RESET_LINK_SENT;
|
||||
try {
|
||||
return $this->passwords->sendResetLink(['email' => $email->value]) === PasswordBroker::RESET_LINK_SENT;
|
||||
} catch (TransportExceptionInterface $exception) {
|
||||
// The mail server is down or refused the message: log it and let
|
||||
// the caller offer a resend instead of failing the whole action.
|
||||
report($exception);
|
||||
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+23
-2
@@ -20,6 +20,13 @@ class EloquentUserAccountRepository implements UserAccountRepository
|
||||
return $model === null ? null : $this->toEntity($model);
|
||||
}
|
||||
|
||||
public function findByEmail(EmailAddress $email): ?UserAccount
|
||||
{
|
||||
$model = User::query()->where('email', $email->value)->first();
|
||||
|
||||
return $model === null ? null : $this->toEntity($model);
|
||||
}
|
||||
|
||||
public function save(UserAccount $user): UserAccount
|
||||
{
|
||||
if ($user->id() === null) {
|
||||
@@ -52,10 +59,24 @@ class EloquentUserAccountRepository implements UserAccountRepository
|
||||
|
||||
public function countActiveAdmins(?int $exceptUserId = null): int
|
||||
{
|
||||
return User::query()
|
||||
// Lock every active admin row (in id order, so concurrent callers queue
|
||||
// instead of deadlocking); the second caller then sees the first one's change.
|
||||
$adminIds = User::query()
|
||||
->where('role', Role::Admin)
|
||||
->where('is_active', true)
|
||||
->when($exceptUserId !== null, fn ($query) => $query->whereKeyNot($exceptUserId))
|
||||
->orderBy('id')
|
||||
->lockForUpdate()
|
||||
->pluck('id');
|
||||
|
||||
return $adminIds->reject(fn (int $id): bool => $id === $exceptUserId)->count();
|
||||
}
|
||||
|
||||
public function countActiveInternsSupervisedBy(int $supervisorId): int
|
||||
{
|
||||
return User::query()
|
||||
->where('role', Role::Intern)
|
||||
->where('is_active', true)
|
||||
->where('supervisor_id', $supervisorId)
|
||||
->count();
|
||||
}
|
||||
|
||||
|
||||
@@ -17,7 +17,7 @@ class CreateAdminCommand extends Command
|
||||
public function handle(CreateUserAccount $createUserAccount): int
|
||||
{
|
||||
try {
|
||||
$createUserAccount->execute(new UserAccountData(
|
||||
$created = $createUserAccount->execute(new UserAccountData(
|
||||
name: (string) $this->argument('name'),
|
||||
email: (string) $this->argument('email'),
|
||||
role: Role::Admin,
|
||||
@@ -28,6 +28,12 @@ class CreateAdminCommand extends Command
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
if (! $created->setupLinkSent) {
|
||||
$this->components->warn('Admin created, but the set-password email could not be sent (see the log). Fix the mail settings and use "Unohditko salasanan?" on the login page.');
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
|
||||
$this->components->info('Admin created. A link for setting the password was emailed to '.$this->argument('email').'.');
|
||||
|
||||
if (config('mail.default') === 'log') {
|
||||
|
||||
@@ -25,7 +25,9 @@ class EnsureAccountIsUsable
|
||||
$request->session()->invalidate();
|
||||
$request->session()->regenerateToken();
|
||||
|
||||
return redirect()->route('login')->with('status', __('auth.account_disabled'));
|
||||
// The reason goes in the URL: Livewire follows this redirect with
|
||||
// fetch first, which would consume a flashed message.
|
||||
return redirect()->route('login', ['access' => 'ended']);
|
||||
}
|
||||
|
||||
return $next($request);
|
||||
|
||||
@@ -12,6 +12,7 @@ use App\Modules\Users\Domain\Exceptions\InvalidEmailAddress;
|
||||
use App\Modules\Users\Domain\Exceptions\InvalidPersonName;
|
||||
use App\Modules\Users\Domain\Exceptions\InvalidSupervisor;
|
||||
use App\Modules\Users\Domain\Exceptions\LastAdminCannotBeRemoved;
|
||||
use App\Modules\Users\Domain\Exceptions\SupervisorHasInterns;
|
||||
use Illuminate\Validation\Rule;
|
||||
use Livewire\Form;
|
||||
|
||||
@@ -75,6 +76,7 @@ class UserForm extends Form
|
||||
InternRequiresEndDateAndSupervisor::class => ['supervisor_id', 'users.errors.supervisor_required'],
|
||||
InvalidSupervisor::class => ['supervisor_id', 'users.errors.invalid_supervisor'],
|
||||
LastAdminCannotBeRemoved::class => ['role', 'users.errors.last_admin'],
|
||||
SupervisorHasInterns::class => ['role', 'users.errors.supervisor_has_interns'],
|
||||
default => throw $exception,
|
||||
};
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<?php
|
||||
|
||||
use App\Modules\Users\Application\Contracts\PasswordLinkSender;
|
||||
use App\Modules\Users\Application\UseCases\RequestPasswordReset;
|
||||
use App\Modules\Users\Domain\ValueObjects\EmailAddress;
|
||||
use Livewire\Component;
|
||||
|
||||
@@ -11,17 +11,19 @@ new class extends Component
|
||||
public bool $linkRequested = false;
|
||||
|
||||
/**
|
||||
* Shows the same message whether or not the address has an account, so
|
||||
* the page cannot be used to find out which addresses are in use.
|
||||
* Shows the same message whether or not the address has a usable
|
||||
* account, so the page cannot be used to find out which addresses exist.
|
||||
*/
|
||||
public function sendLink(PasswordLinkSender $passwordLinks): void
|
||||
public function sendLink(RequestPasswordReset $requestPasswordReset): void
|
||||
{
|
||||
$this->email = trim($this->email);
|
||||
|
||||
$this->validate(
|
||||
['email' => ['required', 'string', 'email:filter', 'max:255']],
|
||||
['email.required' => __('auth.email_required'), 'email.email' => __('auth.email_invalid'), 'email.max' => __('auth.email_invalid')],
|
||||
);
|
||||
|
||||
$passwordLinks->sendSetupLink(new EmailAddress($this->email));
|
||||
$requestPasswordReset->execute(new EmailAddress($this->email));
|
||||
|
||||
$this->linkRequested = true;
|
||||
}
|
||||
|
||||
@@ -58,8 +58,11 @@ new class extends Component
|
||||
|
||||
try {
|
||||
if ($this->userId === null) {
|
||||
$createUser->execute($data);
|
||||
session()->flash('status', __('users.created', ['name' => $data->name]));
|
||||
$created = $createUser->execute($data);
|
||||
session()->flash('status', __(
|
||||
$created->setupLinkSent ? 'users.created' : 'users.created_link_failed',
|
||||
['name' => $data->name],
|
||||
));
|
||||
} else {
|
||||
$updateUser->execute($this->userId, $data);
|
||||
session()->flash('status', __('users.updated', ['name' => $data->name]));
|
||||
|
||||
@@ -17,6 +17,18 @@ new class extends Component
|
||||
|
||||
public bool $remember = false;
|
||||
|
||||
/**
|
||||
* Set when EnsureAccountIsUsable ended the session. Passed in the URL,
|
||||
* not flashed: a Livewire request that gets redirected here would
|
||||
* consume a flash message before the browser shows the page.
|
||||
*/
|
||||
public bool $accessEnded = false;
|
||||
|
||||
public function mount(): void
|
||||
{
|
||||
$this->accessEnded = request()->query('access') === 'ended';
|
||||
}
|
||||
|
||||
public function login(CheckLoginAllowed $checkLoginAllowed): void
|
||||
{
|
||||
$this->email = trim($this->email);
|
||||
@@ -39,15 +51,9 @@ new class extends Component
|
||||
]);
|
||||
}
|
||||
|
||||
$accountDisabled = false;
|
||||
|
||||
$signedIn = Auth::attemptWhen(
|
||||
['email' => $email, 'password' => $this->password],
|
||||
function ($user) use ($checkLoginAllowed, &$accountDisabled): bool {
|
||||
$accountDisabled = ! $checkLoginAllowed->execute($user->getAuthIdentifier());
|
||||
|
||||
return ! $accountDisabled;
|
||||
},
|
||||
fn ($user): bool => $checkLoginAllowed->execute($user->getAuthIdentifier()),
|
||||
$this->remember,
|
||||
);
|
||||
|
||||
@@ -55,9 +61,9 @@ new class extends Component
|
||||
RateLimiter::hit($throttleKey);
|
||||
$this->reset('password');
|
||||
|
||||
throw ValidationException::withMessages([
|
||||
'email' => __($accountDisabled ? 'auth.account_disabled' : 'auth.failed'),
|
||||
]);
|
||||
// One message for a wrong password and a disabled account, so the
|
||||
// form never confirms that a disabled account's password is right.
|
||||
throw ValidationException::withMessages(['email' => __('auth.failed')]);
|
||||
}
|
||||
|
||||
RateLimiter::clear($throttleKey);
|
||||
@@ -76,7 +82,10 @@ new class extends Component
|
||||
<div class="mx-auto max-w-md space-y-6 p-4 sm:p-6 sm:pt-16">
|
||||
<flux:heading size="xl" level="1">{{ __('auth.login_title') }}</flux:heading>
|
||||
|
||||
@if (session('status'))
|
||||
@if ($accessEnded)
|
||||
{{-- Not variant="warning": its yellow heading is only 2.8:1 on the light background. --}}
|
||||
<flux:callout icon="exclamation-triangle" role="status" :heading="__('auth.account_disabled')" />
|
||||
@elseif (session('status'))
|
||||
<flux:callout variant="success" icon="information-circle" role="status" :heading="session('status')" />
|
||||
@endif
|
||||
|
||||
|
||||
@@ -216,8 +216,8 @@ Esimerkki: vaiheen 1 `CustomerJobs` (asiakastyöt).
|
||||
## 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ä.
|
||||
- **`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; tarkistus lukitsee pääkäyttäjärivit, joten samanaikaiset muutokset eivät ohita sitä. Aktiivisten harjoittelijoiden vastuuhenkilöä ei voi poistaa käytöstä eikä siirtää rooliin, joka ei voi toimia vastuuhenkilönä (`SupervisorHasInterns`). Tallennettu käyttäjä ladataan tarkistamatta sääntöjä (`reconstitute`), jotta virheellinen rivi ei kaada kirjautumista; säännöt tarkistetaan seuraavassa muutoksessa.
|
||||
- **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. Väärä salasana ja käytöstä poistettu tunnus saavat saman viestin, jotta lomake ei paljasta, että poistetun tunnuksen salasana oli oikein.
|
||||
- **`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, ja käyttäjä ohjataan osoitteeseen `/login?access=ended`, joka kertoo syyn. Syy kulkee URL:ssa eikä flash-viestinä, koska Livewire seuraa uudelleenohjausta ensin fetchillä, joka kuluttaisi flash-viestin.
|
||||
- **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ä. "Unohditko salasanan?" lähettää linkin vain käyttäjälle, joka saa kirjautua tänään, mutta näyttää aina saman viestin. Jos sähköpostin lähetys epäonnistuu, käyttäjä luodaan silti, virhe kirjataan lokiin ja pääkäyttäjää pyydetään lähettämään linkki uudelleen muokkaussivulta.
|
||||
- **Ensimmäinen pääkäyttäjä:** `php artisan users:create-admin "Nimi" [email protected]`. Kun `MAIL_MAILER=log`, linkki löytyy tiedostosta `storage/logs/laravel.log`.
|
||||
|
||||
+1
-1
@@ -1,7 +1,7 @@
|
||||
<?php
|
||||
|
||||
return [
|
||||
'failed' => 'Sähköposti tai salasana on väärin.',
|
||||
'failed' => 'Kirjautuminen ei onnistunut. Tarkista sähköposti ja salasana. Jos tunnuksesi on poistettu käytöstä, ota yhteyttä pääkäyttäjään.',
|
||||
'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.',
|
||||
|
||||
+3
-1
@@ -18,7 +18,8 @@ return [
|
||||
'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.',
|
||||
'created_link_failed' => 'Käyttäjä :name lisätty, mutta salasanan asetuslinkin lähetys epäonnistui. Lähetä linkki uudelleen käyttäjän muokkaussivulta.',
|
||||
'link_throttled' => 'Linkkiä ei voitu lähettää: se lähetettiin juuri, tai sähköpostin lähetys epäonnistui. Yritä hetken kuluttua uudelleen.',
|
||||
|
||||
'fields' => [
|
||||
'name' => 'Nimi',
|
||||
@@ -60,6 +61,7 @@ return [
|
||||
'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.',
|
||||
'supervisor_has_interns' => 'Käyttäjä on aktiivisten harjoittelijoiden vastuuhenkilö. Vaihda harjoittelijoille ensin uusi vastuuhenkilö.',
|
||||
],
|
||||
|
||||
'password_mail' => [
|
||||
|
||||
@@ -60,10 +60,26 @@ it('shows a login error without accessibility issues', function (string $colorSc
|
||||
$page->fill('[wire\\:model="email"]', '[email protected]')
|
||||
->fill('[wire\\:model="password"]', 'väärä-salasana')
|
||||
->press('Kirjaudu')
|
||||
->assertSee('Sähköposti tai salasana on väärin.')
|
||||
->assertSee('Kirjautuminen ei onnistunut.')
|
||||
->assertNoAccessibilityIssues(level: 2);
|
||||
})->with(['light', 'dark']);
|
||||
|
||||
it('sends a user who is deactivated mid-session to the login page with the reason', function () {
|
||||
$user = User::factory()->create();
|
||||
$this->actingAs($user);
|
||||
|
||||
// visit() is lazy: load the form before the account is deactivated.
|
||||
$page = visit(route('customers.create'))->assertSee('Uusi asiakas');
|
||||
|
||||
$user->update(['is_active' => false]);
|
||||
|
||||
$page->fill('[wire\\:model="form.name"]', 'Mainos Oy')
|
||||
->press('Tallenna')
|
||||
->assertPathIs('/login')
|
||||
->assertSee('Käyttöoikeutesi on päättynyt. Ota yhteyttä pääkäyttäjään.')
|
||||
->assertNoAccessibilityIssues(level: 2);
|
||||
});
|
||||
|
||||
it('logs in with the keyboard alone', function () {
|
||||
User::factory()->create(['email' => '[email protected]']);
|
||||
|
||||
|
||||
@@ -20,6 +20,17 @@ class InMemoryUserAccountRepository implements UserAccountRepository
|
||||
return isset($this->users[$id]) ? clone $this->users[$id] : null;
|
||||
}
|
||||
|
||||
public function findByEmail(EmailAddress $email): ?UserAccount
|
||||
{
|
||||
foreach ($this->users as $user) {
|
||||
if ($user->email()->equals($email)) {
|
||||
return clone $user;
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
public function save(UserAccount $user): UserAccount
|
||||
{
|
||||
$id = $user->id() ?? $this->nextId++;
|
||||
@@ -56,4 +67,12 @@ class InMemoryUserAccountRepository implements UserAccountRepository
|
||||
ARRAY_FILTER_USE_BOTH,
|
||||
));
|
||||
}
|
||||
|
||||
public function countActiveInternsSupervisedBy(int $supervisorId): int
|
||||
{
|
||||
return count(array_filter(
|
||||
$this->users,
|
||||
fn (UserAccount $user): bool => $user->isActive() && $user->supervisorId() === $supervisorId,
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -36,13 +36,13 @@ it('rejects a wrong password', function () {
|
||||
->set('password', 'väärä')
|
||||
->call('login')
|
||||
->assertHasErrors(['email'])
|
||||
->assertSee('Sähköposti tai salasana on väärin.')
|
||||
->assertSee('Kirjautuminen ei onnistunut.')
|
||||
->assertSet('password', '');
|
||||
|
||||
$this->assertGuest();
|
||||
});
|
||||
|
||||
it('does not let a deactivated user or an intern past the last day log in', function (string $state) {
|
||||
it('does not let a deactivated user or an intern past the last day log in, with the same message as a wrong password', function (string $state) {
|
||||
$factory = User::factory();
|
||||
$user = match ($state) {
|
||||
'inactive' => $factory->inactive()->create(),
|
||||
@@ -54,7 +54,8 @@ it('does not let a deactivated user or an intern past the last day log in', func
|
||||
->set('password', 'password')
|
||||
->call('login')
|
||||
->assertHasErrors(['email'])
|
||||
->assertSee('Käyttöoikeutesi on päättynyt.');
|
||||
->assertSee('Kirjautuminen ei onnistunut.')
|
||||
->assertDontSee('Käyttöoikeutesi on päättynyt.');
|
||||
|
||||
$this->assertGuest();
|
||||
})->with(['inactive', 'intern ended yesterday']);
|
||||
@@ -96,11 +97,13 @@ it('ends the session of a user who is deactivated while signed in', function ()
|
||||
|
||||
$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->get(route('customers.index'))->assertRedirect(route('login', ['access' => 'ended']));
|
||||
|
||||
$this->assertGuest();
|
||||
|
||||
$this->get(route('login', ['access' => 'ended']))
|
||||
->assertOk()
|
||||
->assertSee('Käyttöoikeutesi on päättynyt. Ota yhteyttä pääkäyttäjään.');
|
||||
});
|
||||
|
||||
it('logs out', function () {
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
<?php
|
||||
|
||||
use App\Models\User;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\Exceptions;
|
||||
use Livewire\Livewire;
|
||||
use Symfony\Component\Mailer\Exception\TransportException;
|
||||
|
||||
uses(RefreshDatabase::class);
|
||||
|
||||
beforeEach(function () {
|
||||
// An SMTP server that refuses every connection.
|
||||
config([
|
||||
'mail.default' => 'smtp',
|
||||
'mail.mailers.smtp.host' => '127.0.0.1',
|
||||
'mail.mailers.smtp.port' => 9,
|
||||
'mail.mailers.smtp.timeout' => 1,
|
||||
]);
|
||||
|
||||
Exceptions::fake();
|
||||
});
|
||||
|
||||
it('creates the user and asks for a resend when the email cannot be sent', function () {
|
||||
Livewire::actingAs(User::factory()->admin()->create())
|
||||
->test('users::form')
|
||||
->set('form.name', 'Maija Meikäläinen')
|
||||
->set('form.email', '[email protected]')
|
||||
->call('save')
|
||||
->assertHasNoErrors()
|
||||
->assertRedirect(route('users.index'));
|
||||
|
||||
expect(User::query()->where('email', '[email protected]')->exists())->toBeTrue()
|
||||
->and(session('status'))->toContain('salasanan asetuslinkin lähetys epäonnistui');
|
||||
|
||||
Exceptions::assertReported(TransportException::class);
|
||||
});
|
||||
|
||||
it('tells the admin when a resend fails', function () {
|
||||
$user = User::factory()->create(['email' => '[email protected]']);
|
||||
|
||||
Livewire::actingAs(User::factory()->admin()->create())
|
||||
->test('users::form', ['user' => $user->id])
|
||||
->call('sendPasswordLink')
|
||||
->assertSee('Linkkiä ei voitu lähettää');
|
||||
});
|
||||
|
||||
it('still creates the first admin from the command', function () {
|
||||
$this->artisan('users:create-admin', ['name' => 'Anna Admin', 'email' => '[email protected]'])
|
||||
->expectsOutputToContain('could not be sent')
|
||||
->assertSuccessful();
|
||||
|
||||
expect(User::query()->where('email', '[email protected]')->exists())->toBeTrue();
|
||||
});
|
||||
@@ -53,6 +53,22 @@ it('shows the same message for an unknown address', function () {
|
||||
Notification::assertNothingSent();
|
||||
});
|
||||
|
||||
it('sends no link to a deactivated user or an intern past the last day, with the same message', function (string $state) {
|
||||
Notification::fake();
|
||||
$user = match ($state) {
|
||||
'inactive' => User::factory()->inactive()->create(),
|
||||
'intern ended' => User::factory()->intern(now()->subDays(2)->toDateString())->create(),
|
||||
};
|
||||
|
||||
Livewire::test('users::forgot-password')
|
||||
->set('email', $user->email)
|
||||
->call('sendLink')
|
||||
->assertHasNoErrors()
|
||||
->assertSee('Jos osoitteella on käyttäjätunnus');
|
||||
|
||||
Notification::assertNothingSent();
|
||||
})->with(['inactive', 'intern ended']);
|
||||
|
||||
it('sets a new password with a valid link', function () {
|
||||
$user = User::factory()->create(['email' => '[email protected]']);
|
||||
$token = Password::createToken($user);
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
<?php
|
||||
|
||||
use App\Models\User;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Livewire\Livewire;
|
||||
|
||||
uses(RefreshDatabase::class);
|
||||
|
||||
it('keeps working for an intern whose supervisor was deleted', function () {
|
||||
$supervisor = User::factory()->create();
|
||||
$intern = User::factory()->intern(now()->addMonth()->toDateString(), $supervisor)->create();
|
||||
|
||||
$supervisor->delete();
|
||||
|
||||
expect($intern->fresh()->supervisor_id)->toBeNull();
|
||||
|
||||
$this->actingAs($intern)->get(route('customers.index'))->assertOk();
|
||||
});
|
||||
|
||||
it('asks for a new supervisor when an admin edits such an intern', function () {
|
||||
$supervisor = User::factory()->create();
|
||||
$intern = User::factory()->intern('2027-05-31', $supervisor)->create();
|
||||
$supervisor->delete();
|
||||
|
||||
Livewire::actingAs(User::factory()->admin()->create())
|
||||
->test('users::form', ['user' => $intern->id])
|
||||
->set('form.name', 'Ida Uusi')
|
||||
->call('save')
|
||||
->assertHasErrors(['form.supervisor_id']);
|
||||
});
|
||||
@@ -110,6 +110,20 @@ it('deactivates a user', function () {
|
||||
expect($user->fresh()->is_active)->toBeFalse();
|
||||
});
|
||||
|
||||
it('does not deactivate a supervisor who still has active interns', function () {
|
||||
$supervisor = User::factory()->create();
|
||||
User::factory()->intern('2027-05-31', $supervisor)->create();
|
||||
|
||||
Livewire::actingAs($this->admin)
|
||||
->test('users::form', ['user' => $supervisor->id])
|
||||
->set('form.active', false)
|
||||
->call('save')
|
||||
->assertHasErrors(['form.role'])
|
||||
->assertSee('Vaihda harjoittelijoille ensin uusi vastuuhenkilö.');
|
||||
|
||||
expect($supervisor->fresh()->is_active)->toBeTrue();
|
||||
});
|
||||
|
||||
it('does not let the last admin deactivate themselves', function () {
|
||||
Livewire::actingAs($this->admin)
|
||||
->test('users::form', ['user' => $this->admin->id])
|
||||
|
||||
@@ -10,6 +10,7 @@ use App\Modules\Users\Domain\Enums\Role;
|
||||
use App\Modules\Users\Domain\Exceptions\EmailAlreadyInUse;
|
||||
use App\Modules\Users\Domain\Exceptions\InvalidSupervisor;
|
||||
use App\Modules\Users\Domain\Exceptions\LastAdminCannotBeRemoved;
|
||||
use App\Modules\Users\Domain\Exceptions\SupervisorHasInterns;
|
||||
use App\Modules\Users\Domain\Exceptions\UserAccountNotFound;
|
||||
use App\Modules\Users\Domain\Services\SupervisorRule;
|
||||
use App\Modules\Users\Domain\ValueObjects\EmailAddress;
|
||||
@@ -33,14 +34,14 @@ beforeEach(function () {
|
||||
});
|
||||
|
||||
it('creates a user and sends a link for setting the password', function () {
|
||||
$userId = $this->createUser->execute(new UserAccountData('Maija Meikäläinen', '[email protected]', Role::Employee));
|
||||
$userId = $this->createUser->execute(new UserAccountData('Maija Meikäläinen', '[email protected]', Role::Employee))->userId;
|
||||
|
||||
expect($this->users->findById($userId)?->email()->value)->toBe('[email protected]')
|
||||
->and($this->passwordLinks->sentTo)->toBe(['[email protected]']);
|
||||
});
|
||||
|
||||
it('creates an intern with an end date and a supervisor', function () {
|
||||
$userId = $this->createUser->execute(new UserAccountData('Ida', '[email protected]', Role::Intern, true, '2027-05-31', $this->employeeId));
|
||||
$userId = $this->createUser->execute(new UserAccountData('Ida', '[email protected]', Role::Intern, true, '2027-05-31', $this->employeeId))->userId;
|
||||
|
||||
$intern = $this->users->findById($userId);
|
||||
|
||||
@@ -79,6 +80,24 @@ it('lets an admin be demoted when another active admin remains', function () {
|
||||
expect($this->users->findById($this->adminId)?->role())->toBe(Role::Management);
|
||||
});
|
||||
|
||||
it('does not let a supervisor of active interns stop supervising', function (bool $active, Role $role) {
|
||||
$this->createUser->execute(new UserAccountData('Ida', '[email protected]', Role::Intern, true, '2027-05-31', $this->employeeId));
|
||||
|
||||
$this->updateUser->execute($this->employeeId, new UserAccountData('Eero Työntekijä', '[email protected]', $role, $active));
|
||||
})->throws(SupervisorHasInterns::class)->with([
|
||||
'deactivated' => [false, Role::Employee],
|
||||
'made a subcontractor' => [true, Role::Subcontractor],
|
||||
]);
|
||||
|
||||
it('lets a supervisor without interns change role, and one with interns move between supervising roles', function () {
|
||||
$this->createUser->execute(new UserAccountData('Ida', '[email protected]', Role::Intern, true, '2027-05-31', $this->employeeId));
|
||||
|
||||
$this->updateUser->execute($this->employeeId, new UserAccountData('Eero Työntekijä', '[email protected]', Role::Management));
|
||||
$this->updateUser->execute($this->adminId, new UserAccountData('Anna Admin', '[email protected]', Role::Admin));
|
||||
|
||||
expect($this->users->findById($this->employeeId)?->role())->toBe(Role::Management);
|
||||
});
|
||||
|
||||
it('fails to update an unknown user', function () {
|
||||
$this->updateUser->execute(999, new UserAccountData('X', '[email protected]', Role::Employee));
|
||||
})->throws(UserAccountNotFound::class);
|
||||
@@ -90,7 +109,7 @@ it('sends a password link to a stored user', function () {
|
||||
});
|
||||
|
||||
it('checks whether a user may log in today', function () {
|
||||
$internId = $this->createUser->execute(new UserAccountData('Ida', '[email protected]', Role::Intern, true, '2027-05-31', $this->employeeId));
|
||||
$internId = $this->createUser->execute(new UserAccountData('Ida', '[email protected]', Role::Intern, true, '2027-05-31', $this->employeeId))->userId;
|
||||
$clock = new FakeClock(new DateTimeImmutable('2027-05-31'));
|
||||
$checkLogin = new CheckLoginAllowed($this->users, $clock);
|
||||
|
||||
|
||||
Reference in New Issue
Block a user