Give the machine console its own session with PIN sign-in, make counters cumulative

The console under console/ has its own session cookie and console guard
(UseConsoleSession), so signing out or changing user there leaves the
normal interface alone. Links open it in a new window through a one-time
handoff key; a signed-out console asks for a PIN code or password on its
own login page. Users set their 4-6 digit PIN on the profile's PIN page,
and the console's change user dialog takes it on a keypad; five wrong
PINs lock PIN sign-in for 15 minutes.

Machine counters are cumulative: users record how much a job used and it
is added to the latest reading. A maintenance record restarts the whole
counter interval from the reading at the record.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
This commit is contained in:
2026-11-29 09:58:11 +02:00
co-authored by Claude Sonnet 5.5
parent 87e38260dc
commit 32c33e2a64
55 changed files with 1660 additions and 194 deletions
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace App\Modules\Users\Application\Contracts;
/**
* One-way hashing of passwords and PIN codes.
*/
interface SecretHasher
{
public function hash(string $secret): string;
public function check(string $secret, string $hash): bool;
}
@@ -36,6 +36,14 @@ interface UserAccountQueries
*/
public function activeUserOptions(): array;
/**
* Users who may sign in today and have a console PIN code, ordered by
* name, for switching user on a machine console.
*
* @return list<UserOption>
*/
public function pinLoginOptions(): array;
/**
* User names for many ids at once, active or not (for lists and history).
*
@@ -0,0 +1,79 @@
<?php
declare(strict_types=1);
namespace App\Modules\Users\Application\UseCases;
use App\Modules\Shared\Application\Contracts\TransactionManager;
use App\Modules\Users\Application\Contracts\SecretHasher;
use App\Modules\Users\Domain\Contracts\LoginSecrets;
use App\Modules\Users\Domain\Exceptions\InvalidLoginPin;
use App\Modules\Users\Domain\Exceptions\WrongPassword;
use App\Modules\Users\Domain\ValueObjects\LoginPin;
/**
* Users' own PIN codes for switching user on a machine console (spec
* 19.6): a user sets one with their password, and the console signs them
* in with it while their account may sign in. Only the hash is stored.
*/
final class LoginPins
{
public function __construct(
private LoginSecrets $secrets,
private SecretHasher $hasher,
private CheckLoginAllowed $loginAllowed,
private TransactionManager $transactions,
) {}
/**
* @throws InvalidLoginPin
* @throws WrongPassword
*/
public function set(int $userId, string $currentPassword, string $pin): void
{
$pin = new LoginPin($pin);
$this->checkPassword($userId, $currentPassword);
$this->transactions->run(fn () => $this->secrets->storePinHash($userId, $this->hasher->hash($pin->value)));
}
/**
* @throws WrongPassword
*/
public function remove(int $userId, string $currentPassword): void
{
$this->checkPassword($userId, $currentPassword);
$this->transactions->run(fn () => $this->secrets->storePinHash($userId, null));
}
public function has(int $userId): bool
{
return $this->secrets->pinHashOf($userId) !== null;
}
/**
* Whether the PIN code is the user's and the user may sign in today.
*/
public function verify(int $userId, string $pin): bool
{
$hash = $this->secrets->pinHashOf($userId);
return $hash !== null
&& preg_match('/^\d{'.LoginPin::MIN_LENGTH.','.LoginPin::MAX_LENGTH.'}$/', trim($pin)) === 1
&& $this->hasher->check(trim($pin), $hash)
&& $this->loginAllowed->execute($userId);
}
/**
* @throws WrongPassword
*/
private function checkPassword(int $userId, string $password): void
{
$hash = $this->secrets->passwordHashOf($userId);
if ($hash === null || ! $this->hasher->check($password, $hash)) {
throw new WrongPassword;
}
}
}
@@ -0,0 +1,20 @@
<?php
declare(strict_types=1);
namespace App\Modules\Users\Domain\Contracts;
/**
* The hashes of a user's password and console PIN code.
*/
interface LoginSecrets
{
public function passwordHashOf(int $userId): ?string;
public function pinHashOf(int $userId): ?string;
/**
* Stores the hash of the user's PIN code, or removes it with null.
*/
public function storePinHash(int $userId, ?string $hash): void;
}
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace App\Modules\Users\Domain\Exceptions;
use App\Modules\Shared\Domain\Exceptions\DomainException;
final class InvalidLoginPin extends DomainException
{
public function __construct()
{
parent::__construct('The PIN code must be 4–6 digits.');
}
}
@@ -0,0 +1,15 @@
<?php
declare(strict_types=1);
namespace App\Modules\Users\Domain\Exceptions;
use App\Modules\Shared\Domain\Exceptions\DomainException;
final class WrongPassword extends DomainException
{
public function __construct()
{
parent::__construct('The current password is not correct.');
}
}
@@ -0,0 +1,31 @@
<?php
declare(strict_types=1);
namespace App\Modules\Users\Domain\ValueObjects;
use App\Modules\Users\Domain\Exceptions\InvalidLoginPin;
/**
* A user's own PIN code for switching user on a machine console: 4–6
* digits. It is never stored as such, only its hash.
*/
final readonly class LoginPin
{
public const int MIN_LENGTH = 4;
public const int MAX_LENGTH = 6;
public string $value;
public function __construct(string $value)
{
$value = trim($value);
if (preg_match('/^\d{'.self::MIN_LENGTH.','.self::MAX_LENGTH.'}$/', $value) !== 1) {
throw new InvalidLoginPin;
}
$this->value = $value;
}
}
@@ -0,0 +1,19 @@
<?php
namespace App\Modules\Users\Infrastructure\Auth;
use App\Modules\Users\Application\Contracts\SecretHasher;
use Illuminate\Support\Facades\Hash;
class LaravelSecretHasher implements SecretHasher
{
public function hash(string $secret): string
{
return Hash::make($secret);
}
public function check(string $secret, string $hash): bool
{
return Hash::check($secret, $hash);
}
}
@@ -0,0 +1,28 @@
<?php
namespace App\Modules\Users\Infrastructure\Persistence\Repositories;
use App\Models\User;
use App\Modules\Users\Domain\Contracts\LoginSecrets;
class EloquentLoginSecrets implements LoginSecrets
{
public function passwordHashOf(int $userId): ?string
{
$hash = User::query()->whereKey($userId)->value('password');
return $hash === null ? null : (string) $hash;
}
public function pinHashOf(int $userId): ?string
{
$hash = User::query()->whereKey($userId)->value('pin_hash');
return $hash === null ? null : (string) $hash;
}
public function storePinHash(int $userId, ?string $hash): void
{
User::query()->whereKey($userId)->update(['pin_hash' => $hash]);
}
}
@@ -3,6 +3,7 @@
namespace App\Modules\Users\Infrastructure\Persistence\Repositories;
use App\Models\User;
use App\Modules\Users\Application\Contracts\Clock;
use App\Modules\Users\Application\Contracts\UserAccountQueries;
use App\Modules\Users\Application\DTOs\UserOption;
use App\Modules\Users\Application\DTOs\UserSummary;
@@ -12,6 +13,10 @@ use Illuminate\Database\Eloquent\Builder;
class EloquentUserAccountQueries implements UserAccountQueries
{
public function __construct(
private Clock $clock,
) {}
public function findSummary(int $id): ?UserSummary
{
$model = User::query()->with(['supervisor:id,name', 'moneyPermissions'])->find($id);
@@ -61,6 +66,21 @@ class EloquentUserAccountQueries implements UserAccountQueries
->all();
}
public function pinLoginOptions(): array
{
$today = $this->clock->today()->format('Y-m-d');
return User::query()
->where('is_active', true)
->whereNotNull('pin_hash')
->where(fn (Builder $query) => $query->whereNull('employment_ends_on')->orWhereDate('employment_ends_on', '>=', $today))
->orderBy('name')
->get(['id', 'name', 'role'])
->map(fn (User $model): UserOption => new UserOption($model->id, $model->name, $model->role))
->values()
->all();
}
public function namesByIds(array $ids): array
{
return $ids === [] ? [] : User::query()->whereIn('id', $ids)->pluck('name', 'id')->all();
@@ -5,11 +5,15 @@ 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\SecretHasher;
use App\Modules\Users\Application\Contracts\UserAccountQueries;
use App\Modules\Users\Domain\Contracts\LoginSecrets;
use App\Modules\Users\Domain\Contracts\UserAccountRepository;
use App\Modules\Users\Domain\Enums\MoneyPermission;
use App\Modules\Users\Infrastructure\Auth\LaravelPasswordLinkSender;
use App\Modules\Users\Infrastructure\Auth\LaravelSecretHasher;
use App\Modules\Users\Infrastructure\Auth\PasswordLinkMail;
use App\Modules\Users\Infrastructure\Persistence\Repositories\EloquentLoginSecrets;
use App\Modules\Users\Infrastructure\Persistence\Repositories\EloquentUserAccountQueries;
use App\Modules\Users\Infrastructure\Persistence\Repositories\EloquentUserAccountRepository;
use App\Modules\Users\Infrastructure\SystemClock;
@@ -17,6 +21,7 @@ use App\Modules\Users\Presentation\Console\CreateAdminCommand;
use App\Modules\Users\Presentation\Http\Listeners\StoreLocaleChosenBeforeLogin;
use App\Modules\Users\Presentation\Http\Middleware\EnsureAccountIsUsable;
use App\Modules\Users\Presentation\Http\Middleware\SetLocale;
use App\Modules\Users\Presentation\Http\Middleware\UseConsoleSession;
use Illuminate\Auth\Events\Login;
use Illuminate\Auth\Notifications\ResetPassword;
use Illuminate\Contracts\Auth\CanResetPassword;
@@ -42,6 +47,8 @@ class UsersServiceProvider extends ServiceProvider
UserAccountRepository::class => EloquentUserAccountRepository::class,
UserAccountQueries::class => EloquentUserAccountQueries::class,
PasswordLinkSender::class => LaravelPasswordLinkSender::class,
LoginSecrets::class => EloquentLoginSecrets::class,
SecretHasher::class => LaravelSecretHasher::class,
];
public function register(): void
@@ -59,6 +66,9 @@ class UsersServiceProvider extends ServiceProvider
$this->loadRoutesFrom($presentationPath.'/Routes/web.php');
}
// The machine console's own session and guard; before the session starts.
$router->prependMiddlewareToGroup('web', UseConsoleSession::class);
$router->pushMiddlewareToGroup('web', EnsureAccountIsUsable::class);
// Ends the user's other sessions when their password changes.
@@ -0,0 +1,65 @@
<?php
namespace App\Modules\Users\Presentation\Http\Controllers;
use App\Modules\Users\Application\UseCases\CheckLoginAllowed;
use App\Modules\Users\Presentation\Http\Middleware\UseConsoleSession;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Str;
/**
* Opens the machine console in its own window signed in as the same user
* (spec 19.6). The normal user interface makes a one-time key valid for a
* minute; the console's own session (UseConsoleSession) takes it and signs
* the user in there. After that the two sessions live apart.
*/
class ConsoleHandoff
{
public const int SECONDS = 60;
/**
* In the normal user interface: a key for the console page in "to".
*/
public function start(Request $request): RedirectResponse
{
$to = (string) $request->query('to', '');
abort_unless(UseConsoleSession::isConsoleUrl($to), 404);
$token = Str::random(40);
Cache::put(self::cacheKey($token), ['user' => (int) $request->user()?->getAuthIdentifier(), 'to' => $to], self::SECONDS);
return redirect()->route('console.handoff.accept', $token);
}
/**
* In the console's own session: signs in with the key once.
*/
public function accept(Request $request, string $token, CheckLoginAllowed $checkLoginAllowed): RedirectResponse
{
/** @var array{user: int, to: string}|null $handoff */
$handoff = Cache::pull(self::cacheKey($token));
if ($handoff === null || ! $checkLoginAllowed->execute($handoff['user'])) {
return redirect()->route('console.login');
}
if (Auth::check()) {
Auth::logout();
$request->session()->invalidate();
$request->session()->regenerateToken();
}
Auth::loginUsingId($handoff['user']);
$request->session()->regenerate();
return redirect()->to($handoff['to']);
}
private static function cacheKey(string $token): string
{
return 'console-handoff|'.hash('sha256', $token);
}
}
@@ -0,0 +1,34 @@
<?php
namespace App\Modules\Users\Presentation\Http\Controllers;
use App\Modules\Users\Presentation\Http\Middleware\SetLocale;
use App\Modules\Users\Presentation\Http\Middleware\UseConsoleSession;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
/**
* Signs out of the machine console's own session only (spec 19.6), e.g. to
* sign in there with email and password; the normal user interface stays
* signed in. The console's sign-in page returns to the console page.
*/
class ConsoleLogoutController
{
public function __invoke(Request $request): RedirectResponse
{
$locale = app()->getLocale();
$returnTo = (string) $request->input('return_to', '');
Auth::logout();
$request->session()->invalidate();
$request->session()->regenerateToken();
$request->session()->put(SetLocale::SESSION_KEY, $locale);
if (UseConsoleSession::isConsoleUrl($returnTo)) {
$request->session()->put('url.intended', $returnTo);
}
return redirect()->route('console.login');
}
}
@@ -36,7 +36,7 @@ class EnsureAccountIsUsable
// The reason goes in the URL: Livewire follows this redirect with
// fetch first, which would consume a flashed message.
return redirect()->route('login', ['access' => 'ended']);
return redirect()->route(UseConsoleSession::isConsole($request) ? 'console.login' : 'login', ['access' => 'ended']);
}
return $next($request);
@@ -0,0 +1,78 @@
<?php
namespace App\Modules\Users\Presentation\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Session\SessionManager;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Str;
use Symfony\Component\HttpFoundation\Response;
/**
* Gives the machine console its own session (spec 19.6), so the console can
* run in its own window or on a tablet next to the normal user interface
* in the same browser: pages under console/ and the Livewire requests of
* components rendered there use a session cookie of their own and the
* "console" guard. Signing in or out on one side leaves the other alone,
* and /login always signs in to the normal user interface.
*
* Runs before StartSession. A Livewire request tells where its component
* was rendered by the path Livewire keeps in the snapshot (memo.path); it
* can only choose between the browser's own sessions, and the CSRF token
* of that session must still match.
*/
class UseConsoleSession
{
public const string PREFIX = 'console';
public const string GUARD = 'console';
public const string DEFAULT_GUARD = 'web';
public function __construct(private SessionManager $sessions) {}
public function handle(Request $request, Closure $next): Response
{
$console = self::isConsole($request);
$cookie = (string) config('session.cookie');
$this->sessions->driver()->setName($console ? $cookie.'_console' : $cookie);
Auth::shouldUse($console ? self::GUARD : self::DEFAULT_GUARD);
return $next($request);
}
public static function isConsole(Request $request): bool
{
if (self::isConsolePath($request->path())) {
return true;
}
if (! $request->hasHeader('X-Livewire')) {
return false;
}
$snapshot = json_decode((string) $request->input('components.0.snapshot', ''), true);
$path = is_array($snapshot) ? ($snapshot['memo']['path'] ?? null) : null;
return is_string($path) && self::isConsolePath($path);
}
/**
* Whether a URL of this application is on the console.
*/
public static function isConsoleUrl(string $url): bool
{
$base = rtrim(url('/'), '/').'/';
return Str::startsWith($url, $base.self::PREFIX.'/') && ! Str::contains($url, ['\\', '@']);
}
private static function isConsolePath(string $path): bool
{
$path = trim($path, '/');
return $path === self::PREFIX || str_starts_with($path, self::PREFIX.'/');
}
}
@@ -0,0 +1,74 @@
<?php
namespace App\Modules\Users\Presentation\Livewire\Concerns;
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;
/**
* Signing in with email and password, on the login page and on the
* machine console's sign-in page: 5 failed attempts a minute per email and
* address, 20 per address across all accounts (password spraying), and one
* message for a wrong password and a disabled account. Signs in to the
* request's guard (the console's own on console pages).
*
* @property string $email
* @property string $password
*/
trait SignsInWithPassword
{
public string $email = '';
public string $password = '';
/**
* @throws ValidationException
*/
protected function signInWithPassword(CheckLoginAllowed $checkLoginAllowed, bool $remember = false): 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());
$ipThrottleKey = 'login-ip|'.request()->ip();
foreach ([$throttleKey => 5, $ipThrottleKey => 20] as $key => $maxAttempts) {
if (RateLimiter::tooManyAttempts($key, $maxAttempts)) {
throw ValidationException::withMessages([
'email' => __('auth.throttle', ['seconds' => RateLimiter::availableIn($key)]),
]);
}
}
$signedIn = Auth::attemptWhen(
['email' => $email, 'password' => $this->password],
fn ($user): bool => $checkLoginAllowed->execute($user->getAuthIdentifier()),
$remember,
);
if (! $signedIn) {
RateLimiter::hit($throttleKey);
RateLimiter::hit($ipThrottleKey);
$this->reset('password');
// One message for a wrong password and a disabled account, so the
// form never confirms that a disabled account's password is right.
throw ValidationException::withMessages(['email' => __('auth.failed')]);
}
RateLimiter::clear($throttleKey);
session()->regenerate();
}
}
@@ -0,0 +1,84 @@
<?php
namespace App\Modules\Users\Presentation\Livewire\Concerns;
use App\Modules\Users\Application\Contracts\UserAccountQueries;
use App\Modules\Users\Application\DTOs\UserOption;
use App\Modules\Users\Application\UseCases\LoginPins;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\RateLimiter;
use Livewire\Attributes\Computed;
/**
* Signing in with a user's own console PIN code (spec 19.6): the user picks
* their name and types the PIN. Five wrong PIN codes lock the user's PIN
* sign-in for 15 minutes, and one address may try 20 times a minute. Ends
* the request's guard's earlier sign-in (the console's own on console
* pages) and starts a new session for the user.
*/
trait SignsInWithPin
{
public string $userId = '';
public string $pin = '';
/**
* @return list<UserOption>
*/
#[Computed]
public function pinUsers(): array
{
return app(UserAccountQueries::class)->pinLoginOptions();
}
/**
* @return bool Whether the user is now signed in.
*/
protected function signInWithPin(LoginPins $pins): bool
{
$this->resetErrorBag();
$user = collect($this->pinUsers)->firstWhere('id', (int) $this->userId);
if ($user === null) {
$this->addError('userId', __('users.pin_switch.errors.user'));
return false;
}
$userKey = 'pin-login|user|'.$user->id;
$ipKey = 'pin-login|ip|'.request()->ip();
foreach ([[$userKey, 5], [$ipKey, 20]] as [$key, $max]) {
if (RateLimiter::tooManyAttempts($key, $max)) {
$this->addError('pin', __('users.pin_switch.errors.locked', ['minutes' => (int) ceil(RateLimiter::availableIn($key) / 60)]));
$this->pin = '';
return false;
}
}
RateLimiter::hit($ipKey, 60);
if (! $pins->verify($user->id, $this->pin)) {
RateLimiter::hit($userKey, 900);
$this->addError('pin', __('users.pin_switch.errors.pin'));
$this->pin = '';
return false;
}
RateLimiter::clear($userKey);
if (Auth::check()) {
Auth::logout();
session()->invalidate();
session()->regenerateToken();
}
Auth::loginUsingId($user->id);
session()->regenerate();
return true;
}
}
@@ -0,0 +1,81 @@
<?php
use App\Modules\Users\Application\UseCases\CheckLoginAllowed;
use App\Modules\Users\Application\UseCases\LoginPins;
use App\Modules\Users\Presentation\Livewire\Concerns\SignsInWithPassword;
use App\Modules\Users\Presentation\Livewire\Concerns\SignsInWithPin;
use Livewire\Attributes\Layout;
use Livewire\Component;
/**
* Signing in to the machine console's own session (spec 19.6), e.g. on a
* tablet next to the machine: with the user's own PIN code or with email
* and password. Returns to the console page that asked for it.
*/
new #[Layout('layouts.console')] class extends Component
{
use SignsInWithPassword;
use SignsInWithPin;
public bool $accessEnded = false;
public function mount(): void
{
$this->accessEnded = request()->query('access') === 'ended';
}
public function loginWithPin(LoginPins $pins): void
{
if ($this->signInWithPin($pins)) {
$this->redirectIntended(route('machines.index'));
}
}
public function loginWithPassword(CheckLoginAllowed $checkLoginAllowed): void
{
$this->signInWithPassword($checkLoginAllowed);
$this->redirectIntended(route('machines.index'));
}
public function render(): mixed
{
return $this->view()->title(__('users.console_login.title'));
}
};
?>
<div class="mx-auto max-w-3xl space-y-6 p-3 sm:p-6">
<h1 class="text-2xl font-semibold">{{ __('users.console_login.title') }}</h1>
<p>{{ __('users.console_login.intro') }}</p>
@if ($accessEnded)
<x-alert role="status" color="yellow" light icon="exclamation-triangle" :text="__('auth.account_disabled')" />
@elseif (session('status'))
<x-alert role="status" color="green" light icon="information-circle" :text="session('status')" />
@endif
<div class="grid gap-6 md:grid-cols-2">
<section aria-labelledby="console-login-pin" class="space-y-4 rounded-lg border border-zinc-300 p-4 dark:border-zinc-600">
<h2 id="console-login-pin" class="text-xl font-semibold">{{ __('users.console_login.with_pin') }}</h2>
@if ($this->pinUsers === [])
<p>{{ __('users.pin_switch.no_users') }}</p>
@else
<form wire:submit="loginWithPin" class="space-y-4" novalidate>
<x-users.pin-fields :users="$this->pinUsers" />
<x-button submit icon="arrow-right-end-on-rectangle" :text="__('users.pin_switch.submit')" class="w-full" />
</form>
@endif
</section>
<section aria-labelledby="console-login-password" class="space-y-4 rounded-lg border border-zinc-300 p-4 dark:border-zinc-600">
<h2 id="console-login-password" class="text-xl font-semibold">{{ __('users.console_login.with_password') }}</h2>
<form wire:submit="loginWithPassword" class="space-y-4" novalidate>
<x-input id="console-login-email" wire:model="email" type="email" :label="__('auth.email')" autocomplete="username" required />
<x-password-field id="console-login-password-field" wire:model="password" :label="__('auth.password_label')" autocomplete="current-password" required />
<x-button submit :text="__('auth.login')" class="w-full" />
</form>
</section>
</div>
</div>
@@ -1,25 +1,12 @@
<?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 App\Modules\Users\Presentation\Livewire\Concerns\SignsInWithPassword;
use Livewire\Component;
new class extends Component
{
public const int MAX_ATTEMPTS_PER_MINUTE = 5;
/**
* Failed attempts from one address across all accounts, so one common
* password cannot be tried on every account (password spraying).
*/
public const int MAX_ATTEMPTS_PER_IP_PER_MINUTE = 20;
public string $email = '';
public string $password = '';
use SignsInWithPassword;
public bool $remember = false;
@@ -37,47 +24,7 @@ new class extends Component
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());
$ipThrottleKey = 'login-ip|'.request()->ip();
foreach ([$throttleKey => self::MAX_ATTEMPTS_PER_MINUTE, $ipThrottleKey => self::MAX_ATTEMPTS_PER_IP_PER_MINUTE] as $key => $maxAttempts) {
if (RateLimiter::tooManyAttempts($key, $maxAttempts)) {
throw ValidationException::withMessages([
'email' => __('auth.throttle', ['seconds' => RateLimiter::availableIn($key)]),
]);
}
}
$signedIn = Auth::attemptWhen(
['email' => $email, 'password' => $this->password],
fn ($user): bool => $checkLoginAllowed->execute($user->getAuthIdentifier()),
$this->remember,
);
if (! $signedIn) {
RateLimiter::hit($throttleKey);
RateLimiter::hit($ipThrottleKey);
$this->reset('password');
// One message for a wrong password and a disabled account, so the
// form never confirms that a disabled account's password is right.
throw ValidationException::withMessages(['email' => __('auth.failed')]);
}
RateLimiter::clear($throttleKey);
session()->regenerate();
$this->signInWithPassword($checkLoginAllowed, $this->remember);
$this->redirectIntended(route('home'));
}
@@ -0,0 +1,83 @@
<?php
use App\Modules\Users\Application\UseCases\LoginPins;
use App\Modules\Users\Presentation\Http\Middleware\UseConsoleSession;
use App\Modules\Users\Presentation\Livewire\Concerns\SignsInWithPin;
use Livewire\Attributes\Locked;
use Livewire\Component;
/**
* "Vaihda käyttäjä" on a machine console (spec 19.6): the next user picks
* their name and types their own PIN code. The console has its own session
* (UseConsoleSession), so this changes only the console's user. Users
* without a PIN code sign in with their email and password on the
* console's sign-in page, back to the console.
*/
new class extends Component
{
use SignsInWithPin;
/**
* The console to return to, given by the console page.
*/
#[Locked]
public string $returnTo = '';
public function mount(string $returnTo): void
{
abort_unless(UseConsoleSession::isConsoleUrl($returnTo) && ! str_contains($returnTo, '?'), 404);
$this->returnTo = $returnTo;
}
public function switchUser(LoginPins $pins): void
{
if ($this->signInWithPin($pins)) {
$this->redirect($this->returnTo);
}
}
public function render(): mixed
{
return $this->view();
}
};
?>
@php
$touch = 'inline-flex min-h-11 min-w-11 items-center justify-center gap-2 rounded-lg px-4 py-2 font-medium focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-blue-700 dark:focus-visible:outline-blue-400';
@endphp
<div>
<button
type="button"
id="pin-switch-open"
x-on:click="document.getElementById('pin-switch-dialog').showModal()"
class="{{ $touch }} border border-zinc-300 text-zinc-100 hover:bg-zinc-700"
>
<x-icon name="user-circle" class="size-6" aria-hidden="true" />
{{ __('machines.console.change_user') }}
</button>
<x-confirm-dialog id="pin-switch-dialog" :title="__('users.pin_switch.title')" class="text-base">
@if ($this->pinUsers === [])
<p>{{ __('users.pin_switch.no_users') }}</p>
@else
<form id="pin-switch-form" wire:submit="switchUser" class="space-y-4" novalidate>
<x-users.pin-fields :users="$this->pinUsers" />
</form>
@endif
<form method="POST" action="{{ route('console.logout') }}" class="mt-4 border-t border-zinc-300 pt-3 dark:border-zinc-600">
@csrf
<input type="hidden" name="return_to" value="{{ $returnTo }}">
<button type="submit" class="text-sm font-medium text-primary-700 underline hover:no-underline focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-blue-700 dark:text-primary-300">{{ __('users.pin_switch.with_password') }}</button>
</form>
<x-slot:actions>
@if ($this->pinUsers !== [])
<x-button wire:click="switchUser" icon="arrow-right-end-on-rectangle" :text="__('users.pin_switch.submit')" />
@endif
</x-slot:actions>
</x-confirm-dialog>
</div>
@@ -0,0 +1,101 @@
<?php
use App\Modules\Users\Application\UseCases\LoginPins;
use App\Modules\Users\Domain\Exceptions\InvalidLoginPin;
use App\Modules\Users\Domain\Exceptions\WrongPassword;
use Livewire\Attributes\Locked;
use Livewire\Component;
/**
* The user's own PIN code for switching user on a machine console (spec
* 19.6). Setting or removing it asks for the user's password.
*/
new class extends Component
{
public string $currentPassword = '';
public string $pin = '';
public string $pinConfirmation = '';
#[Locked]
public string $message = '';
public function mount(): void
{
$this->authorize('machines.use');
}
public function save(LoginPins $pins): void
{
$this->authorize('machines.use');
$this->resetErrorBag();
if (trim($this->pin) !== trim($this->pinConfirmation)) {
$this->addError('pinConfirmation', __('users.pin.errors.confirmation'));
return;
}
try {
$pins->set((int) auth()->id(), $this->currentPassword, $this->pin);
} catch (InvalidLoginPin) {
$this->addError('pin', __('users.pin.errors.pin'));
return;
} catch (WrongPassword) {
$this->addError('currentPassword', __('users.pin.errors.password'));
return;
}
$this->reset('currentPassword', 'pin', 'pinConfirmation');
$this->message = __('users.pin.saved');
}
public function remove(LoginPins $pins): void
{
$this->authorize('machines.use');
$this->resetErrorBag();
try {
$pins->remove((int) auth()->id(), $this->currentPassword);
} catch (WrongPassword) {
$this->addError('currentPassword', __('users.pin.errors.password'));
return;
}
$this->reset('currentPassword', 'pin', 'pinConfirmation');
$this->message = __('users.pin.removed');
}
public function render(): mixed
{
return $this->view()->title(__('users.pin.title'));
}
};
?>
<div class="mx-auto max-w-md space-y-6 p-4 sm:p-6">
<h1 class="text-2xl font-semibold">{{ __('users.pin.title') }}</h1>
<p class="text-sm">{{ __('users.pin.intro') }}</p>
<p role="status" aria-live="polite" class="text-sm font-medium">
{{ $message !== '' ? $message : (app(LoginPins::class)->has((int) auth()->id()) ? __('users.pin.is_set') : __('users.pin.not_set')) }}
</p>
<form wire:submit="save" class="space-y-4" novalidate>
<x-password-field id="current-password" wire:model="currentPassword" :label="__('users.pin.current_password')" autocomplete="current-password" />
<x-input id="pin" wire:model="pin" type="password" inputmode="numeric" maxlength="6" :label="__('users.pin.pin')" :hint="__('users.pin.pin_hint')" autocomplete="off" />
<x-input id="pin-confirmation" wire:model="pinConfirmation" type="password" inputmode="numeric" maxlength="6" :label="__('users.pin.pin_confirmation')" autocomplete="off" />
<div class="flex flex-wrap gap-3">
<x-button submit :text="__('users.pin.save')" />
@if (app(LoginPins::class)->has((int) auth()->id()))
<x-button wire:click="remove" subtle color="black" :text="__('users.pin.remove')" />
@endif
</div>
</form>
</div>
@@ -1,5 +1,7 @@
<?php
use App\Modules\Users\Presentation\Http\Controllers\ConsoleHandoff;
use App\Modules\Users\Presentation\Http\Controllers\ConsoleLogoutController;
use App\Modules\Users\Presentation\Http\Controllers\LogoutController;
use App\Modules\Users\Presentation\Http\Controllers\SwitchLocaleController;
use Illuminate\Support\Facades\Route;
@@ -12,8 +14,17 @@ Route::middleware(['web', 'guest'])->group(function () {
Route::livewire('/reset-password/{token}', 'users::reset-password')->name('password.reset');
});
// The machine console's own session (UseConsoleSession: paths under console/).
Route::middleware('web')->prefix('console')->name('console.')->group(function () {
Route::livewire('/login', 'users::console-login')->middleware('guest')->name('login');
Route::get('/handoff/{token}', [ConsoleHandoff::class, 'accept'])->middleware('throttle:30,1')->name('handoff.accept');
Route::post('/logout', ConsoleLogoutController::class)->middleware('auth')->name('logout');
});
Route::middleware(['web', 'auth'])->group(function () {
Route::post('/logout', LogoutController::class)->name('logout');
Route::livewire('/profile/pin', 'users::pin')->middleware('can:machines.use')->name('profile.pin');
Route::get('/console-handoff', [ConsoleHandoff::class, 'start'])->middleware('throttle:30,1')->name('console.handoff');
Route::middleware('can:users.manage')
->prefix('users')