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.
75 lines
1.9 KiB
PHP
75 lines
1.9 KiB
PHP
<?php
|
|
|
|
namespace App\Services\Auth;
|
|
|
|
use App\Models\User;
|
|
use App\Utils;
|
|
use App\Services\Jwt;
|
|
use App\Services\LoginSessionRevocationService;
|
|
|
|
class JwtToken extends Base
|
|
{
|
|
public function login($uid, $time)
|
|
{
|
|
$user = User::find($uid);
|
|
if ($user === null) {
|
|
return;
|
|
}
|
|
|
|
$expireTime = time() + $time;
|
|
$ary = [
|
|
"uid" => $uid,
|
|
"expire_time" => $expireTime,
|
|
"session_version" => LoginSessionRevocationService::currentVersion($user),
|
|
];
|
|
$decode = Jwt::encode($ary);
|
|
Utils\Cookie::set([
|
|
//"uid" => $uid,
|
|
"token" => $decode
|
|
], $expireTime);
|
|
}
|
|
|
|
public function logout()
|
|
{
|
|
Utils\Cookie::set([
|
|
//"uid" => $uid,
|
|
"token" => ""
|
|
], time()-3600);
|
|
}
|
|
|
|
public function getUser()
|
|
{
|
|
$token = Utils\Cookie::get('token');
|
|
try {
|
|
$tokenInfo = Jwt::decodeArray($token);
|
|
} catch (\Throwable $exception) {
|
|
$user = new User();
|
|
$user->isLogin = false;
|
|
return $user;
|
|
}
|
|
|
|
$userId = isset($tokenInfo->uid) ? (int) $tokenInfo->uid : 0;
|
|
$expireTime = isset($tokenInfo->expire_time) ? (int) $tokenInfo->expire_time : 0;
|
|
$user = $userId > 0 ? User::find($userId) : null;
|
|
if ($user === null || $expireTime < time()) {
|
|
$user = $user ?: new User();
|
|
$user->isLogin = false;
|
|
return $user;
|
|
}
|
|
|
|
$sessionVersion = property_exists($tokenInfo, 'session_version')
|
|
? $tokenInfo->session_version
|
|
: null;
|
|
if (!LoginSessionRevocationService::snapshotMatches(
|
|
$sessionVersion,
|
|
LoginSessionRevocationService::currentVersion($user)
|
|
)) {
|
|
$user->isLogin = false;
|
|
return $user;
|
|
}
|
|
|
|
$user->isLogin = true;
|
|
return $user;
|
|
}
|
|
}
|