Add login, password reset and user management (Users module)
New Users module with the four layers: - Domain: Role enum, UserAccount entity (intern needs end date and supervisor, login allowed until the end of the last day), email and name value objects, SupervisorRule, last-admin protection. - Application: CreateUserAccount (emails a set-password link), UpdateUserAccount, SendPasswordSetupLink, CheckLoginAllowed, query contract and Clock (business time zone Europe/Helsinki). - Infrastructure: users table gets role, is_active, employment_ends_on and supervisor_id; Eloquent repository and queries; Password broker link sender with a Finnish email; Gate users.manage. - Presentation: Livewire login (rate limited), forgot and reset password pages, logout, EnsureAccountIsUsable middleware that ends sessions of deactivated users, admin-only user list and form, and users:create-admin command. Also: - Layout gets a labelled main menu, the signed-in user and logout. - Remove the local /dev/login; guests are redirected to /login. - Customers: customers.use ability (no subcontractors), authorization in mount and save, locked customerId, 404 for a missing customer, empty-state check uses the total count. - Architecture test lets module providers register their own Presentation classes; docs and CLAUDE.md updated. Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
+27
-1
@@ -3,20 +3,43 @@
|
||||
namespace App\Models;
|
||||
|
||||
// use Illuminate\Contracts\Auth\MustVerifyEmail;
|
||||
use App\Modules\Users\Domain\Enums\Role;
|
||||
use Database\Factories\UserFactory;
|
||||
use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
use Illuminate\Database\Eloquent\Attributes\Hidden;
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
use Illuminate\Foundation\Auth\User as Authenticatable;
|
||||
use Illuminate\Notifications\Notifiable;
|
||||
use Illuminate\Support\Carbon;
|
||||
|
||||
#[Fillable(['name', 'email', 'password'])]
|
||||
/**
|
||||
* Laravel's authentication model. It belongs to the Users module's
|
||||
* Infrastructure layer; other modules use it only through auth() and Gate.
|
||||
*
|
||||
* @property int $id
|
||||
* @property string $name
|
||||
* @property string $email
|
||||
* @property Role $role
|
||||
* @property bool $is_active
|
||||
* @property Carbon|null $employment_ends_on
|
||||
* @property int|null $supervisor_id
|
||||
*/
|
||||
#[Fillable(['name', 'email', 'password', 'role', 'is_active', 'employment_ends_on', 'supervisor_id'])]
|
||||
#[Hidden(['password', 'remember_token'])]
|
||||
class User extends Authenticatable
|
||||
{
|
||||
/** @use HasFactory<UserFactory> */
|
||||
use HasFactory, Notifiable;
|
||||
|
||||
/**
|
||||
* @return BelongsTo<User, $this>
|
||||
*/
|
||||
public function supervisor(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(User::class, 'supervisor_id');
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the attributes that should be cast.
|
||||
*
|
||||
@@ -27,6 +50,9 @@ class User extends Authenticatable
|
||||
return [
|
||||
'email_verified_at' => 'datetime',
|
||||
'password' => 'hashed',
|
||||
'role' => Role::class,
|
||||
'is_active' => 'boolean',
|
||||
'employment_ends_on' => 'date',
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,16 +2,19 @@
|
||||
|
||||
namespace App\Modules\Customers\Infrastructure\Providers;
|
||||
|
||||
use App\Models\User;
|
||||
use App\Modules\Customers\Application\Contracts\CustomerQueries;
|
||||
use App\Modules\Customers\Domain\Contracts\CustomerRepository;
|
||||
use App\Modules\Customers\Infrastructure\Persistence\Repositories\EloquentCustomerQueries;
|
||||
use App\Modules\Customers\Infrastructure\Persistence\Repositories\EloquentCustomerRepository;
|
||||
use App\Modules\Users\Domain\Enums\Role;
|
||||
use Illuminate\Support\Facades\Gate;
|
||||
use Illuminate\Support\ServiceProvider;
|
||||
use Livewire\Livewire;
|
||||
|
||||
/**
|
||||
* Wires the Customers module into Laravel: contract bindings, routes and
|
||||
* the `customers::` Livewire namespace.
|
||||
* Wires the Customers module into Laravel: contract bindings, routes, the
|
||||
* `customers::` Livewire namespace and the `customers.use` ability.
|
||||
*/
|
||||
class CustomersServiceProvider extends ServiceProvider
|
||||
{
|
||||
@@ -32,5 +35,8 @@ class CustomersServiceProvider extends ServiceProvider
|
||||
if (! $this->app->routesAreCached()) {
|
||||
$this->loadRoutesFrom($presentationPath.'/Routes/web.php');
|
||||
}
|
||||
|
||||
// Subcontractors see only the customer jobs assigned to them, not the customer register.
|
||||
Gate::define('customers.use', fn (User $user): bool => $user->role !== Role::Subcontractor);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4,8 +4,10 @@ use App\Modules\Customers\Application\Contracts\CustomerQueries;
|
||||
use App\Modules\Customers\Application\UseCases\RegisterCustomer;
|
||||
use App\Modules\Customers\Application\UseCases\UpdateCustomer;
|
||||
use App\Modules\Customers\Domain\Enums\CustomerType;
|
||||
use App\Modules\Customers\Domain\Exceptions\CustomerNotFound;
|
||||
use App\Modules\Customers\Presentation\Livewire\Forms\CustomerForm;
|
||||
use App\Modules\Shared\Domain\Exceptions\DomainException;
|
||||
use Livewire\Attributes\Locked;
|
||||
use Livewire\Component;
|
||||
|
||||
/**
|
||||
@@ -13,12 +15,15 @@ use Livewire\Component;
|
||||
*/
|
||||
new class extends Component
|
||||
{
|
||||
#[Locked]
|
||||
public ?int $customerId = null;
|
||||
|
||||
public CustomerForm $form;
|
||||
|
||||
public function mount(CustomerQueries $customerQueries, ?int $customer = null): void
|
||||
{
|
||||
$this->authorize('customers.use');
|
||||
|
||||
if ($customer === null) {
|
||||
return;
|
||||
}
|
||||
@@ -33,6 +38,8 @@ new class extends Component
|
||||
|
||||
public function save(RegisterCustomer $registerCustomer, UpdateCustomer $updateCustomer): void
|
||||
{
|
||||
$this->authorize('customers.use');
|
||||
|
||||
$data = $this->form->toData();
|
||||
|
||||
try {
|
||||
@@ -43,6 +50,8 @@ new class extends Component
|
||||
$updateCustomer->execute($this->customerId, $data);
|
||||
session()->flash('status', __('customers.updated', ['name' => $data->name]));
|
||||
}
|
||||
} catch (CustomerNotFound) {
|
||||
abort(404);
|
||||
} catch (DomainException $exception) {
|
||||
$this->form->showDomainError($exception);
|
||||
|
||||
|
||||
@@ -22,6 +22,11 @@ new class extends Component
|
||||
$this->customerQueries = $customerQueries;
|
||||
}
|
||||
|
||||
public function mount(): void
|
||||
{
|
||||
$this->authorize('customers.use');
|
||||
}
|
||||
|
||||
public function updatedSearch(): void
|
||||
{
|
||||
$this->resetPage();
|
||||
@@ -68,7 +73,7 @@ new class extends Component
|
||||
{{ trans_choice('customers.result_count', $this->customers->total(), ['count' => $this->customers->total()]) }}
|
||||
</flux:text>
|
||||
|
||||
@if ($this->customers->isEmpty())
|
||||
@if ($this->customers->total() === 0)
|
||||
<flux:text>{{ __('customers.empty') }}</flux:text>
|
||||
@else
|
||||
<flux:table :paginate="$this->customers">
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
use Illuminate\Support\Facades\Route;
|
||||
|
||||
Route::middleware(['web', 'auth'])
|
||||
Route::middleware(['web', 'auth', 'can:customers.use'])
|
||||
->prefix('customers')
|
||||
->name('customers.')
|
||||
->group(function () {
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Users\Application\Contracts;
|
||||
|
||||
use DateTimeImmutable;
|
||||
|
||||
interface Clock
|
||||
{
|
||||
/**
|
||||
* The current day in the company's time zone.
|
||||
*/
|
||||
public function today(): DateTimeImmutable;
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Users\Application\Contracts;
|
||||
|
||||
use App\Modules\Users\Domain\ValueObjects\EmailAddress;
|
||||
|
||||
/**
|
||||
* Emails a link for setting a new password. New users get the same link
|
||||
* to set their first password.
|
||||
*/
|
||||
interface PasswordLinkSender
|
||||
{
|
||||
/**
|
||||
* @return bool False when a link was sent to this address too recently.
|
||||
*/
|
||||
public function sendSetupLink(EmailAddress $email): bool;
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Users\Application\Contracts;
|
||||
|
||||
use App\Modules\Users\Application\DTOs\UserOption;
|
||||
use App\Modules\Users\Application\DTOs\UserSummary;
|
||||
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
|
||||
|
||||
/**
|
||||
* Read side of the Users module.
|
||||
*/
|
||||
interface UserAccountQueries
|
||||
{
|
||||
public function findSummary(int $id): ?UserSummary;
|
||||
|
||||
/**
|
||||
* Users ordered by name, filtered by a name or email fragment.
|
||||
*
|
||||
* @return LengthAwarePaginator<int, UserSummary>
|
||||
*/
|
||||
public function paginate(?string $search, int $perPage = 25): LengthAwarePaginator;
|
||||
|
||||
/**
|
||||
* Active management and employee users who can supervise an intern.
|
||||
*
|
||||
* @return list<UserOption>
|
||||
*/
|
||||
public function supervisorOptions(?int $exceptUserId = null): array;
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Users\Application\DTOs;
|
||||
|
||||
use App\Modules\Users\Domain\Enums\Role;
|
||||
|
||||
/**
|
||||
* Input for creating a user or changing a user's details.
|
||||
*/
|
||||
final readonly class UserAccountData
|
||||
{
|
||||
/**
|
||||
* @param string|null $employmentEndsOn Date as Y-m-d.
|
||||
*/
|
||||
public function __construct(
|
||||
public string $name,
|
||||
public string $email,
|
||||
public Role $role,
|
||||
public bool $active = true,
|
||||
public ?string $employmentEndsOn = null,
|
||||
public ?int $supervisorId = null,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* @param array{name: string, email: string, role: string|Role, active?: bool, employment_ends_on?: string|null, supervisor_id?: int|string|null} $data
|
||||
*/
|
||||
public static function fromArray(array $data): self
|
||||
{
|
||||
$endsOn = trim((string) ($data['employment_ends_on'] ?? ''));
|
||||
$supervisorId = $data['supervisor_id'] ?? null;
|
||||
|
||||
return new self(
|
||||
name: $data['name'],
|
||||
email: $data['email'],
|
||||
role: $data['role'] instanceof Role ? $data['role'] : Role::from($data['role']),
|
||||
active: $data['active'] ?? true,
|
||||
employmentEndsOn: $endsOn === '' ? null : $endsOn,
|
||||
supervisorId: $supervisorId === null || $supervisorId === '' ? null : (int) $supervisorId,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Users\Application\DTOs;
|
||||
|
||||
/**
|
||||
* A user as a choice in a select list.
|
||||
*/
|
||||
final readonly class UserOption
|
||||
{
|
||||
public function __construct(
|
||||
public int $id,
|
||||
public string $name,
|
||||
) {}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Users\Application\DTOs;
|
||||
|
||||
use App\Modules\Users\Domain\Enums\Role;
|
||||
|
||||
/**
|
||||
* Read model of a user for lists and forms.
|
||||
*/
|
||||
final readonly class UserSummary
|
||||
{
|
||||
/**
|
||||
* @param string|null $employmentEndsOn Date as Y-m-d.
|
||||
*/
|
||||
public function __construct(
|
||||
public int $id,
|
||||
public string $name,
|
||||
public string $email,
|
||||
public Role $role,
|
||||
public bool $active,
|
||||
public ?string $employmentEndsOn,
|
||||
public ?int $supervisorId,
|
||||
public ?string $supervisorName,
|
||||
) {}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Users\Application\UseCases;
|
||||
|
||||
use App\Modules\Users\Application\Contracts\Clock;
|
||||
use App\Modules\Users\Domain\Contracts\UserAccountRepository;
|
||||
|
||||
/**
|
||||
* Whether a user may sign in or keep using the system today: active, and
|
||||
* an intern's last day not passed.
|
||||
*/
|
||||
final class CheckLoginAllowed
|
||||
{
|
||||
public function __construct(
|
||||
private UserAccountRepository $users,
|
||||
private Clock $clock,
|
||||
) {}
|
||||
|
||||
public function execute(int $userId): bool
|
||||
{
|
||||
return $this->users->findById($userId)?->canLogInOn($this->clock->today()) ?? false;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Users\Application\UseCases;
|
||||
|
||||
use App\Modules\Shared\Application\Contracts\TransactionManager;
|
||||
use App\Modules\Users\Application\Contracts\PasswordLinkSender;
|
||||
use App\Modules\Users\Application\DTOs\UserAccountData;
|
||||
use App\Modules\Users\Domain\Contracts\UserAccountRepository;
|
||||
use App\Modules\Users\Domain\Entities\UserAccount;
|
||||
use App\Modules\Users\Domain\Exceptions\EmailAlreadyInUse;
|
||||
use App\Modules\Users\Domain\Exceptions\InvalidSupervisor;
|
||||
use App\Modules\Users\Domain\Services\SupervisorRule;
|
||||
use App\Modules\Users\Domain\ValueObjects\EmailAddress;
|
||||
use App\Modules\Users\Domain\ValueObjects\PersonName;
|
||||
|
||||
/**
|
||||
* Creates a user and emails a link for setting the first password, so
|
||||
* nobody handles the password in plain text.
|
||||
*/
|
||||
final class CreateUserAccount
|
||||
{
|
||||
public function __construct(
|
||||
private UserAccountRepository $users,
|
||||
private SupervisorRule $supervisorRule,
|
||||
private TransactionManager $transactions,
|
||||
private PasswordLinkSender $passwordLinks,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* @return int The new user's id.
|
||||
*
|
||||
* @throws EmailAlreadyInUse
|
||||
* @throws InvalidSupervisor
|
||||
*/
|
||||
public function execute(UserAccountData $data): int
|
||||
{
|
||||
$user = UserAccount::register(
|
||||
new PersonName($data->name),
|
||||
new EmailAddress($data->email),
|
||||
$data->role,
|
||||
EmploymentEndDate::parse($data->employmentEndsOn),
|
||||
$data->supervisorId,
|
||||
);
|
||||
|
||||
$userId = $this->transactions->run(function () use ($user): int {
|
||||
if ($this->users->isEmailTaken($user->email())) {
|
||||
throw new EmailAlreadyInUse;
|
||||
}
|
||||
|
||||
$this->supervisorRule->ensureValidFor($user);
|
||||
|
||||
return (int) $this->users->save($user)->id();
|
||||
});
|
||||
|
||||
$this->passwordLinks->sendSetupLink($user->email());
|
||||
|
||||
return $userId;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Users\Application\UseCases;
|
||||
|
||||
use DateTimeImmutable;
|
||||
use InvalidArgumentException;
|
||||
|
||||
/**
|
||||
* Turns the Y-m-d date of a UserAccountData into a date object.
|
||||
*
|
||||
* @internal Shared by the user use cases.
|
||||
*/
|
||||
final class EmploymentEndDate
|
||||
{
|
||||
public static function parse(?string $date): ?DateTimeImmutable
|
||||
{
|
||||
if ($date === null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
$parsed = DateTimeImmutable::createFromFormat('!Y-m-d', $date);
|
||||
|
||||
if ($parsed === false || $parsed->format('Y-m-d') !== $date) {
|
||||
throw new InvalidArgumentException("Invalid employment end date [{$date}], expected Y-m-d.");
|
||||
}
|
||||
|
||||
return $parsed;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Users\Application\UseCases;
|
||||
|
||||
use App\Modules\Users\Application\Contracts\PasswordLinkSender;
|
||||
use App\Modules\Users\Domain\Contracts\UserAccountRepository;
|
||||
use App\Modules\Users\Domain\Exceptions\UserAccountNotFound;
|
||||
|
||||
/**
|
||||
* An admin sends a user a link for setting a new password.
|
||||
*/
|
||||
final class SendPasswordSetupLink
|
||||
{
|
||||
public function __construct(
|
||||
private UserAccountRepository $users,
|
||||
private PasswordLinkSender $passwordLinks,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* @return bool False when a link was sent to the user too recently.
|
||||
*
|
||||
* @throws UserAccountNotFound
|
||||
*/
|
||||
public function execute(int $userId): bool
|
||||
{
|
||||
$user = $this->users->findById($userId) ?? throw new UserAccountNotFound($userId);
|
||||
|
||||
return $this->passwordLinks->sendSetupLink($user->email());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Users\Application\UseCases;
|
||||
|
||||
use App\Modules\Shared\Application\Contracts\TransactionManager;
|
||||
use App\Modules\Users\Application\DTOs\UserAccountData;
|
||||
use App\Modules\Users\Domain\Contracts\UserAccountRepository;
|
||||
use App\Modules\Users\Domain\Exceptions\EmailAlreadyInUse;
|
||||
use App\Modules\Users\Domain\Exceptions\InvalidSupervisor;
|
||||
use App\Modules\Users\Domain\Exceptions\LastAdminCannotBeRemoved;
|
||||
use App\Modules\Users\Domain\Exceptions\UserAccountNotFound;
|
||||
use App\Modules\Users\Domain\Services\SupervisorRule;
|
||||
use App\Modules\Users\Domain\ValueObjects\EmailAddress;
|
||||
use App\Modules\Users\Domain\ValueObjects\PersonName;
|
||||
|
||||
final class UpdateUserAccount
|
||||
{
|
||||
public function __construct(
|
||||
private UserAccountRepository $users,
|
||||
private SupervisorRule $supervisorRule,
|
||||
private TransactionManager $transactions,
|
||||
) {}
|
||||
|
||||
/**
|
||||
* @throws UserAccountNotFound
|
||||
* @throws EmailAlreadyInUse
|
||||
* @throws InvalidSupervisor
|
||||
* @throws LastAdminCannotBeRemoved
|
||||
*/
|
||||
public function execute(int $userId, UserAccountData $data): void
|
||||
{
|
||||
$name = new PersonName($data->name);
|
||||
$email = new EmailAddress($data->email);
|
||||
$endsOn = EmploymentEndDate::parse($data->employmentEndsOn);
|
||||
|
||||
$this->transactions->run(function () use ($userId, $data, $name, $email, $endsOn): void {
|
||||
$user = $this->users->findById($userId) ?? throw new UserAccountNotFound($userId);
|
||||
$wasActiveAdmin = $user->isActiveAdmin();
|
||||
|
||||
if ($this->users->isEmailTaken($email, $userId)) {
|
||||
throw new EmailAlreadyInUse;
|
||||
}
|
||||
|
||||
$user->changeDetails($name, $email, $data->role, $data->active, $endsOn, $data->supervisorId);
|
||||
|
||||
if ($wasActiveAdmin && ! $user->isActiveAdmin() && $this->users->countActiveAdmins($userId) === 0) {
|
||||
throw new LastAdminCannotBeRemoved;
|
||||
}
|
||||
|
||||
$this->supervisorRule->ensureValidFor($user);
|
||||
|
||||
$this->users->save($user);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Users\Domain\Contracts;
|
||||
|
||||
use App\Modules\Users\Domain\Entities\UserAccount;
|
||||
use App\Modules\Users\Domain\ValueObjects\EmailAddress;
|
||||
|
||||
interface UserAccountRepository
|
||||
{
|
||||
public function findById(int $id): ?UserAccount;
|
||||
|
||||
/**
|
||||
* Inserts a new user or updates a stored one, and returns the stored
|
||||
* user (a new one gets its id here).
|
||||
*/
|
||||
public function save(UserAccount $user): UserAccount;
|
||||
|
||||
public function isEmailTaken(EmailAddress $email, ?int $exceptUserId = null): bool;
|
||||
|
||||
public function countActiveAdmins(?int $exceptUserId = null): int;
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Users\Domain\Entities;
|
||||
|
||||
use App\Modules\Users\Domain\Enums\Role;
|
||||
use App\Modules\Users\Domain\Exceptions\InternRequiresEndDateAndSupervisor;
|
||||
use App\Modules\Users\Domain\Exceptions\InvalidSupervisor;
|
||||
use App\Modules\Users\Domain\ValueObjects\EmailAddress;
|
||||
use App\Modules\Users\Domain\ValueObjects\PersonName;
|
||||
use DateTimeImmutable;
|
||||
|
||||
/**
|
||||
* A person who can sign in to the system.
|
||||
*
|
||||
* Interns have an employment end date (their last day with access) and a
|
||||
* supervisor. Other roles have neither: they are cleared on a role change.
|
||||
*/
|
||||
final class UserAccount
|
||||
{
|
||||
private function __construct(
|
||||
private ?int $id,
|
||||
private PersonName $name,
|
||||
private EmailAddress $email,
|
||||
private Role $role,
|
||||
private bool $active,
|
||||
private ?DateTimeImmutable $employmentEndsOn,
|
||||
private ?int $supervisorId,
|
||||
) {
|
||||
$this->applyRoleRules();
|
||||
}
|
||||
|
||||
/**
|
||||
* A new, active user that is not stored yet, so it has no id.
|
||||
*/
|
||||
public static function register(
|
||||
PersonName $name,
|
||||
EmailAddress $email,
|
||||
Role $role,
|
||||
?DateTimeImmutable $employmentEndsOn = null,
|
||||
?int $supervisorId = null,
|
||||
): self {
|
||||
return new self(null, $name, $email, $role, true, $employmentEndsOn, $supervisorId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Rebuilds a stored user. Used only by repositories.
|
||||
*/
|
||||
public static function reconstitute(
|
||||
int $id,
|
||||
PersonName $name,
|
||||
EmailAddress $email,
|
||||
Role $role,
|
||||
bool $active,
|
||||
?DateTimeImmutable $employmentEndsOn,
|
||||
?int $supervisorId,
|
||||
): self {
|
||||
return new self($id, $name, $email, $role, $active, $employmentEndsOn, $supervisorId);
|
||||
}
|
||||
|
||||
public function changeDetails(
|
||||
PersonName $name,
|
||||
EmailAddress $email,
|
||||
Role $role,
|
||||
bool $active,
|
||||
?DateTimeImmutable $employmentEndsOn,
|
||||
?int $supervisorId,
|
||||
): void {
|
||||
$changed = clone $this;
|
||||
$changed->name = $name;
|
||||
$changed->email = $email;
|
||||
$changed->role = $role;
|
||||
$changed->active = $active;
|
||||
$changed->employmentEndsOn = $employmentEndsOn;
|
||||
$changed->supervisorId = $supervisorId;
|
||||
$changed->applyRoleRules();
|
||||
|
||||
foreach (get_object_vars($changed) as $property => $value) {
|
||||
$this->{$property} = $value;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the user may sign in on the given day. An intern's end date
|
||||
* is the last day with access.
|
||||
*/
|
||||
public function canLogInOn(DateTimeImmutable $day): bool
|
||||
{
|
||||
if (! $this->active) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return $this->employmentEndsOn === null
|
||||
|| $day->format('Y-m-d') <= $this->employmentEndsOn->format('Y-m-d');
|
||||
}
|
||||
|
||||
public function isActiveAdmin(): bool
|
||||
{
|
||||
return $this->active && $this->role === Role::Admin;
|
||||
}
|
||||
|
||||
public function id(): ?int
|
||||
{
|
||||
return $this->id;
|
||||
}
|
||||
|
||||
public function name(): PersonName
|
||||
{
|
||||
return $this->name;
|
||||
}
|
||||
|
||||
public function email(): EmailAddress
|
||||
{
|
||||
return $this->email;
|
||||
}
|
||||
|
||||
public function role(): Role
|
||||
{
|
||||
return $this->role;
|
||||
}
|
||||
|
||||
public function isActive(): bool
|
||||
{
|
||||
return $this->active;
|
||||
}
|
||||
|
||||
public function employmentEndsOn(): ?DateTimeImmutable
|
||||
{
|
||||
return $this->employmentEndsOn;
|
||||
}
|
||||
|
||||
public function supervisorId(): ?int
|
||||
{
|
||||
return $this->supervisorId;
|
||||
}
|
||||
|
||||
private function applyRoleRules(): void
|
||||
{
|
||||
if ($this->role !== Role::Intern) {
|
||||
$this->employmentEndsOn = null;
|
||||
$this->supervisorId = null;
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
if ($this->employmentEndsOn === null || $this->supervisorId === null) {
|
||||
throw new InternRequiresEndDateAndSupervisor;
|
||||
}
|
||||
|
||||
if ($this->id !== null && $this->supervisorId === $this->id) {
|
||||
throw new InvalidSupervisor;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Users\Domain\Enums;
|
||||
|
||||
/**
|
||||
* User roles. Other modules may use this enum in their authorization
|
||||
* rules: it is the one published Domain type of the Users module.
|
||||
*/
|
||||
enum Role: string
|
||||
{
|
||||
case Admin = 'admin';
|
||||
case Management = 'management';
|
||||
case Employee = 'employee';
|
||||
case Intern = 'intern';
|
||||
case Subcontractor = 'subcontractor';
|
||||
|
||||
public function canManageUsers(): bool
|
||||
{
|
||||
return $this === self::Admin;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a user with this role can be an intern's supervisor.
|
||||
*/
|
||||
public function canSupervise(): bool
|
||||
{
|
||||
return $this === self::Management || $this === self::Employee;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Users\Domain\Exceptions;
|
||||
|
||||
use App\Modules\Shared\Domain\Exceptions\DomainException;
|
||||
|
||||
final class EmailAlreadyInUse extends DomainException
|
||||
{
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct('The email address already belongs to another user.');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Users\Domain\Exceptions;
|
||||
|
||||
use App\Modules\Shared\Domain\Exceptions\DomainException;
|
||||
|
||||
final class InternRequiresEndDateAndSupervisor extends DomainException
|
||||
{
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct('An intern must have an employment end date and a supervisor.');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Users\Domain\Exceptions;
|
||||
|
||||
use App\Modules\Shared\Domain\Exceptions\DomainException;
|
||||
|
||||
final class InvalidEmailAddress extends DomainException
|
||||
{
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct('The email address is not valid.');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Users\Domain\Exceptions;
|
||||
|
||||
use App\Modules\Shared\Domain\Exceptions\DomainException;
|
||||
|
||||
final class InvalidPersonName extends DomainException
|
||||
{
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct('The name must be 1–255 characters.');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Users\Domain\Exceptions;
|
||||
|
||||
use App\Modules\Shared\Domain\Exceptions\DomainException;
|
||||
|
||||
final class InvalidSupervisor extends DomainException
|
||||
{
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct('The supervisor must be an active management or employee user other than the intern.');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Users\Domain\Exceptions;
|
||||
|
||||
use App\Modules\Shared\Domain\Exceptions\DomainException;
|
||||
|
||||
final class LastAdminCannotBeRemoved extends DomainException
|
||||
{
|
||||
public function __construct()
|
||||
{
|
||||
parent::__construct('The last active admin cannot be deactivated or given another role.');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Users\Domain\Exceptions;
|
||||
|
||||
use App\Modules\Shared\Domain\Exceptions\DomainException;
|
||||
|
||||
final class UserAccountNotFound extends DomainException
|
||||
{
|
||||
public function __construct(public readonly int $userId)
|
||||
{
|
||||
parent::__construct("User {$userId} was not found.");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Users\Domain\Services;
|
||||
|
||||
use App\Modules\Users\Domain\Contracts\UserAccountRepository;
|
||||
use App\Modules\Users\Domain\Entities\UserAccount;
|
||||
use App\Modules\Users\Domain\Exceptions\InvalidSupervisor;
|
||||
|
||||
/**
|
||||
* An intern's supervisor must be another active management or employee
|
||||
* user. Needs the repository, so it cannot live in the entity.
|
||||
*/
|
||||
final class SupervisorRule
|
||||
{
|
||||
public function __construct(private UserAccountRepository $users) {}
|
||||
|
||||
/**
|
||||
* @throws InvalidSupervisor
|
||||
*/
|
||||
public function ensureValidFor(UserAccount $user): void
|
||||
{
|
||||
$supervisorId = $user->supervisorId();
|
||||
|
||||
if ($supervisorId === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
$supervisor = $this->users->findById($supervisorId);
|
||||
|
||||
if ($supervisor === null
|
||||
|| $supervisor->id() === $user->id()
|
||||
|| ! $supervisor->isActive()
|
||||
|| ! $supervisor->role()->canSupervise()) {
|
||||
throw new InvalidSupervisor;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Users\Domain\ValueObjects;
|
||||
|
||||
use App\Modules\Users\Domain\Exceptions\InvalidEmailAddress;
|
||||
|
||||
/**
|
||||
* Login email address, stored in lower case so it is unique regardless
|
||||
* of how it was typed.
|
||||
*/
|
||||
final readonly class EmailAddress
|
||||
{
|
||||
public const int MAX_LENGTH = 255;
|
||||
|
||||
public string $value;
|
||||
|
||||
public function __construct(string $value)
|
||||
{
|
||||
$value = mb_strtolower(trim($value));
|
||||
|
||||
if (mb_strlen($value) > self::MAX_LENGTH || filter_var($value, FILTER_VALIDATE_EMAIL) === false) {
|
||||
throw new InvalidEmailAddress;
|
||||
}
|
||||
|
||||
$this->value = $value;
|
||||
}
|
||||
|
||||
public function equals(self $other): bool
|
||||
{
|
||||
return $this->value === $other->value;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
<?php
|
||||
|
||||
declare(strict_types=1);
|
||||
|
||||
namespace App\Modules\Users\Domain\ValueObjects;
|
||||
|
||||
use App\Modules\Users\Domain\Exceptions\InvalidPersonName;
|
||||
|
||||
final readonly class PersonName
|
||||
{
|
||||
public const int MAX_LENGTH = 255;
|
||||
|
||||
public string $value;
|
||||
|
||||
public function __construct(string $value)
|
||||
{
|
||||
$value = trim(preg_replace('/\s+/u', ' ', $value) ?? $value);
|
||||
|
||||
if ($value === '' || mb_strlen($value) > self::MAX_LENGTH) {
|
||||
throw new InvalidPersonName;
|
||||
}
|
||||
|
||||
$this->value = $value;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
<?php
|
||||
|
||||
namespace App\Modules\Users\Infrastructure\Auth;
|
||||
|
||||
use App\Modules\Users\Application\Contracts\PasswordLinkSender;
|
||||
use App\Modules\Users\Domain\ValueObjects\EmailAddress;
|
||||
use Illuminate\Contracts\Auth\PasswordBroker;
|
||||
|
||||
/**
|
||||
* Sends Laravel's password reset notification, which the Users module
|
||||
* provider words as a "set your password" email.
|
||||
*/
|
||||
class LaravelPasswordLinkSender implements PasswordLinkSender
|
||||
{
|
||||
public function __construct(private PasswordBroker $passwords) {}
|
||||
|
||||
public function sendSetupLink(EmailAddress $email): bool
|
||||
{
|
||||
return $this->passwords->sendResetLink(['email' => $email->value]) === PasswordBroker::RESET_LINK_SENT;
|
||||
}
|
||||
}
|
||||
+66
@@ -0,0 +1,66 @@
|
||||
<?php
|
||||
|
||||
namespace App\Modules\Users\Infrastructure\Persistence\Repositories;
|
||||
|
||||
use App\Models\User;
|
||||
use App\Modules\Users\Application\Contracts\UserAccountQueries;
|
||||
use App\Modules\Users\Application\DTOs\UserOption;
|
||||
use App\Modules\Users\Application\DTOs\UserSummary;
|
||||
use App\Modules\Users\Domain\Enums\Role;
|
||||
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
|
||||
class EloquentUserAccountQueries implements UserAccountQueries
|
||||
{
|
||||
public function findSummary(int $id): ?UserSummary
|
||||
{
|
||||
$model = User::query()->with('supervisor:id,name')->find($id);
|
||||
|
||||
return $model === null ? null : $this->toSummary($model);
|
||||
}
|
||||
|
||||
public function paginate(?string $search, int $perPage = 25): LengthAwarePaginator
|
||||
{
|
||||
$search = trim((string) $search);
|
||||
|
||||
return User::query()
|
||||
->with('supervisor:id,name')
|
||||
->when($search !== '', function (Builder $query) use ($search): void {
|
||||
$pattern = '%'.addcslashes($search, '%_\\').'%';
|
||||
|
||||
$query->where(fn (Builder $query) => $query
|
||||
->where('name', 'like', $pattern)
|
||||
->orWhere('email', 'like', $pattern));
|
||||
})
|
||||
->orderBy('name')
|
||||
->paginate($perPage)
|
||||
->through(fn (User $model): UserSummary => $this->toSummary($model));
|
||||
}
|
||||
|
||||
public function supervisorOptions(?int $exceptUserId = null): array
|
||||
{
|
||||
return User::query()
|
||||
->whereIn('role', array_filter(Role::cases(), fn (Role $role): bool => $role->canSupervise()))
|
||||
->where('is_active', true)
|
||||
->when($exceptUserId !== null, fn (Builder $query) => $query->whereKeyNot($exceptUserId))
|
||||
->orderBy('name')
|
||||
->get(['id', 'name'])
|
||||
->map(fn (User $model): UserOption => new UserOption($model->id, $model->name))
|
||||
->values()
|
||||
->all();
|
||||
}
|
||||
|
||||
private function toSummary(User $model): UserSummary
|
||||
{
|
||||
return new UserSummary(
|
||||
id: $model->id,
|
||||
name: $model->name,
|
||||
email: $model->email,
|
||||
role: $model->role,
|
||||
active: $model->is_active,
|
||||
employmentEndsOn: $model->employment_ends_on?->toDateString(),
|
||||
supervisorId: $model->supervisor_id,
|
||||
supervisorName: $model->supervisor?->name,
|
||||
);
|
||||
}
|
||||
}
|
||||
+74
@@ -0,0 +1,74 @@
|
||||
<?php
|
||||
|
||||
namespace App\Modules\Users\Infrastructure\Persistence\Repositories;
|
||||
|
||||
use App\Models\User;
|
||||
use App\Modules\Users\Domain\Contracts\UserAccountRepository;
|
||||
use App\Modules\Users\Domain\Entities\UserAccount;
|
||||
use App\Modules\Users\Domain\Enums\Role;
|
||||
use App\Modules\Users\Domain\ValueObjects\EmailAddress;
|
||||
use App\Modules\Users\Domain\ValueObjects\PersonName;
|
||||
use DateTimeImmutable;
|
||||
use Illuminate\Support\Str;
|
||||
|
||||
class EloquentUserAccountRepository implements UserAccountRepository
|
||||
{
|
||||
public function findById(int $id): ?UserAccount
|
||||
{
|
||||
$model = User::query()->find($id);
|
||||
|
||||
return $model === null ? null : $this->toEntity($model);
|
||||
}
|
||||
|
||||
public function save(UserAccount $user): UserAccount
|
||||
{
|
||||
if ($user->id() === null) {
|
||||
$model = new User;
|
||||
// Nobody knows this password: the user sets their own through the emailed link.
|
||||
$model->password = Str::random(64);
|
||||
} else {
|
||||
$model = User::query()->findOrFail($user->id());
|
||||
}
|
||||
|
||||
$model->fill([
|
||||
'name' => $user->name()->value,
|
||||
'email' => $user->email()->value,
|
||||
'role' => $user->role(),
|
||||
'is_active' => $user->isActive(),
|
||||
'employment_ends_on' => $user->employmentEndsOn()?->format('Y-m-d'),
|
||||
'supervisor_id' => $user->supervisorId(),
|
||||
])->save();
|
||||
|
||||
return $this->toEntity($model->refresh());
|
||||
}
|
||||
|
||||
public function isEmailTaken(EmailAddress $email, ?int $exceptUserId = null): bool
|
||||
{
|
||||
return User::query()
|
||||
->where('email', $email->value)
|
||||
->when($exceptUserId !== null, fn ($query) => $query->whereKeyNot($exceptUserId))
|
||||
->exists();
|
||||
}
|
||||
|
||||
public function countActiveAdmins(?int $exceptUserId = null): int
|
||||
{
|
||||
return User::query()
|
||||
->where('role', Role::Admin)
|
||||
->where('is_active', true)
|
||||
->when($exceptUserId !== null, fn ($query) => $query->whereKeyNot($exceptUserId))
|
||||
->count();
|
||||
}
|
||||
|
||||
private function toEntity(User $model): UserAccount
|
||||
{
|
||||
return UserAccount::reconstitute(
|
||||
$model->id,
|
||||
new PersonName($model->name),
|
||||
new EmailAddress($model->email),
|
||||
$model->role,
|
||||
$model->is_active,
|
||||
$model->employment_ends_on === null ? null : DateTimeImmutable::createFromInterface($model->employment_ends_on),
|
||||
$model->supervisor_id,
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
<?php
|
||||
|
||||
namespace App\Modules\Users\Infrastructure\Providers;
|
||||
|
||||
use App\Models\User;
|
||||
use App\Modules\Users\Application\Contracts\Clock;
|
||||
use App\Modules\Users\Application\Contracts\PasswordLinkSender;
|
||||
use App\Modules\Users\Application\Contracts\UserAccountQueries;
|
||||
use App\Modules\Users\Domain\Contracts\UserAccountRepository;
|
||||
use App\Modules\Users\Infrastructure\Auth\LaravelPasswordLinkSender;
|
||||
use App\Modules\Users\Infrastructure\Persistence\Repositories\EloquentUserAccountQueries;
|
||||
use App\Modules\Users\Infrastructure\Persistence\Repositories\EloquentUserAccountRepository;
|
||||
use App\Modules\Users\Infrastructure\SystemClock;
|
||||
use App\Modules\Users\Presentation\Console\CreateAdminCommand;
|
||||
use App\Modules\Users\Presentation\Http\Middleware\EnsureAccountIsUsable;
|
||||
use Illuminate\Auth\Notifications\ResetPassword;
|
||||
use Illuminate\Notifications\Messages\MailMessage;
|
||||
use Illuminate\Routing\Router;
|
||||
use Illuminate\Support\Facades\Gate;
|
||||
use Illuminate\Support\ServiceProvider;
|
||||
use Illuminate\Validation\Rules\Password;
|
||||
use Livewire\Livewire;
|
||||
|
||||
/**
|
||||
* Wires the Users module into Laravel. As the module's composition root it
|
||||
* may register the module's Presentation classes (command, middleware).
|
||||
*/
|
||||
class UsersServiceProvider extends ServiceProvider
|
||||
{
|
||||
/**
|
||||
* @var array<class-string, class-string>
|
||||
*/
|
||||
public array $bindings = [
|
||||
UserAccountRepository::class => EloquentUserAccountRepository::class,
|
||||
UserAccountQueries::class => EloquentUserAccountQueries::class,
|
||||
PasswordLinkSender::class => LaravelPasswordLinkSender::class,
|
||||
];
|
||||
|
||||
public function register(): void
|
||||
{
|
||||
$this->app->bind(Clock::class, fn () => new SystemClock(config('app.business_timezone')));
|
||||
}
|
||||
|
||||
public function boot(Router $router): void
|
||||
{
|
||||
$presentationPath = dirname(__DIR__, 2).'/Presentation';
|
||||
|
||||
Livewire::addNamespace('users', viewPath: $presentationPath.'/Livewire');
|
||||
|
||||
if (! $this->app->routesAreCached()) {
|
||||
$this->loadRoutesFrom($presentationPath.'/Routes/web.php');
|
||||
}
|
||||
|
||||
$router->pushMiddlewareToGroup('web', EnsureAccountIsUsable::class);
|
||||
|
||||
if ($this->app->runningInConsole()) {
|
||||
$this->commands([CreateAdminCommand::class]);
|
||||
}
|
||||
|
||||
Gate::define('users.manage', fn (User $user): bool => $user->role->canManageUsers());
|
||||
|
||||
Password::defaults(fn () => Password::min(12));
|
||||
|
||||
ResetPassword::toMailUsing(fn (object $notifiable, string $token): MailMessage => (new MailMessage)
|
||||
->subject(__('users.password_mail.subject'))
|
||||
->greeting(__('users.password_mail.greeting'))
|
||||
->line(__('users.password_mail.intro'))
|
||||
->action(__('users.password_mail.action'), route('password.reset', [
|
||||
'token' => $token,
|
||||
'email' => $notifiable->getEmailForPasswordReset(),
|
||||
]))
|
||||
->line(__('users.password_mail.expires', ['count' => config('auth.passwords.users.expire')]))
|
||||
->line(__('users.password_mail.ignore'))
|
||||
->salutation(config('app.name')));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
<?php
|
||||
|
||||
namespace App\Modules\Users\Infrastructure;
|
||||
|
||||
use App\Modules\Users\Application\Contracts\Clock;
|
||||
use DateTimeImmutable;
|
||||
use Illuminate\Support\Facades\Date;
|
||||
|
||||
class SystemClock implements Clock
|
||||
{
|
||||
public function __construct(private string $timezone) {}
|
||||
|
||||
public function today(): DateTimeImmutable
|
||||
{
|
||||
return Date::now($this->timezone)->startOfDay()->toDateTimeImmutable();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
<?php
|
||||
|
||||
namespace App\Modules\Users\Presentation\Console;
|
||||
|
||||
use App\Modules\Shared\Domain\Exceptions\DomainException;
|
||||
use App\Modules\Users\Application\DTOs\UserAccountData;
|
||||
use App\Modules\Users\Application\UseCases\CreateUserAccount;
|
||||
use App\Modules\Users\Domain\Enums\Role;
|
||||
use Illuminate\Console\Attributes\Description;
|
||||
use Illuminate\Console\Attributes\Signature;
|
||||
use Illuminate\Console\Command;
|
||||
|
||||
#[Signature('users:create-admin {name : Full name} {email : Login email address}')]
|
||||
#[Description('Create an admin user and email them a link for setting their password')]
|
||||
class CreateAdminCommand extends Command
|
||||
{
|
||||
public function handle(CreateUserAccount $createUserAccount): int
|
||||
{
|
||||
try {
|
||||
$createUserAccount->execute(new UserAccountData(
|
||||
name: (string) $this->argument('name'),
|
||||
email: (string) $this->argument('email'),
|
||||
role: Role::Admin,
|
||||
));
|
||||
} catch (DomainException $exception) {
|
||||
$this->components->error($exception->getMessage());
|
||||
|
||||
return self::FAILURE;
|
||||
}
|
||||
|
||||
$this->components->info('Admin created. A link for setting the password was emailed to '.$this->argument('email').'.');
|
||||
|
||||
if (config('mail.default') === 'log') {
|
||||
$this->components->warn('MAIL_MAILER=log: find the link in storage/logs/laravel.log.');
|
||||
}
|
||||
|
||||
return self::SUCCESS;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
<?php
|
||||
|
||||
namespace App\Modules\Users\Presentation\Http\Controllers;
|
||||
|
||||
use Illuminate\Http\RedirectResponse;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
|
||||
class LogoutController
|
||||
{
|
||||
public function __invoke(Request $request): RedirectResponse
|
||||
{
|
||||
Auth::guard('web')->logout();
|
||||
$request->session()->invalidate();
|
||||
$request->session()->regenerateToken();
|
||||
|
||||
return redirect()->route('login')->with('status', __('auth.logged_out'));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
<?php
|
||||
|
||||
namespace App\Modules\Users\Presentation\Http\Middleware;
|
||||
|
||||
use App\Modules\Users\Application\UseCases\CheckLoginAllowed;
|
||||
use Closure;
|
||||
use Illuminate\Http\Request;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Symfony\Component\HttpFoundation\Response;
|
||||
|
||||
/**
|
||||
* Ends the session of a signed-in user who has been deactivated or whose
|
||||
* internship has ended since they signed in.
|
||||
*/
|
||||
class EnsureAccountIsUsable
|
||||
{
|
||||
public function __construct(private CheckLoginAllowed $checkLoginAllowed) {}
|
||||
|
||||
public function handle(Request $request, Closure $next): Response
|
||||
{
|
||||
$userId = Auth::id();
|
||||
|
||||
if ($userId !== null && ! $this->checkLoginAllowed->execute((int) $userId)) {
|
||||
Auth::guard('web')->logout();
|
||||
$request->session()->invalidate();
|
||||
$request->session()->regenerateToken();
|
||||
|
||||
return redirect()->route('login')->with('status', __('auth.account_disabled'));
|
||||
}
|
||||
|
||||
return $next($request);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
<?php
|
||||
|
||||
namespace App\Modules\Users\Presentation\Livewire\Forms;
|
||||
|
||||
use App\Modules\Shared\Domain\Exceptions\DomainException;
|
||||
use App\Modules\Users\Application\DTOs\UserAccountData;
|
||||
use App\Modules\Users\Application\DTOs\UserSummary;
|
||||
use App\Modules\Users\Domain\Enums\Role;
|
||||
use App\Modules\Users\Domain\Exceptions\EmailAlreadyInUse;
|
||||
use App\Modules\Users\Domain\Exceptions\InternRequiresEndDateAndSupervisor;
|
||||
use App\Modules\Users\Domain\Exceptions\InvalidEmailAddress;
|
||||
use App\Modules\Users\Domain\Exceptions\InvalidPersonName;
|
||||
use App\Modules\Users\Domain\Exceptions\InvalidSupervisor;
|
||||
use App\Modules\Users\Domain\Exceptions\LastAdminCannotBeRemoved;
|
||||
use Illuminate\Validation\Rule;
|
||||
use Livewire\Form;
|
||||
|
||||
/**
|
||||
* User details form shared by the create and edit pages. Validates the
|
||||
* shape of the input; business rules come from the Domain and are shown as
|
||||
* field errors by showDomainError().
|
||||
*/
|
||||
class UserForm extends Form
|
||||
{
|
||||
public string $name = '';
|
||||
|
||||
public string $email = '';
|
||||
|
||||
public string $role = Role::Employee->value;
|
||||
|
||||
public bool $active = true;
|
||||
|
||||
public string $employment_ends_on = '';
|
||||
|
||||
public string $supervisor_id = '';
|
||||
|
||||
public function fillFromSummary(UserSummary $user): void
|
||||
{
|
||||
$this->name = $user->name;
|
||||
$this->email = $user->email;
|
||||
$this->role = $user->role->value;
|
||||
$this->active = $user->active;
|
||||
$this->employment_ends_on = $user->employmentEndsOn ?? '';
|
||||
$this->supervisor_id = $user->supervisorId === null ? '' : (string) $user->supervisorId;
|
||||
}
|
||||
|
||||
public function isIntern(): bool
|
||||
{
|
||||
return $this->role === Role::Intern->value;
|
||||
}
|
||||
|
||||
public function toData(): UserAccountData
|
||||
{
|
||||
$this->validate();
|
||||
|
||||
return UserAccountData::fromArray([
|
||||
'name' => $this->name,
|
||||
'email' => $this->email,
|
||||
'role' => $this->role,
|
||||
'active' => $this->active,
|
||||
'employment_ends_on' => $this->isIntern() ? $this->employment_ends_on : null,
|
||||
'supervisor_id' => $this->isIntern() ? $this->supervisor_id : null,
|
||||
]);
|
||||
}
|
||||
|
||||
/**
|
||||
* Shows a broken business rule as an error on the field it concerns.
|
||||
*/
|
||||
public function showDomainError(DomainException $exception): void
|
||||
{
|
||||
[$field, $key] = match ($exception::class) {
|
||||
InvalidPersonName::class => ['name', 'users.errors.invalid_name'],
|
||||
InvalidEmailAddress::class => ['email', 'users.errors.invalid_email'],
|
||||
EmailAlreadyInUse::class => ['email', 'users.errors.email_taken'],
|
||||
InternRequiresEndDateAndSupervisor::class => ['supervisor_id', 'users.errors.supervisor_required'],
|
||||
InvalidSupervisor::class => ['supervisor_id', 'users.errors.invalid_supervisor'],
|
||||
LastAdminCannotBeRemoved::class => ['role', 'users.errors.last_admin'],
|
||||
default => throw $exception,
|
||||
};
|
||||
|
||||
$this->addError($field, __($key));
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, array<int, mixed>>
|
||||
*/
|
||||
protected function rules(): array
|
||||
{
|
||||
return [
|
||||
'name' => ['required', 'string', 'max:255'],
|
||||
'email' => ['required', 'string', 'email:filter', 'max:255'],
|
||||
'role' => ['required', Rule::enum(Role::class)],
|
||||
'active' => ['boolean'],
|
||||
'employment_ends_on' => [Rule::requiredIf($this->isIntern()), 'nullable', 'date_format:Y-m-d'],
|
||||
'supervisor_id' => [Rule::requiredIf($this->isIntern()), 'nullable', 'integer'],
|
||||
];
|
||||
}
|
||||
|
||||
/**
|
||||
* @return array<string, string>
|
||||
*/
|
||||
protected function messages(): array
|
||||
{
|
||||
return [
|
||||
'name.required' => __('users.errors.name_required'),
|
||||
'name.max' => __('users.errors.invalid_name'),
|
||||
'email.required' => __('users.errors.email_required'),
|
||||
'email.email' => __('users.errors.invalid_email'),
|
||||
'email.max' => __('users.errors.invalid_email'),
|
||||
'role.required' => __('users.errors.role_required'),
|
||||
'role.enum' => __('users.errors.role_required'),
|
||||
'employment_ends_on.required' => __('users.errors.end_date_required'),
|
||||
'employment_ends_on.date_format' => __('users.errors.end_date_invalid'),
|
||||
'supervisor_id.required' => __('users.errors.supervisor_required'),
|
||||
'supervisor_id.integer' => __('users.errors.invalid_supervisor'),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
<?php
|
||||
|
||||
use App\Modules\Users\Application\Contracts\PasswordLinkSender;
|
||||
use App\Modules\Users\Domain\ValueObjects\EmailAddress;
|
||||
use Livewire\Component;
|
||||
|
||||
new class extends Component
|
||||
{
|
||||
public string $email = '';
|
||||
|
||||
public bool $linkRequested = false;
|
||||
|
||||
/**
|
||||
* Shows the same message whether or not the address has an account, so
|
||||
* the page cannot be used to find out which addresses are in use.
|
||||
*/
|
||||
public function sendLink(PasswordLinkSender $passwordLinks): void
|
||||
{
|
||||
$this->validate(
|
||||
['email' => ['required', 'string', 'email:filter', 'max:255']],
|
||||
['email.required' => __('auth.email_required'), 'email.email' => __('auth.email_invalid'), 'email.max' => __('auth.email_invalid')],
|
||||
);
|
||||
|
||||
$passwordLinks->sendSetupLink(new EmailAddress($this->email));
|
||||
|
||||
$this->linkRequested = true;
|
||||
}
|
||||
|
||||
public function render(): mixed
|
||||
{
|
||||
return $this->view()->title(__('auth.forgot_title'));
|
||||
}
|
||||
};
|
||||
?>
|
||||
|
||||
<div class="mx-auto max-w-md space-y-6 p-4 sm:p-6 sm:pt-16">
|
||||
<flux:heading size="xl" level="1">{{ __('auth.forgot_title') }}</flux:heading>
|
||||
|
||||
<div role="status" aria-live="polite">
|
||||
@if ($linkRequested)
|
||||
<flux:callout variant="success" icon="envelope" :heading="__('auth.forgot_sent')" />
|
||||
@endif
|
||||
</div>
|
||||
|
||||
<flux:text>{{ __('auth.forgot_intro') }}</flux:text>
|
||||
|
||||
<form wire:submit="sendLink" class="space-y-6" novalidate>
|
||||
<flux:input wire:model="email" type="email" :label="__('auth.email')" autocomplete="username" required />
|
||||
|
||||
<div class="flex flex-wrap items-center justify-between gap-4">
|
||||
<flux:button type="submit" variant="primary">{{ __('auth.forgot_submit') }}</flux:button>
|
||||
<flux:link :href="route('login')" wire:navigate>{{ __('auth.back_to_login') }}</flux:link>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
@@ -0,0 +1,161 @@
|
||||
<?php
|
||||
|
||||
use App\Modules\Shared\Domain\Exceptions\DomainException;
|
||||
use App\Modules\Users\Application\Contracts\UserAccountQueries;
|
||||
use App\Modules\Users\Application\DTOs\UserOption;
|
||||
use App\Modules\Users\Application\UseCases\CreateUserAccount;
|
||||
use App\Modules\Users\Application\UseCases\SendPasswordSetupLink;
|
||||
use App\Modules\Users\Application\UseCases\UpdateUserAccount;
|
||||
use App\Modules\Users\Domain\Enums\Role;
|
||||
use App\Modules\Users\Domain\Exceptions\UserAccountNotFound;
|
||||
use App\Modules\Users\Presentation\Livewire\Forms\UserForm;
|
||||
use Livewire\Attributes\Computed;
|
||||
use Livewire\Attributes\Locked;
|
||||
use Livewire\Component;
|
||||
|
||||
/**
|
||||
* Create page (no route parameter) and edit page (with {user}).
|
||||
*/
|
||||
new class extends Component
|
||||
{
|
||||
#[Locked]
|
||||
public ?int $userId = null;
|
||||
|
||||
public UserForm $form;
|
||||
|
||||
public string $linkStatus = '';
|
||||
|
||||
public function mount(UserAccountQueries $userQueries, ?int $user = null): void
|
||||
{
|
||||
$this->authorize('users.manage');
|
||||
|
||||
if ($user === null) {
|
||||
return;
|
||||
}
|
||||
|
||||
$summary = $userQueries->findSummary($user);
|
||||
|
||||
abort_if($summary === null, 404);
|
||||
|
||||
$this->userId = $summary->id;
|
||||
$this->form->fillFromSummary($summary);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return list<UserOption>
|
||||
*/
|
||||
#[Computed]
|
||||
public function supervisorOptions(): array
|
||||
{
|
||||
return app(UserAccountQueries::class)->supervisorOptions($this->userId);
|
||||
}
|
||||
|
||||
public function save(CreateUserAccount $createUser, UpdateUserAccount $updateUser): void
|
||||
{
|
||||
$this->authorize('users.manage');
|
||||
|
||||
$data = $this->form->toData();
|
||||
|
||||
try {
|
||||
if ($this->userId === null) {
|
||||
$createUser->execute($data);
|
||||
session()->flash('status', __('users.created', ['name' => $data->name]));
|
||||
} else {
|
||||
$updateUser->execute($this->userId, $data);
|
||||
session()->flash('status', __('users.updated', ['name' => $data->name]));
|
||||
}
|
||||
} catch (UserAccountNotFound) {
|
||||
abort(404);
|
||||
} catch (DomainException $exception) {
|
||||
$this->form->showDomainError($exception);
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
$this->redirectRoute('users.index', navigate: true);
|
||||
}
|
||||
|
||||
public function sendPasswordLink(SendPasswordSetupLink $sendLink): void
|
||||
{
|
||||
$this->authorize('users.manage');
|
||||
|
||||
abort_if($this->userId === null, 404);
|
||||
|
||||
try {
|
||||
$sent = $sendLink->execute($this->userId);
|
||||
} catch (UserAccountNotFound) {
|
||||
abort(404);
|
||||
}
|
||||
|
||||
$this->linkStatus = $sent
|
||||
? __('users.link_sent', ['email' => $this->form->email])
|
||||
: __('users.link_throttled');
|
||||
}
|
||||
|
||||
public function render(): mixed
|
||||
{
|
||||
return $this->view()->title(__($this->userId === null ? 'users.create_title' : 'users.edit_title'));
|
||||
}
|
||||
};
|
||||
?>
|
||||
|
||||
<div class="mx-auto max-w-2xl space-y-6 p-4 sm:p-6">
|
||||
<flux:heading size="xl" level="1">
|
||||
{{ __($userId === null ? 'users.create_title' : 'users.edit_title') }}
|
||||
</flux:heading>
|
||||
|
||||
<form wire:submit="save" class="space-y-6" novalidate>
|
||||
<flux:input wire:model="form.name" :label="__('users.fields.name')" autocomplete="off" required />
|
||||
|
||||
<flux:input wire:model="form.email" type="email" :label="__('users.fields.email')" autocomplete="off" required />
|
||||
|
||||
<flux:select wire:model.live="form.role" :label="__('users.fields.role')">
|
||||
@foreach (Role::cases() as $role)
|
||||
<flux:select.option wire:key="role-{{ $role->value }}" :value="$role->value">
|
||||
{{ __('users.roles.'.$role->value) }}
|
||||
</flux:select.option>
|
||||
@endforeach
|
||||
</flux:select>
|
||||
|
||||
@if ($form->isIntern())
|
||||
<flux:input
|
||||
wire:model="form.employment_ends_on"
|
||||
type="date"
|
||||
:label="__('users.fields.employment_ends_on')"
|
||||
:description="__('users.fields.employment_ends_on_description')"
|
||||
required
|
||||
/>
|
||||
|
||||
<flux:select wire:model="form.supervisor_id" :label="__('users.fields.supervisor')" :placeholder="__('users.fields.supervisor_placeholder')">
|
||||
@foreach ($this->supervisorOptions as $option)
|
||||
<flux:select.option wire:key="supervisor-{{ $option->id }}" :value="(string) $option->id">
|
||||
{{ $option->name }}
|
||||
</flux:select.option>
|
||||
@endforeach
|
||||
</flux:select>
|
||||
@endif
|
||||
|
||||
<flux:checkbox
|
||||
wire:model="form.active"
|
||||
:label="__('users.fields.active')"
|
||||
:description="__('users.fields.active_description')"
|
||||
/>
|
||||
|
||||
<div class="flex flex-wrap gap-3">
|
||||
<flux:button type="submit" variant="primary">{{ __('users.save') }}</flux:button>
|
||||
<flux:button :href="route('users.index')" wire:navigate variant="ghost">{{ __('users.cancel') }}</flux:button>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
@if ($userId !== null)
|
||||
<div class="space-y-3 border-t border-zinc-200 pt-6 dark:border-zinc-700">
|
||||
<flux:button wire:click="sendPasswordLink" icon="envelope">{{ __('users.send_link') }}</flux:button>
|
||||
|
||||
<div role="status" aria-live="polite">
|
||||
@if ($linkStatus !== '')
|
||||
<flux:text>{{ $linkStatus }}</flux:text>
|
||||
@endif
|
||||
</div>
|
||||
</div>
|
||||
@endif
|
||||
</div>
|
||||
@@ -0,0 +1,131 @@
|
||||
<?php
|
||||
|
||||
use App\Modules\Users\Application\Contracts\UserAccountQueries;
|
||||
use App\Modules\Users\Application\DTOs\UserSummary;
|
||||
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
|
||||
use Illuminate\Support\Carbon;
|
||||
use Livewire\Attributes\Computed;
|
||||
use Livewire\Attributes\Url;
|
||||
use Livewire\Component;
|
||||
use Livewire\WithPagination;
|
||||
|
||||
new class extends Component
|
||||
{
|
||||
use WithPagination;
|
||||
|
||||
#[Url(as: 'q', except: '')]
|
||||
public string $search = '';
|
||||
|
||||
protected UserAccountQueries $userQueries;
|
||||
|
||||
public function boot(UserAccountQueries $userQueries): void
|
||||
{
|
||||
$this->userQueries = $userQueries;
|
||||
}
|
||||
|
||||
public function mount(): void
|
||||
{
|
||||
$this->authorize('users.manage');
|
||||
}
|
||||
|
||||
public function updatedSearch(): void
|
||||
{
|
||||
$this->resetPage();
|
||||
}
|
||||
|
||||
/**
|
||||
* @return LengthAwarePaginator<int, UserSummary>
|
||||
*/
|
||||
#[Computed]
|
||||
public function users(): LengthAwarePaginator
|
||||
{
|
||||
return $this->userQueries->paginate($this->search);
|
||||
}
|
||||
|
||||
public function statusOf(UserSummary $user): string
|
||||
{
|
||||
if (! $user->active) {
|
||||
return __('users.status.inactive');
|
||||
}
|
||||
|
||||
if ($user->employmentEndsOn === null) {
|
||||
return __('users.status.active');
|
||||
}
|
||||
|
||||
$endsOn = Carbon::parse($user->employmentEndsOn);
|
||||
$today = now(config('app.business_timezone'))->toDateString();
|
||||
|
||||
return __($user->employmentEndsOn < $today ? 'users.status.ended_on' : 'users.status.ends_on', [
|
||||
'date' => $endsOn->format('j.n.Y'),
|
||||
]);
|
||||
}
|
||||
|
||||
public function render(): mixed
|
||||
{
|
||||
return $this->view()->title(__('users.title'));
|
||||
}
|
||||
};
|
||||
?>
|
||||
|
||||
<div class="mx-auto max-w-5xl space-y-6 p-4 sm:p-6">
|
||||
<div class="flex flex-wrap items-center justify-between gap-4">
|
||||
<flux:heading size="xl" level="1">{{ __('users.title') }}</flux:heading>
|
||||
|
||||
<flux:button :href="route('users.create')" wire:navigate variant="primary" icon="plus">
|
||||
{{ __('users.new') }}
|
||||
</flux:button>
|
||||
</div>
|
||||
|
||||
@if (session('status'))
|
||||
<flux:callout variant="success" icon="check-circle" role="status" :heading="session('status')" />
|
||||
@endif
|
||||
|
||||
<flux:input
|
||||
wire:model.live.debounce.300ms="search"
|
||||
type="search"
|
||||
icon="magnifying-glass"
|
||||
:label="__('users.search')"
|
||||
:description="__('users.search_description')"
|
||||
/>
|
||||
|
||||
<flux:text role="status" aria-live="polite" aria-atomic="true">
|
||||
{{ trans_choice('users.result_count', $this->users->total(), ['count' => $this->users->total()]) }}
|
||||
</flux:text>
|
||||
|
||||
@if ($this->users->total() === 0)
|
||||
<flux:text>{{ __('users.empty') }}</flux:text>
|
||||
@else
|
||||
<flux:table :paginate="$this->users">
|
||||
<flux:table.columns>
|
||||
<flux:table.column>{{ __('users.fields.name') }}</flux:table.column>
|
||||
<flux:table.column>{{ __('users.fields.email') }}</flux:table.column>
|
||||
<flux:table.column>{{ __('users.fields.role') }}</flux:table.column>
|
||||
<flux:table.column>{{ __('users.fields.status') }}</flux:table.column>
|
||||
<flux:table.column><span class="sr-only">{{ __('users.edit') }}</span></flux:table.column>
|
||||
</flux:table.columns>
|
||||
|
||||
<flux:table.rows>
|
||||
@foreach ($this->users as $user)
|
||||
<flux:table.row wire:key="user-{{ $user->id }}">
|
||||
<flux:table.cell variant="strong">{{ $user->name }}</flux:table.cell>
|
||||
<flux:table.cell>{{ $user->email }}</flux:table.cell>
|
||||
<flux:table.cell>
|
||||
{{ __('users.roles.'.$user->role->value) }}
|
||||
@if ($user->supervisorName)
|
||||
<span class="block text-xs text-zinc-600 dark:text-zinc-300">
|
||||
{{ __('users.fields.supervisor') }}: {{ $user->supervisorName }}
|
||||
</span>
|
||||
@endif
|
||||
</flux:table.cell>
|
||||
<flux:table.cell>{{ $this->statusOf($user) }}</flux:table.cell>
|
||||
<flux:table.cell align="end">
|
||||
<flux:link :href="route('users.edit', $user->id)" wire:navigate>
|
||||
{{ __('users.edit') }}<span class="sr-only">: {{ $user->name }}</span>
|
||||
</flux:link>
|
||||
</flux:table.cell>
|
||||
</flux:table.row>
|
||||
@endforeach
|
||||
</flux:table.rows>
|
||||
</flux:table>
|
||||
@endif
|
||||
</div>
|
||||
@@ -0,0 +1,108 @@
|
||||
<?php
|
||||
|
||||
use App\Modules\Users\Application\UseCases\CheckLoginAllowed;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Illuminate\Support\Facades\RateLimiter;
|
||||
use Illuminate\Support\Str;
|
||||
use Illuminate\Validation\ValidationException;
|
||||
use Livewire\Component;
|
||||
|
||||
new class extends Component
|
||||
{
|
||||
public const int MAX_ATTEMPTS_PER_MINUTE = 5;
|
||||
|
||||
public string $email = '';
|
||||
|
||||
public string $password = '';
|
||||
|
||||
public bool $remember = false;
|
||||
|
||||
public function login(CheckLoginAllowed $checkLoginAllowed): void
|
||||
{
|
||||
$this->email = trim($this->email);
|
||||
|
||||
$this->validate(
|
||||
['email' => ['required', 'string', 'email'], 'password' => ['required', 'string']],
|
||||
[
|
||||
'email.required' => __('auth.email_required'),
|
||||
'email.email' => __('auth.email_invalid'),
|
||||
'password.required' => __('auth.password_required'),
|
||||
],
|
||||
);
|
||||
|
||||
$email = Str::lower(trim($this->email));
|
||||
$throttleKey = Str::transliterate($email.'|'.request()->ip());
|
||||
|
||||
if (RateLimiter::tooManyAttempts($throttleKey, self::MAX_ATTEMPTS_PER_MINUTE)) {
|
||||
throw ValidationException::withMessages([
|
||||
'email' => __('auth.throttle', ['seconds' => RateLimiter::availableIn($throttleKey)]),
|
||||
]);
|
||||
}
|
||||
|
||||
$accountDisabled = false;
|
||||
|
||||
$signedIn = Auth::attemptWhen(
|
||||
['email' => $email, 'password' => $this->password],
|
||||
function ($user) use ($checkLoginAllowed, &$accountDisabled): bool {
|
||||
$accountDisabled = ! $checkLoginAllowed->execute($user->getAuthIdentifier());
|
||||
|
||||
return ! $accountDisabled;
|
||||
},
|
||||
$this->remember,
|
||||
);
|
||||
|
||||
if (! $signedIn) {
|
||||
RateLimiter::hit($throttleKey);
|
||||
$this->reset('password');
|
||||
|
||||
throw ValidationException::withMessages([
|
||||
'email' => __($accountDisabled ? 'auth.account_disabled' : 'auth.failed'),
|
||||
]);
|
||||
}
|
||||
|
||||
RateLimiter::clear($throttleKey);
|
||||
session()->regenerate();
|
||||
|
||||
$this->redirectIntended(route('home'));
|
||||
}
|
||||
|
||||
public function render(): mixed
|
||||
{
|
||||
return $this->view()->title(__('auth.login_title'));
|
||||
}
|
||||
};
|
||||
?>
|
||||
|
||||
<div class="mx-auto max-w-md space-y-6 p-4 sm:p-6 sm:pt-16">
|
||||
<flux:heading size="xl" level="1">{{ __('auth.login_title') }}</flux:heading>
|
||||
|
||||
@if (session('status'))
|
||||
<flux:callout variant="success" icon="information-circle" role="status" :heading="session('status')" />
|
||||
@endif
|
||||
|
||||
<form wire:submit="login" class="space-y-6" novalidate>
|
||||
<flux:input
|
||||
wire:model="email"
|
||||
type="email"
|
||||
:label="__('auth.email')"
|
||||
autocomplete="username"
|
||||
required
|
||||
/>
|
||||
|
||||
<flux:input
|
||||
wire:model="password"
|
||||
type="password"
|
||||
:label="__('auth.password_label')"
|
||||
autocomplete="current-password"
|
||||
viewable
|
||||
required
|
||||
/>
|
||||
|
||||
<flux:checkbox wire:model="remember" :label="__('auth.remember')" />
|
||||
|
||||
<div class="flex flex-wrap items-center justify-between gap-4">
|
||||
<flux:button type="submit" variant="primary">{{ __('auth.login') }}</flux:button>
|
||||
<flux:link :href="route('password.request')" wire:navigate>{{ __('auth.forgot_password') }}</flux:link>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
@@ -0,0 +1,105 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Auth\Events\PasswordReset;
|
||||
use Illuminate\Support\Facades\Password;
|
||||
use Illuminate\Support\Str;
|
||||
use Illuminate\Validation\Rules\Password as PasswordRule;
|
||||
use Livewire\Attributes\Locked;
|
||||
use Livewire\Component;
|
||||
|
||||
new class extends Component
|
||||
{
|
||||
#[Locked]
|
||||
public string $token = '';
|
||||
|
||||
public string $email = '';
|
||||
|
||||
public string $password = '';
|
||||
|
||||
public string $password_confirmation = '';
|
||||
|
||||
public function mount(string $token): void
|
||||
{
|
||||
$this->token = $token;
|
||||
$this->email = (string) request()->query('email', '');
|
||||
}
|
||||
|
||||
public function resetPassword(): void
|
||||
{
|
||||
$this->validate(
|
||||
[
|
||||
'email' => ['required', 'string', 'email'],
|
||||
'password' => ['required', 'string', 'confirmed', PasswordRule::defaults()],
|
||||
],
|
||||
[
|
||||
'email.required' => __('auth.email_required'),
|
||||
'email.email' => __('auth.email_invalid'),
|
||||
'password.required' => __('auth.password_required'),
|
||||
'password.confirmed' => __('auth.password_mismatch'),
|
||||
'password.min' => __('auth.password_too_short', ['min' => 12]),
|
||||
],
|
||||
);
|
||||
|
||||
$status = Password::reset(
|
||||
[
|
||||
'email' => Str::lower(trim($this->email)),
|
||||
'password' => $this->password,
|
||||
'password_confirmation' => $this->password_confirmation,
|
||||
'token' => $this->token,
|
||||
],
|
||||
function ($user, string $password): void {
|
||||
$user->forceFill(['password' => $password, 'remember_token' => Str::random(60)])->save();
|
||||
|
||||
event(new PasswordReset($user));
|
||||
},
|
||||
);
|
||||
|
||||
if ($status !== Password::PASSWORD_RESET) {
|
||||
$this->reset('password', 'password_confirmation');
|
||||
$this->addError('email', __($status));
|
||||
|
||||
return;
|
||||
}
|
||||
|
||||
session()->flash('status', __($status));
|
||||
|
||||
$this->redirectRoute('login');
|
||||
}
|
||||
|
||||
public function render(): mixed
|
||||
{
|
||||
return $this->view()->title(__('auth.reset_title'));
|
||||
}
|
||||
};
|
||||
?>
|
||||
|
||||
<div class="mx-auto max-w-md space-y-6 p-4 sm:p-6 sm:pt-16">
|
||||
<flux:heading size="xl" level="1">{{ __('auth.reset_title') }}</flux:heading>
|
||||
|
||||
<flux:text>{{ __('auth.reset_intro') }}</flux:text>
|
||||
|
||||
<form wire:submit="resetPassword" class="space-y-6" novalidate>
|
||||
<flux:input wire:model="email" type="email" :label="__('auth.email')" autocomplete="username" required />
|
||||
|
||||
<flux:input
|
||||
wire:model="password"
|
||||
type="password"
|
||||
:label="__('auth.new_password')"
|
||||
:description="__('auth.password_rules')"
|
||||
autocomplete="new-password"
|
||||
viewable
|
||||
required
|
||||
/>
|
||||
|
||||
<flux:input
|
||||
wire:model="password_confirmation"
|
||||
type="password"
|
||||
:label="__('auth.confirm_password')"
|
||||
autocomplete="new-password"
|
||||
viewable
|
||||
required
|
||||
/>
|
||||
|
||||
<flux:button type="submit" variant="primary">{{ __('auth.reset_submit') }}</flux:button>
|
||||
</form>
|
||||
</div>
|
||||
@@ -0,0 +1,23 @@
|
||||
<?php
|
||||
|
||||
use App\Modules\Users\Presentation\Http\Controllers\LogoutController;
|
||||
use Illuminate\Support\Facades\Route;
|
||||
|
||||
Route::middleware(['web', 'guest'])->group(function () {
|
||||
Route::livewire('/login', 'users::login')->name('login');
|
||||
Route::livewire('/forgot-password', 'users::forgot-password')->name('password.request');
|
||||
Route::livewire('/reset-password/{token}', 'users::reset-password')->name('password.reset');
|
||||
});
|
||||
|
||||
Route::middleware(['web', 'auth'])->group(function () {
|
||||
Route::post('/logout', LogoutController::class)->name('logout');
|
||||
|
||||
Route::middleware('can:users.manage')
|
||||
->prefix('users')
|
||||
->name('users.')
|
||||
->group(function () {
|
||||
Route::livewire('/', 'users::index')->name('index');
|
||||
Route::livewire('/create', 'users::form')->name('create');
|
||||
Route::livewire('/{user}/edit', 'users::form')->whereNumber('user')->name('edit');
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user