You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
90 lines
2.3 KiB
PHP
90 lines
2.3 KiB
PHP
<?php
|
|
|
|
namespace App\Services\Auth;
|
|
|
|
use App\Models\User;
|
|
use App\Utils;
|
|
use App\Services\LoginSessionRevocationService;
|
|
|
|
class Cookie extends Base
|
|
{
|
|
private const LEGACY_COOKIE_NAMES = [
|
|
'uid', 'email', 'key', 'ip', 'expire_in', LoginSessionRevocationService::COOKIE_VERSION_NAME,
|
|
];
|
|
|
|
public function login($uid, $time)
|
|
{
|
|
$user = User::find($uid);
|
|
if ($user === null) {
|
|
return;
|
|
}
|
|
|
|
$now = time();
|
|
$expiresAt = $now + (int) $time;
|
|
$sessionVersion = LoginSessionRevocationService::currentVersion($user);
|
|
$token = SignedCookieSession::issue(
|
|
(int) $user->id,
|
|
$sessionVersion,
|
|
$expiresAt,
|
|
self::remoteAddress(),
|
|
$now
|
|
);
|
|
Utils\Cookie::set([
|
|
SignedCookieSession::COOKIE_NAME => $token,
|
|
], $expiresAt);
|
|
self::clearLegacyCookies();
|
|
}
|
|
|
|
public function getUser()
|
|
{
|
|
$claims = SignedCookieSession::verify(
|
|
(string) Utils\Cookie::get(SignedCookieSession::COOKIE_NAME),
|
|
self::remoteAddress()
|
|
);
|
|
if ($claims === null) {
|
|
return self::guest();
|
|
}
|
|
|
|
$user = User::find($claims['user_id']);
|
|
if ($user == null) {
|
|
return self::guest();
|
|
}
|
|
|
|
if (!LoginSessionRevocationService::snapshotMatches(
|
|
$claims['session_version'],
|
|
LoginSessionRevocationService::currentVersion($user)
|
|
)) {
|
|
return self::guest($user);
|
|
}
|
|
$user->isLogin = true;
|
|
return $user;
|
|
}
|
|
|
|
public function logout()
|
|
{
|
|
$time = time() - 1000;
|
|
Utils\Cookie::set([
|
|
SignedCookieSession::COOKIE_NAME => null,
|
|
], $time);
|
|
self::clearLegacyCookies($time);
|
|
}
|
|
|
|
private static function remoteAddress(): ?string
|
|
{
|
|
$address = isset($_SERVER['REMOTE_ADDR']) ? trim((string) $_SERVER['REMOTE_ADDR']) : '';
|
|
return $address === '' ? null : $address;
|
|
}
|
|
|
|
private static function guest(?User $user = null): User
|
|
{
|
|
$user = $user ?? new User();
|
|
$user->isLogin = false;
|
|
return $user;
|
|
}
|
|
|
|
private static function clearLegacyCookies(?int $time = null): void
|
|
{
|
|
Utils\Cookie::set(array_fill_keys(self::LEGACY_COOKIE_NAMES, null), $time ?? time() - 1000);
|
|
}
|
|
}
|