74 lines
1.8 KiB
PHP
74 lines
1.8 KiB
PHP
<?php
|
|
|
|
namespace App\Auth;
|
|
|
|
use App\Models\User;
|
|
use Illuminate\Http\Request;
|
|
use Illuminate\Support\Facades\Cookie;
|
|
use Illuminate\Support\Facades\Crypt;
|
|
|
|
class TrustedStaffDevice
|
|
{
|
|
public const COOKIE = 'luf_staff_mfa';
|
|
|
|
public const DAYS = 30;
|
|
|
|
public function remember(User $user): void
|
|
{
|
|
Cookie::queue(cookie(
|
|
self::COOKIE,
|
|
$this->token($user),
|
|
self::DAYS * 24 * 60,
|
|
'/',
|
|
null,
|
|
request()->isSecure(),
|
|
true,
|
|
false,
|
|
'lax',
|
|
));
|
|
}
|
|
|
|
public function token(User $user): string
|
|
{
|
|
return Crypt::encryptString(json_encode([
|
|
'user' => $user->getKey(),
|
|
'until' => now()->addDays(self::DAYS)->getTimestamp(),
|
|
'secret' => $this->fingerprint($user),
|
|
], JSON_THROW_ON_ERROR));
|
|
}
|
|
|
|
public function isTrusted(User $user, ?Request $request = null): bool
|
|
{
|
|
$request ??= request();
|
|
$token = $request->cookies->get(self::COOKIE);
|
|
|
|
if (! is_string($token) || $token === '') {
|
|
return false;
|
|
}
|
|
|
|
try {
|
|
$payload = json_decode(Crypt::decryptString($token), true, 8, JSON_THROW_ON_ERROR);
|
|
} catch (\Throwable) {
|
|
return false;
|
|
}
|
|
|
|
if (! is_array($payload)) {
|
|
return false;
|
|
}
|
|
|
|
$until = $payload['until'] ?? null;
|
|
$fingerprint = $payload['secret'] ?? null;
|
|
|
|
return (int) ($payload['user'] ?? 0) === (int) $user->getKey()
|
|
&& is_int($until)
|
|
&& $until >= now()->getTimestamp()
|
|
&& is_string($fingerprint)
|
|
&& hash_equals($this->fingerprint($user), $fingerprint);
|
|
}
|
|
|
|
private function fingerprint(User $user): string
|
|
{
|
|
return hash('sha256', (string) $user->getAppAuthenticationSecret());
|
|
}
|
|
}
|