Files
portal-api/app/Support/Auth/AdminLoginLockout.php
T

78 lines
3.0 KiB
PHP

<?php
namespace App\Support\Auth;
use App\Models\AdminLoginBlock;
use Illuminate\Support\Facades\DB;
class AdminLoginLockout
{
public const MAX_FAILURES = 4;
public const BLOCK_MINUTES = 20;
public const KIND_IP = 'ip';
public const KIND_ACCOUNT = 'account';
public static function activeBlock(string $ip, string $username): ?AdminLoginBlock
{
return AdminLoginBlock::active()
->where(fn ($query) => $query
->where(['kind' => self::KIND_IP, 'identifier' => $ip])
->orWhere(fn ($account) => $account->where(['kind' => self::KIND_ACCOUNT, 'identifier' => self::accountKey($username)])))
->orderByDesc('blocked_until')
->first();
}
/**
* @return list<AdminLoginBlock> IP counter first, then the account counter when a username was given
*/
public static function recordFailure(string $ip, string $username, ?string $userAgent): array
{
$blocks = [self::recordOne(self::KIND_IP, $ip, $ip, $username, $userAgent)];
if (self::accountKey($username) !== '') {
$blocks[] = self::recordOne(self::KIND_ACCOUNT, self::accountKey($username), $ip, $username, $userAgent);
}
return $blocks;
}
/**
* @param list<AdminLoginBlock> $blocks
*/
public static function remainingAttempts(array $blocks): int
{
return max(0, min(array_map(fn (AdminLoginBlock $block) => self::MAX_FAILURES + 1 - $block->failed_attempts, $blocks)));
}
private static function recordOne(string $kind, string $identifier, string $ip, string $username, ?string $userAgent): AdminLoginBlock
{
return DB::transaction(function () use ($kind, $identifier, $ip, $username, $userAgent) {
AdminLoginBlock::query()->insertOrIgnore([
'kind' => $kind, 'identifier' => $identifier, 'created_at' => now(), 'updated_at' => now(),
]);
$block = AdminLoginBlock::where(['kind' => $kind, 'identifier' => $identifier])->lockForUpdate()->firstOrFail();
$windowExpired = $block->last_failed_at === null
|| $block->last_failed_at->lt(now()->subMinutes(self::BLOCK_MINUTES));
$attempts = ($windowExpired && ! $block->isBlocked() ? 0 : $block->failed_attempts) + 1;
$block->update([
'failed_attempts' => $attempts,
'last_username' => mb_substr($username, 0, 191),
'last_ip' => $ip,
'user_agent' => $userAgent ? mb_substr($userAgent, 0, 500) : null,
'last_failed_at' => now(),
'blocked_until' => $attempts > self::MAX_FAILURES
? now()->addMinutes(self::BLOCK_MINUTES)
: $block->blocked_until,
]);
return $block;
});
}
private static function accountKey(string $username): string
{
return mb_strtolower(mb_substr(trim($username), 0, 191));
}
}