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:
@@ -1,5 +1,14 @@
|
||||
<?php
|
||||
|
||||
use App\Models\User;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
|
||||
uses(RefreshDatabase::class);
|
||||
|
||||
beforeEach(function () {
|
||||
$this->actingAs(User::factory()->admin()->create());
|
||||
});
|
||||
|
||||
it('has no accessibility issues on the home page', function (string $device, string $colorScheme) {
|
||||
$page = visit(route('home'));
|
||||
|
||||
@@ -21,8 +30,15 @@ it('can be operated with the keyboard alone', function () {
|
||||
|
||||
$page->keys('html > body', 'Tab')
|
||||
->assertScript('document.activeElement.textContent.trim()', 'Siirry pääsisältöön')
|
||||
->keys('a[href="#main-content"]', 'Tab')
|
||||
->keys('a[href="#main-content"]', 'Enter')
|
||||
->keys('#main-content', 'Tab')
|
||||
->assertScript('document.activeElement.textContent.trim()', 'Lisää klikkaus')
|
||||
->keys('#main-content button', 'Enter')
|
||||
->assertSeeIn('[role="status"]', 'Klikattu 1 kertaa');
|
||||
});
|
||||
|
||||
it('reaches the main menu with the keyboard', function () {
|
||||
visit(route('home'))
|
||||
->keys('html > body', ['Tab', 'Tab', 'Tab'])
|
||||
->assertScript('document.activeElement.closest("nav")?.getAttribute("aria-label")', 'Päävalikko');
|
||||
});
|
||||
|
||||
@@ -46,7 +46,8 @@ it('creates a customer with the keyboard alone', function () {
|
||||
visit(route('customers.create'))
|
||||
->keys('html > body', 'Tab')
|
||||
->assertScript('document.activeElement.textContent.trim()', 'Siirry pääsisältöön')
|
||||
->keys('a[href="#main-content"]', 'Tab')
|
||||
->keys('a[href="#main-content"]', 'Enter')
|
||||
->keys('#main-content', 'Tab')
|
||||
->assertScript('document.activeElement.getAttribute("wire:model")', 'form.name')
|
||||
->type('[wire\\:model="form.name"]', 'Mainos Oy')
|
||||
->keys('[wire\\:model="form.name"]', 'Enter')
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
<?php
|
||||
|
||||
use App\Models\User;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Pest\Browser\Api\AwaitableWebpage;
|
||||
use Pest\Browser\Api\PendingAwaitablePage;
|
||||
|
||||
uses(RefreshDatabase::class);
|
||||
|
||||
$devicesAndSchemes = [
|
||||
'desktop, light' => ['desktop', 'light'],
|
||||
'desktop, dark' => ['desktop', 'dark'],
|
||||
'mobile, light' => ['mobile', 'light'],
|
||||
'mobile, dark' => ['mobile', 'dark'],
|
||||
];
|
||||
|
||||
/**
|
||||
* @param PendingAwaitablePage|AwaitableWebpage $page
|
||||
*/
|
||||
function onDeviceAndScheme(mixed $page, string $device, string $colorScheme): mixed
|
||||
{
|
||||
$page = $device === 'mobile' ? $page->on()->mobile() : $page->on()->desktop();
|
||||
|
||||
return $colorScheme === 'dark' ? $page->inDarkMode() : $page->inLightMode();
|
||||
}
|
||||
|
||||
it('has no accessibility issues on the guest pages', function (string $routeName, string $device, string $colorScheme) {
|
||||
$url = $routeName === 'password.reset'
|
||||
? route($routeName, ['token' => 'token', 'email' => '[email protected]'])
|
||||
: route($routeName);
|
||||
|
||||
onDeviceAndScheme(visit($url), $device, $colorScheme)
|
||||
->assertNoJavaScriptErrors()
|
||||
->assertNoAccessibilityIssues(level: 2);
|
||||
})->with([
|
||||
'login' => 'login',
|
||||
'forgot password' => 'password.request',
|
||||
'reset password' => 'password.reset',
|
||||
])->with($devicesAndSchemes);
|
||||
|
||||
it('has no accessibility issues on the user admin pages', function (string $page, string $device, string $colorScheme) {
|
||||
$admin = User::factory()->admin()->create();
|
||||
$intern = User::factory()->intern('2027-05-31')->create();
|
||||
$this->actingAs($admin);
|
||||
|
||||
$url = match ($page) {
|
||||
'list' => route('users.index'),
|
||||
'create' => route('users.create'),
|
||||
'edit intern' => route('users.edit', $intern->id),
|
||||
};
|
||||
|
||||
onDeviceAndScheme(visit($url), $device, $colorScheme)
|
||||
->assertNoJavaScriptErrors()
|
||||
->assertNoAccessibilityIssues(level: 2);
|
||||
})->with(['list', 'create', 'edit intern'])->with($devicesAndSchemes);
|
||||
|
||||
it('shows a login error without accessibility issues', function (string $colorScheme) {
|
||||
$page = onDeviceAndScheme(visit(route('login')), 'desktop', $colorScheme);
|
||||
|
||||
$page->fill('[wire\\:model="email"]', '[email protected]')
|
||||
->fill('[wire\\:model="password"]', 'väärä-salasana')
|
||||
->press('Kirjaudu')
|
||||
->assertSee('Sähköposti tai salasana on väärin.')
|
||||
->assertNoAccessibilityIssues(level: 2);
|
||||
})->with(['light', 'dark']);
|
||||
|
||||
it('logs in with the keyboard alone', function () {
|
||||
User::factory()->create(['email' => '[email protected]']);
|
||||
|
||||
visit(route('login'))
|
||||
->keys('html > body', 'Tab')
|
||||
->keys('a[href="#main-content"]', 'Enter')
|
||||
->keys('#main-content', 'Tab')
|
||||
->assertScript('document.activeElement.getAttribute("wire:model")', 'email')
|
||||
->type('[wire\\:model="email"]', '[email protected]')
|
||||
->type('[wire\\:model="password"]', 'password')
|
||||
->keys('[wire\\:model="password"]', 'Enter')
|
||||
->assertPathIs('/')
|
||||
->assertSee('Kirjaudu ulos');
|
||||
});
|
||||
@@ -0,0 +1,16 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Fakes;
|
||||
|
||||
use App\Modules\Users\Application\Contracts\Clock;
|
||||
use DateTimeImmutable;
|
||||
|
||||
class FakeClock implements Clock
|
||||
{
|
||||
public function __construct(public DateTimeImmutable $today) {}
|
||||
|
||||
public function today(): DateTimeImmutable
|
||||
{
|
||||
return $this->today;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Fakes;
|
||||
|
||||
use App\Modules\Users\Application\Contracts\PasswordLinkSender;
|
||||
use App\Modules\Users\Domain\ValueObjects\EmailAddress;
|
||||
|
||||
class FakePasswordLinkSender implements PasswordLinkSender
|
||||
{
|
||||
/**
|
||||
* @var list<string>
|
||||
*/
|
||||
public array $sentTo = [];
|
||||
|
||||
public function sendSetupLink(EmailAddress $email): bool
|
||||
{
|
||||
$this->sentTo[] = $email->value;
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
<?php
|
||||
|
||||
namespace Tests\Fakes;
|
||||
|
||||
use App\Modules\Users\Domain\Contracts\UserAccountRepository;
|
||||
use App\Modules\Users\Domain\Entities\UserAccount;
|
||||
use App\Modules\Users\Domain\ValueObjects\EmailAddress;
|
||||
|
||||
class InMemoryUserAccountRepository implements UserAccountRepository
|
||||
{
|
||||
/**
|
||||
* @var array<int, UserAccount>
|
||||
*/
|
||||
public array $users = [];
|
||||
|
||||
private int $nextId = 1;
|
||||
|
||||
public function findById(int $id): ?UserAccount
|
||||
{
|
||||
return isset($this->users[$id]) ? clone $this->users[$id] : null;
|
||||
}
|
||||
|
||||
public function save(UserAccount $user): UserAccount
|
||||
{
|
||||
$id = $user->id() ?? $this->nextId++;
|
||||
|
||||
$this->users[$id] = UserAccount::reconstitute(
|
||||
$id,
|
||||
$user->name(),
|
||||
$user->email(),
|
||||
$user->role(),
|
||||
$user->isActive(),
|
||||
$user->employmentEndsOn(),
|
||||
$user->supervisorId(),
|
||||
);
|
||||
|
||||
return clone $this->users[$id];
|
||||
}
|
||||
|
||||
public function isEmailTaken(EmailAddress $email, ?int $exceptUserId = null): bool
|
||||
{
|
||||
foreach ($this->users as $id => $user) {
|
||||
if ($id !== $exceptUserId && $user->email()->equals($email)) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
public function countActiveAdmins(?int $exceptUserId = null): int
|
||||
{
|
||||
return count(array_filter(
|
||||
$this->users,
|
||||
fn (UserAccount $user, int $id): bool => $id !== $exceptUserId && $user->isActiveAdmin(),
|
||||
ARRAY_FILTER_USE_BOTH,
|
||||
));
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,5 @@
|
||||
<?php
|
||||
|
||||
test('the application returns a successful response', function () {
|
||||
$response = $this->get('/');
|
||||
|
||||
$response->assertStatus(200);
|
||||
test('the application sends guests to the login page', function () {
|
||||
$this->get('/')->assertRedirect(route('login'));
|
||||
});
|
||||
|
||||
@@ -1,13 +1,23 @@
|
||||
<?php
|
||||
|
||||
use App\Models\User;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Livewire\Livewire;
|
||||
|
||||
it('renders the home page', function () {
|
||||
uses(RefreshDatabase::class);
|
||||
|
||||
beforeEach(function () {
|
||||
$this->actingAs(User::factory()->create(['name' => 'Eero Esimerkki']));
|
||||
});
|
||||
|
||||
it('renders the home page with the main menu', function () {
|
||||
$this->get(route('home'))
|
||||
->assertOk()
|
||||
->assertSee('Toiminnanohjaus')
|
||||
->assertSee('Siirry pääsisältöön')
|
||||
->assertSee('id="main-content"', false);
|
||||
->assertSee('id="main-content"', false)
|
||||
->assertSee('aria-label="Päävalikko"', false)
|
||||
->assertSee('Kirjautuneena: Eero Esimerkki');
|
||||
});
|
||||
|
||||
it('increments the click count', function () {
|
||||
|
||||
@@ -1,10 +0,0 @@
|
||||
<?php
|
||||
|
||||
use Illuminate\Support\Facades\Route;
|
||||
|
||||
it('does not offer the local test login outside the local environment', function () {
|
||||
expect(app()->environment())->not->toBe('local')
|
||||
->and(Route::has('login'))->toBeFalse();
|
||||
|
||||
$this->get('/dev/login')->assertNotFound();
|
||||
});
|
||||
@@ -0,0 +1,30 @@
|
||||
<?php
|
||||
|
||||
use App\Models\User;
|
||||
use App\Modules\Customers\Infrastructure\Persistence\Eloquent\CustomerModel;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Livewire\Features\SupportLockedProperties\CannotUpdateLockedPropertyException;
|
||||
use Livewire\Livewire;
|
||||
|
||||
uses(RefreshDatabase::class);
|
||||
|
||||
it('lets every role except subcontractors use the customer pages', function (string $state, int $status) {
|
||||
$user = User::factory()->{$state}()->create();
|
||||
|
||||
$this->actingAs($user)->get(route('customers.index'))->assertStatus($status);
|
||||
$this->actingAs($user)->get(route('customers.create'))->assertStatus($status);
|
||||
})->with([
|
||||
'admin' => ['admin', 200],
|
||||
'management' => ['management', 200],
|
||||
'employee' => ['employee', 200],
|
||||
'intern' => ['intern', 200],
|
||||
'subcontractor' => ['subcontractor', 403],
|
||||
]);
|
||||
|
||||
it('does not let the customer id be changed in the browser', function () {
|
||||
$customer = CustomerModel::factory()->create();
|
||||
|
||||
Livewire::actingAs(User::factory()->create())
|
||||
->test('customers::form')
|
||||
->set('customerId', $customer->id);
|
||||
})->throws(CannotUpdateLockedPropertyException::class);
|
||||
@@ -0,0 +1,32 @@
|
||||
<?php
|
||||
|
||||
use App\Models\User;
|
||||
use App\Modules\Users\Domain\Enums\Role;
|
||||
use Illuminate\Auth\Notifications\ResetPassword;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\Notification;
|
||||
|
||||
uses(RefreshDatabase::class);
|
||||
|
||||
it('creates an admin and emails a set-password link', function () {
|
||||
Notification::fake();
|
||||
|
||||
$this->artisan('users:create-admin', ['name' => 'Anna Admin', 'email' => '[email protected]'])
|
||||
->assertSuccessful();
|
||||
|
||||
$admin = User::query()->sole();
|
||||
|
||||
expect($admin->role)->toBe(Role::Admin)
|
||||
->and($admin->email)->toBe('[email protected]');
|
||||
|
||||
Notification::assertSentTo($admin, ResetPassword::class);
|
||||
});
|
||||
|
||||
it('fails for an email address that is in use', function () {
|
||||
User::factory()->create(['email' => '[email protected]']);
|
||||
|
||||
$this->artisan('users:create-admin', ['name' => 'Anna Admin', 'email' => '[email protected]'])
|
||||
->assertFailed();
|
||||
|
||||
expect(User::query()->count())->toBe(1);
|
||||
});
|
||||
@@ -0,0 +1,118 @@
|
||||
<?php
|
||||
|
||||
use App\Models\User;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\RateLimiter;
|
||||
use Livewire\Livewire;
|
||||
|
||||
uses(RefreshDatabase::class);
|
||||
|
||||
beforeEach(function () {
|
||||
$this->travelTo(now('Europe/Helsinki')->setDate(2027, 5, 31)->setTime(12, 0));
|
||||
});
|
||||
|
||||
it('sends guests to the login page and back where they were going', function () {
|
||||
$user = User::factory()->create(['email' => '[email protected]']);
|
||||
|
||||
$this->get(route('customers.index'))->assertRedirect(route('login'));
|
||||
|
||||
$this->get(route('login'))->assertOk()->assertSee('Kirjaudu sisään');
|
||||
|
||||
Livewire::test('users::login')
|
||||
->set('email', ' [email protected] ')
|
||||
->set('password', 'password')
|
||||
->call('login')
|
||||
->assertHasNoErrors()
|
||||
->assertRedirect(route('customers.index'));
|
||||
|
||||
$this->assertAuthenticatedAs($user);
|
||||
});
|
||||
|
||||
it('rejects a wrong password', function () {
|
||||
User::factory()->create(['email' => '[email protected]']);
|
||||
|
||||
Livewire::test('users::login')
|
||||
->set('email', '[email protected]')
|
||||
->set('password', 'väärä')
|
||||
->call('login')
|
||||
->assertHasErrors(['email'])
|
||||
->assertSee('Sähköposti tai salasana on väärin.')
|
||||
->assertSet('password', '');
|
||||
|
||||
$this->assertGuest();
|
||||
});
|
||||
|
||||
it('does not let a deactivated user or an intern past the last day log in', function (string $state) {
|
||||
$factory = User::factory();
|
||||
$user = match ($state) {
|
||||
'inactive' => $factory->inactive()->create(),
|
||||
'intern ended yesterday' => $factory->intern('2027-05-30')->create(),
|
||||
};
|
||||
|
||||
Livewire::test('users::login')
|
||||
->set('email', $user->email)
|
||||
->set('password', 'password')
|
||||
->call('login')
|
||||
->assertHasErrors(['email'])
|
||||
->assertSee('Käyttöoikeutesi on päättynyt.');
|
||||
|
||||
$this->assertGuest();
|
||||
})->with(['inactive', 'intern ended yesterday']);
|
||||
|
||||
it('lets an intern log in on the last day', function () {
|
||||
$intern = User::factory()->intern('2027-05-31')->create();
|
||||
|
||||
Livewire::test('users::login')
|
||||
->set('email', $intern->email)
|
||||
->set('password', 'password')
|
||||
->call('login')
|
||||
->assertHasNoErrors();
|
||||
|
||||
$this->assertAuthenticatedAs($intern);
|
||||
});
|
||||
|
||||
it('blocks login after five failed attempts', function () {
|
||||
RateLimiter::clear('[email protected]|127.0.0.1');
|
||||
User::factory()->create(['email' => '[email protected]']);
|
||||
|
||||
$login = Livewire::test('users::login')->set('email', '[email protected]');
|
||||
|
||||
foreach (range(1, 5) as $attempt) {
|
||||
$login->set('password', 'väärä')->call('login');
|
||||
}
|
||||
|
||||
$login->set('password', 'password')
|
||||
->call('login')
|
||||
->assertHasErrors(['email'])
|
||||
->assertSee('Liian monta kirjautumisyritystä.');
|
||||
|
||||
$this->assertGuest();
|
||||
});
|
||||
|
||||
it('ends the session of a user who is deactivated while signed in', function () {
|
||||
$user = User::factory()->create();
|
||||
|
||||
$this->actingAs($user)->get(route('customers.index'))->assertOk();
|
||||
|
||||
$user->update(['is_active' => false]);
|
||||
|
||||
$this->get(route('customers.index'))
|
||||
->assertRedirect(route('login'))
|
||||
->assertSessionHas('status', 'Käyttöoikeutesi on päättynyt. Ota yhteyttä pääkäyttäjään.');
|
||||
|
||||
$this->assertGuest();
|
||||
});
|
||||
|
||||
it('logs out', function () {
|
||||
$this->actingAs(User::factory()->create())
|
||||
->post(route('logout'))
|
||||
->assertRedirect(route('login'));
|
||||
|
||||
$this->assertGuest();
|
||||
});
|
||||
|
||||
it('sends signed-in users away from the login page', function () {
|
||||
$this->actingAs(User::factory()->create())
|
||||
->get(route('login'))
|
||||
->assertRedirect(route('home'));
|
||||
});
|
||||
@@ -0,0 +1,91 @@
|
||||
<?php
|
||||
|
||||
use App\Models\User;
|
||||
use Illuminate\Auth\Notifications\ResetPassword;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\Hash;
|
||||
use Illuminate\Support\Facades\Notification;
|
||||
use Illuminate\Support\Facades\Password;
|
||||
use Livewire\Livewire;
|
||||
|
||||
uses(RefreshDatabase::class);
|
||||
|
||||
it('emails a Finnish set-password link to a known address', function () {
|
||||
Notification::fake();
|
||||
$user = User::factory()->create(['email' => '[email protected]']);
|
||||
|
||||
$this->get(route('password.request'))->assertOk();
|
||||
|
||||
Livewire::test('users::forgot-password')
|
||||
->set('email', '[email protected]')
|
||||
->call('sendLink')
|
||||
->assertHasNoErrors()
|
||||
->assertSee('Jos osoitteella on käyttäjätunnus');
|
||||
|
||||
Notification::assertSentTo($user, ResetPassword::class, function (ResetPassword $notification) use ($user) {
|
||||
$mail = $notification->toMail($user);
|
||||
|
||||
return $mail->subject === 'Aseta salasana'
|
||||
&& str_contains($mail->actionUrl, '/reset-password/'.$notification->token);
|
||||
});
|
||||
});
|
||||
|
||||
it('renders the whole set-password email in Finnish', function () {
|
||||
$user = User::factory()->create();
|
||||
|
||||
$html = (string) (new ResetPassword('token'))->toMail($user)->render();
|
||||
|
||||
expect($html)->toContain('Aseta salasana')
|
||||
->toContain('kopioi alla oleva osoite')
|
||||
->toContain('Kaikki oikeudet pidätetään.')
|
||||
->not->toContain('All rights reserved');
|
||||
});
|
||||
|
||||
it('shows the same message for an unknown address', function () {
|
||||
Notification::fake();
|
||||
|
||||
Livewire::test('users::forgot-password')
|
||||
->set('email', '[email protected]')
|
||||
->call('sendLink')
|
||||
->assertHasNoErrors()
|
||||
->assertSee('Jos osoitteella on käyttäjätunnus');
|
||||
|
||||
Notification::assertNothingSent();
|
||||
});
|
||||
|
||||
it('sets a new password with a valid link', function () {
|
||||
$user = User::factory()->create(['email' => '[email protected]']);
|
||||
$token = Password::createToken($user);
|
||||
|
||||
$this->get(route('password.reset', ['token' => $token, 'email' => $user->email]))
|
||||
->assertOk()
|
||||
->assertSee('Aseta salasana');
|
||||
|
||||
Livewire::test('users::reset-password', ['token' => $token])
|
||||
->set('email', '[email protected]')
|
||||
->set('password', 'uusi-salasana-123')
|
||||
->set('password_confirmation', 'uusi-salasana-123')
|
||||
->call('resetPassword')
|
||||
->assertHasNoErrors()
|
||||
->assertRedirect(route('login'));
|
||||
|
||||
expect(Hash::check('uusi-salasana-123', $user->fresh()->password))->toBeTrue();
|
||||
});
|
||||
|
||||
it('rejects a short password and an invalid link', function () {
|
||||
$user = User::factory()->create(['email' => '[email protected]']);
|
||||
|
||||
Livewire::test('users::reset-password', ['token' => 'väärä'])
|
||||
->set('email', '[email protected]')
|
||||
->set('password', 'lyhyt')
|
||||
->set('password_confirmation', 'lyhyt')
|
||||
->call('resetPassword')
|
||||
->assertHasErrors(['password'])
|
||||
->set('password', 'uusi-salasana-123')
|
||||
->set('password_confirmation', 'uusi-salasana-123')
|
||||
->call('resetPassword')
|
||||
->assertHasErrors(['email'])
|
||||
->assertSee('Linkki on vanhentunut tai virheellinen.');
|
||||
|
||||
expect(Hash::check('password', $user->fresh()->password))->toBeTrue();
|
||||
});
|
||||
@@ -0,0 +1,143 @@
|
||||
<?php
|
||||
|
||||
use App\Models\User;
|
||||
use App\Modules\Users\Domain\Enums\Role;
|
||||
use Illuminate\Auth\Notifications\ResetPassword;
|
||||
use Illuminate\Foundation\Testing\RefreshDatabase;
|
||||
use Illuminate\Support\Facades\Notification;
|
||||
use Livewire\Features\SupportLockedProperties\CannotUpdateLockedPropertyException;
|
||||
use Livewire\Livewire;
|
||||
|
||||
uses(RefreshDatabase::class);
|
||||
|
||||
beforeEach(function () {
|
||||
Notification::fake();
|
||||
$this->admin = User::factory()->admin()->create(['name' => 'Anna Admin']);
|
||||
});
|
||||
|
||||
it('only lets admins manage users', function (string $state, int $status) {
|
||||
$user = User::factory()->{$state}()->create();
|
||||
|
||||
$this->actingAs($user)->get(route('users.index'))->assertStatus($status);
|
||||
$this->actingAs($user)->get(route('users.create'))->assertStatus($status);
|
||||
})->with([
|
||||
'admin' => ['admin', 200],
|
||||
'management' => ['management', 403],
|
||||
'employee' => ['employee', 403],
|
||||
'intern' => ['intern', 403],
|
||||
'subcontractor' => ['subcontractor', 403],
|
||||
]);
|
||||
|
||||
it('lists users with their role and status', function () {
|
||||
$supervisor = User::factory()->create(['name' => 'Eero Työntekijä']);
|
||||
User::factory()->intern('2027-05-31', $supervisor)->create(['name' => 'Ida Harjoittelija']);
|
||||
User::factory()->inactive()->create(['name' => 'Pekka Poissa']);
|
||||
|
||||
$this->actingAs($this->admin)->get(route('users.index'))
|
||||
->assertOk()
|
||||
->assertSee('Ida Harjoittelija')
|
||||
->assertSee('Harjoittelija')
|
||||
->assertSee('Vastuuhenkilö: Eero Työntekijä')
|
||||
->assertSee('Päättyy 31.5.2027')
|
||||
->assertSee('Ei käytössä');
|
||||
});
|
||||
|
||||
it('creates an intern and emails a set-password link', function () {
|
||||
$supervisor = User::factory()->create();
|
||||
|
||||
Livewire::actingAs($this->admin)
|
||||
->test('users::form')
|
||||
->set('form.name', 'Ida Harjoittelija')
|
||||
->set('form.email', '[email protected]')
|
||||
->set('form.role', 'intern')
|
||||
->set('form.employment_ends_on', '2027-05-31')
|
||||
->set('form.supervisor_id', (string) $supervisor->id)
|
||||
->call('save')
|
||||
->assertHasNoErrors()
|
||||
->assertRedirect(route('users.index'));
|
||||
|
||||
$intern = User::query()->where('email', '[email protected]')->sole();
|
||||
|
||||
expect($intern->role)->toBe(Role::Intern)
|
||||
->and($intern->employment_ends_on?->toDateString())->toBe('2027-05-31')
|
||||
->and($intern->supervisor_id)->toBe($supervisor->id);
|
||||
|
||||
Notification::assertSentTo($intern, ResetPassword::class);
|
||||
});
|
||||
|
||||
it('requires an end date and a supervisor for an intern', function () {
|
||||
Livewire::actingAs($this->admin)
|
||||
->test('users::form')
|
||||
->set('form.name', 'Ida')
|
||||
->set('form.email', '[email protected]')
|
||||
->set('form.role', 'intern')
|
||||
->call('save')
|
||||
->assertHasErrors(['form.employment_ends_on', 'form.supervisor_id'])
|
||||
->assertSee('Anna harjoittelun viimeinen päivä.');
|
||||
});
|
||||
|
||||
it('rejects an admin as an intern supervisor', function () {
|
||||
Livewire::actingAs($this->admin)
|
||||
->test('users::form')
|
||||
->set('form.name', 'Ida')
|
||||
->set('form.email', '[email protected]')
|
||||
->set('form.role', 'intern')
|
||||
->set('form.employment_ends_on', '2027-05-31')
|
||||
->set('form.supervisor_id', (string) $this->admin->id)
|
||||
->call('save')
|
||||
->assertHasErrors(['form.supervisor_id']);
|
||||
});
|
||||
|
||||
it('rejects an email address that is in use', function () {
|
||||
Livewire::actingAs($this->admin)
|
||||
->test('users::form')
|
||||
->set('form.name', 'Toinen Anna')
|
||||
->set('form.email', strtoupper($this->admin->email))
|
||||
->call('save')
|
||||
->assertHasErrors(['form.email'])
|
||||
->assertSee('Tällä sähköpostiosoitteella on jo käyttäjä.');
|
||||
});
|
||||
|
||||
it('deactivates a user', function () {
|
||||
$user = User::factory()->create();
|
||||
|
||||
Livewire::actingAs($this->admin)
|
||||
->test('users::form', ['user' => $user->id])
|
||||
->set('form.active', false)
|
||||
->call('save')
|
||||
->assertHasNoErrors();
|
||||
|
||||
expect($user->fresh()->is_active)->toBeFalse();
|
||||
});
|
||||
|
||||
it('does not let the last admin deactivate themselves', function () {
|
||||
Livewire::actingAs($this->admin)
|
||||
->test('users::form', ['user' => $this->admin->id])
|
||||
->set('form.active', false)
|
||||
->call('save')
|
||||
->assertHasErrors(['form.role'])
|
||||
->assertSee('Viimeistä aktiivista pääkäyttäjää ei voi poistaa käytöstä');
|
||||
|
||||
expect($this->admin->fresh()->is_active)->toBeTrue();
|
||||
});
|
||||
|
||||
it('sends a set-password link from the edit page', function () {
|
||||
$user = User::factory()->create(['email' => '[email protected]']);
|
||||
|
||||
Livewire::actingAs($this->admin)
|
||||
->test('users::form', ['user' => $user->id])
|
||||
->call('sendPasswordLink')
|
||||
->assertSee('Lähetimme linkin salasanan asettamiseen osoitteeseen [email protected].');
|
||||
|
||||
Notification::assertSentTo($user, ResetPassword::class);
|
||||
});
|
||||
|
||||
it('does not let the user id be changed in the browser', function () {
|
||||
Livewire::actingAs($this->admin)
|
||||
->test('users::form')
|
||||
->set('userId', 1);
|
||||
})->throws(CannotUpdateLockedPropertyException::class);
|
||||
|
||||
it('returns 404 for an unknown user', function () {
|
||||
$this->actingAs($this->admin)->get(route('users.edit', 999))->assertNotFound();
|
||||
});
|
||||
@@ -42,9 +42,11 @@ foreach ($modules as $module) {
|
||||
$root.'\\Presentation',
|
||||
]);
|
||||
|
||||
// Service providers are the module's composition root: they may register its commands and middleware.
|
||||
arch("{$module}: infrastructure does not depend on presentation")
|
||||
->expect($root.'\\Infrastructure')
|
||||
->not->toUse($root.'\\Presentation');
|
||||
->not->toUse($root.'\\Presentation')
|
||||
->ignoring($root.'\\Infrastructure\\Providers');
|
||||
|
||||
$otherModules = array_values(array_diff($modules, [$module]));
|
||||
|
||||
|
||||
@@ -0,0 +1,111 @@
|
||||
<?php
|
||||
|
||||
use App\Modules\Users\Application\DTOs\UserAccountData;
|
||||
use App\Modules\Users\Application\UseCases\CheckLoginAllowed;
|
||||
use App\Modules\Users\Application\UseCases\CreateUserAccount;
|
||||
use App\Modules\Users\Application\UseCases\SendPasswordSetupLink;
|
||||
use App\Modules\Users\Application\UseCases\UpdateUserAccount;
|
||||
use App\Modules\Users\Domain\Entities\UserAccount;
|
||||
use App\Modules\Users\Domain\Enums\Role;
|
||||
use App\Modules\Users\Domain\Exceptions\EmailAlreadyInUse;
|
||||
use App\Modules\Users\Domain\Exceptions\InvalidSupervisor;
|
||||
use App\Modules\Users\Domain\Exceptions\LastAdminCannotBeRemoved;
|
||||
use App\Modules\Users\Domain\Exceptions\UserAccountNotFound;
|
||||
use App\Modules\Users\Domain\Services\SupervisorRule;
|
||||
use App\Modules\Users\Domain\ValueObjects\EmailAddress;
|
||||
use App\Modules\Users\Domain\ValueObjects\PersonName;
|
||||
use Tests\Fakes\FakeClock;
|
||||
use Tests\Fakes\FakePasswordLinkSender;
|
||||
use Tests\Fakes\FakeTransactionManager;
|
||||
use Tests\Fakes\InMemoryUserAccountRepository;
|
||||
|
||||
beforeEach(function () {
|
||||
$this->users = new InMemoryUserAccountRepository;
|
||||
$this->passwordLinks = new FakePasswordLinkSender;
|
||||
$supervisorRule = new SupervisorRule($this->users);
|
||||
$transactions = new FakeTransactionManager;
|
||||
|
||||
$this->createUser = new CreateUserAccount($this->users, $supervisorRule, $transactions, $this->passwordLinks);
|
||||
$this->updateUser = new UpdateUserAccount($this->users, $supervisorRule, $transactions);
|
||||
|
||||
$this->adminId = $this->users->save(UserAccount::register(new PersonName('Anna Admin'), new EmailAddress('[email protected]'), Role::Admin))->id();
|
||||
$this->employeeId = $this->users->save(UserAccount::register(new PersonName('Eero Työntekijä'), new EmailAddress('[email protected]'), Role::Employee))->id();
|
||||
});
|
||||
|
||||
it('creates a user and sends a link for setting the password', function () {
|
||||
$userId = $this->createUser->execute(new UserAccountData('Maija Meikäläinen', '[email protected]', Role::Employee));
|
||||
|
||||
expect($this->users->findById($userId)?->email()->value)->toBe('[email protected]')
|
||||
->and($this->passwordLinks->sentTo)->toBe(['[email protected]']);
|
||||
});
|
||||
|
||||
it('creates an intern with an end date and a supervisor', function () {
|
||||
$userId = $this->createUser->execute(new UserAccountData('Ida', '[email protected]', Role::Intern, true, '2027-05-31', $this->employeeId));
|
||||
|
||||
$intern = $this->users->findById($userId);
|
||||
|
||||
expect($intern?->employmentEndsOn()?->format('Y-m-d'))->toBe('2027-05-31')
|
||||
->and($intern?->supervisorId())->toBe($this->employeeId);
|
||||
});
|
||||
|
||||
it('rejects a supervisor who cannot supervise', function (string $case) {
|
||||
$supervisorId = match ($case) {
|
||||
'admin' => $this->adminId,
|
||||
'unknown' => 999,
|
||||
'inactive' => $this->users->save(UserAccount::reconstitute(50, new PersonName('Pois'), new EmailAddress('[email protected]'), Role::Employee, false, null, null))->id(),
|
||||
};
|
||||
|
||||
$this->createUser->execute(new UserAccountData('Ida', '[email protected]', Role::Intern, true, '2027-05-31', $supervisorId));
|
||||
})->throws(InvalidSupervisor::class)->with(['admin', 'unknown', 'inactive']);
|
||||
|
||||
it('rejects an email address that another user has', function () {
|
||||
expect(fn () => $this->createUser->execute(new UserAccountData('Toinen Eero', '[email protected]', Role::Employee)))
|
||||
->toThrow(EmailAlreadyInUse::class)
|
||||
->and($this->passwordLinks->sentTo)->toBeEmpty();
|
||||
});
|
||||
|
||||
it('does not let the last active admin be deactivated or demoted', function (bool $active, Role $role) {
|
||||
$this->updateUser->execute($this->adminId, new UserAccountData('Anna Admin', '[email protected]', $role, $active));
|
||||
})->throws(LastAdminCannotBeRemoved::class)->with([
|
||||
'deactivated' => [false, Role::Admin],
|
||||
'demoted' => [true, Role::Management],
|
||||
]);
|
||||
|
||||
it('lets an admin be demoted when another active admin remains', function () {
|
||||
$this->users->save(UserAccount::register(new PersonName('Toinen Admin'), new EmailAddress('[email protected]'), Role::Admin));
|
||||
|
||||
$this->updateUser->execute($this->adminId, new UserAccountData('Anna Admin', '[email protected]', Role::Management));
|
||||
|
||||
expect($this->users->findById($this->adminId)?->role())->toBe(Role::Management);
|
||||
});
|
||||
|
||||
it('fails to update an unknown user', function () {
|
||||
$this->updateUser->execute(999, new UserAccountData('X', '[email protected]', Role::Employee));
|
||||
})->throws(UserAccountNotFound::class);
|
||||
|
||||
it('sends a password link to a stored user', function () {
|
||||
(new SendPasswordSetupLink($this->users, $this->passwordLinks))->execute($this->employeeId);
|
||||
|
||||
expect($this->passwordLinks->sentTo)->toBe(['[email protected]']);
|
||||
});
|
||||
|
||||
it('checks whether a user may log in today', function () {
|
||||
$internId = $this->createUser->execute(new UserAccountData('Ida', '[email protected]', Role::Intern, true, '2027-05-31', $this->employeeId));
|
||||
$clock = new FakeClock(new DateTimeImmutable('2027-05-31'));
|
||||
$checkLogin = new CheckLoginAllowed($this->users, $clock);
|
||||
|
||||
expect($checkLogin->execute($internId))->toBeTrue()
|
||||
->and($checkLogin->execute(999))->toBeFalse();
|
||||
|
||||
$clock->today = new DateTimeImmutable('2027-06-01');
|
||||
|
||||
expect($checkLogin->execute($internId))->toBeFalse();
|
||||
});
|
||||
|
||||
it('builds input from form data', function () {
|
||||
$data = UserAccountData::fromArray(['name' => 'Ida', 'email' => '[email protected]', 'role' => 'intern', 'active' => true, 'employment_ends_on' => '', 'supervisor_id' => '3']);
|
||||
|
||||
expect($data->role)->toBe(Role::Intern)
|
||||
->and($data->employmentEndsOn)->toBeNull()
|
||||
->and($data->supervisorId)->toBe(3);
|
||||
});
|
||||
@@ -0,0 +1,74 @@
|
||||
<?php
|
||||
|
||||
use App\Modules\Users\Domain\Entities\UserAccount;
|
||||
use App\Modules\Users\Domain\Enums\Role;
|
||||
use App\Modules\Users\Domain\Exceptions\InternRequiresEndDateAndSupervisor;
|
||||
use App\Modules\Users\Domain\Exceptions\InvalidSupervisor;
|
||||
use App\Modules\Users\Domain\ValueObjects\EmailAddress;
|
||||
use App\Modules\Users\Domain\ValueObjects\PersonName;
|
||||
|
||||
function makeIntern(?string $endsOn = '2027-05-31', ?int $supervisorId = 1): UserAccount
|
||||
{
|
||||
return UserAccount::register(
|
||||
new PersonName('Ida Harjoittelija'),
|
||||
new EmailAddress('[email protected]'),
|
||||
Role::Intern,
|
||||
$endsOn === null ? null : new DateTimeImmutable($endsOn),
|
||||
$supervisorId,
|
||||
);
|
||||
}
|
||||
|
||||
it('registers an active user', function () {
|
||||
$user = UserAccount::register(new PersonName('Eero Esimerkki'), new EmailAddress('[email protected]'), Role::Employee);
|
||||
|
||||
expect($user->id())->toBeNull()
|
||||
->and($user->isActive())->toBeTrue()
|
||||
->and($user->email()->value)->toBe('[email protected]');
|
||||
});
|
||||
|
||||
it('requires an intern to have an end date and a supervisor', function (?string $endsOn, ?int $supervisorId) {
|
||||
makeIntern($endsOn, $supervisorId);
|
||||
})->throws(InternRequiresEndDateAndSupervisor::class)->with([
|
||||
'no end date' => [null, 1],
|
||||
'no supervisor' => ['2027-05-31', null],
|
||||
]);
|
||||
|
||||
it('does not let an intern supervise themselves', function () {
|
||||
$user = UserAccount::reconstitute(5, new PersonName('Ida'), new EmailAddress('[email protected]'), Role::Employee, true, null, null);
|
||||
|
||||
$user->changeDetails($user->name(), $user->email(), Role::Intern, true, new DateTimeImmutable('2027-05-31'), 5);
|
||||
})->throws(InvalidSupervisor::class);
|
||||
|
||||
it('clears the end date and supervisor when an intern gets another role', function () {
|
||||
$user = makeIntern();
|
||||
|
||||
$user->changeDetails($user->name(), $user->email(), Role::Employee, true, $user->employmentEndsOn(), $user->supervisorId());
|
||||
|
||||
expect($user->role())->toBe(Role::Employee)
|
||||
->and($user->employmentEndsOn())->toBeNull()
|
||||
->and($user->supervisorId())->toBeNull();
|
||||
});
|
||||
|
||||
it('keeps the old details when a change breaks a rule', function () {
|
||||
$user = UserAccount::register(new PersonName('Eero'), new EmailAddress('[email protected]'), Role::Employee);
|
||||
|
||||
expect(fn () => $user->changeDetails(new PersonName('Uusi'), $user->email(), Role::Intern, true, null, null))
|
||||
->toThrow(InternRequiresEndDateAndSupervisor::class)
|
||||
->and($user->name()->value)->toBe('Eero')
|
||||
->and($user->role())->toBe(Role::Employee);
|
||||
});
|
||||
|
||||
it('lets an intern log in until the end of the last day', function (string $day, bool $allowed) {
|
||||
expect(makeIntern('2027-05-31')->canLogInOn(new DateTimeImmutable($day)))->toBe($allowed);
|
||||
})->with([
|
||||
'before' => ['2027-05-30', true],
|
||||
'last day' => ['2027-05-31 23:59', true],
|
||||
'day after' => ['2027-06-01', false],
|
||||
]);
|
||||
|
||||
it('does not let an inactive user log in', function () {
|
||||
$user = UserAccount::reconstitute(1, new PersonName('Eero'), new EmailAddress('[email protected]'), Role::Admin, false, null, null);
|
||||
|
||||
expect($user->canLogInOn(new DateTimeImmutable('2026-01-01')))->toBeFalse()
|
||||
->and($user->isActiveAdmin())->toBeFalse();
|
||||
});
|
||||
@@ -0,0 +1,24 @@
|
||||
<?php
|
||||
|
||||
use App\Modules\Users\Domain\Enums\Role;
|
||||
use App\Modules\Users\Domain\Exceptions\InvalidEmailAddress;
|
||||
use App\Modules\Users\Domain\Exceptions\InvalidPersonName;
|
||||
use App\Modules\Users\Domain\ValueObjects\EmailAddress;
|
||||
use App\Modules\Users\Domain\ValueObjects\PersonName;
|
||||
|
||||
it('normalises an email address to lower case', function () {
|
||||
expect((new EmailAddress(' [email protected] '))->value)->toBe('[email protected]');
|
||||
});
|
||||
|
||||
it('rejects an invalid email address', function (string $email) {
|
||||
new EmailAddress($email);
|
||||
})->throws(InvalidEmailAddress::class)->with(['', 'maija', 'maija@', '@example.fi']);
|
||||
|
||||
it('rejects an empty person name', function () {
|
||||
new PersonName(' ');
|
||||
})->throws(InvalidPersonName::class);
|
||||
|
||||
it('knows which roles manage users and supervise interns', function () {
|
||||
expect(array_filter(Role::cases(), fn (Role $role) => $role->canManageUsers()))->toBe([Role::Admin])
|
||||
->and(array_values(array_filter(Role::cases(), fn (Role $role) => $role->canSupervise())))->toBe([Role::Management, Role::Employee]);
|
||||
});
|
||||
Reference in New Issue
Block a user