mirror of
https://github.com/v2board/v2board.git
synced 2025-06-16 06:37:53 +08:00
update: multiple session
This commit is contained in:
@ -2,10 +2,13 @@
|
||||
|
||||
namespace App\Services;
|
||||
|
||||
use App\Utils\CacheKey;
|
||||
use App\Utils\Helper;
|
||||
use Firebase\JWT\JWT;
|
||||
use Firebase\JWT\Key;
|
||||
use App\Models\User;
|
||||
use Illuminate\Support\Facades\Cache;
|
||||
use Illuminate\Http\Request;
|
||||
|
||||
class AuthService
|
||||
{
|
||||
@ -16,26 +19,29 @@ class AuthService
|
||||
$this->user = $user;
|
||||
}
|
||||
|
||||
public function generateAuthData($utm)
|
||||
public function generateAuthData(Request $request)
|
||||
{
|
||||
$guid = Helper::guid();
|
||||
$authData = JWT::encode([
|
||||
'id' => $this->user->id,
|
||||
'session' => $guid,
|
||||
], config('app.key'), 'HS256');
|
||||
self::addSession($this->user->id, $guid, [
|
||||
'ip' => $request->ip()
|
||||
]);
|
||||
return [
|
||||
'token' => $this->user->token,
|
||||
'is_admin' => $this->user->is_admin,
|
||||
'auth_data' => JWT::encode([
|
||||
'expired_at' => time() + 3600,
|
||||
'id' => $this->user->id,
|
||||
'utm' => $utm,
|
||||
], config('app.key'), 'HS256')
|
||||
'auth_data' => $authData
|
||||
];
|
||||
}
|
||||
|
||||
|
||||
public static function decryptAuthData($jwt)
|
||||
{
|
||||
try {
|
||||
if (!Cache::has($jwt)) {
|
||||
$data = (array)JWT::decode($jwt, new Key(config('app.key'), 'HS256'));
|
||||
if ($data['expired_at'] < time()) return false;
|
||||
if (!self::checkSession($data['id'], $data['session'])) return false;
|
||||
$user = User::select([
|
||||
'id',
|
||||
'email',
|
||||
@ -51,4 +57,22 @@ class AuthService
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private static function checkSession($userId, $session)
|
||||
{
|
||||
$sessions = (array)Cache::get(CacheKey::get("USER_SESSIONS", $userId)) ?? [];
|
||||
if (!in_array($session, array_keys($sessions))) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
private static function addSession($userId, $guid, $meta)
|
||||
{
|
||||
$cacheKey = CacheKey::get("USER_SESSIONS", $userId);
|
||||
$sessions = (array)Cache::get($cacheKey, []);
|
||||
$sessions[$guid] = $meta;
|
||||
if (!Cache::put(
|
||||
$cacheKey,
|
||||
$sessions
|
||||
)) return false;
|
||||
}
|
||||
}
|
||||
|
Reference in New Issue
Block a user