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:
@@ -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
|
||||
|
||||
|
||||
Reference in New Issue
Block a user