v2board/app/Services/AuthService.php

105 lines
2.8 KiB
PHP
Raw Normal View History

2022-12-13 12:29:23 +08:00
<?php
namespace App\Services;
2022-12-15 15:53:25 +08:00
use App\Utils\CacheKey;
use App\Utils\Helper;
2022-12-13 12:29:23 +08:00
use Firebase\JWT\JWT;
use Firebase\JWT\Key;
use App\Models\User;
use Illuminate\Support\Facades\Cache;
2022-12-15 15:53:25 +08:00
use Illuminate\Http\Request;
2022-12-13 12:29:23 +08:00
class AuthService
{
private $user;
2022-12-18 15:03:23 +08:00
public function __construct(User $user)
2022-12-13 12:29:23 +08:00
{
$this->user = $user;
}
2022-12-15 15:53:25 +08:00
public function generateAuthData(Request $request)
2022-12-13 12:29:23 +08:00
{
2022-12-15 15:53:25 +08:00
$guid = Helper::guid();
$authData = JWT::encode([
'id' => $this->user->id,
'session' => $guid,
], config('app.key'), 'HS256');
self::addSession($this->user->id, $guid, [
2022-12-15 23:16:06 +08:00
'ip' => $request->ip(),
'login_at' => time(),
'ua' => $request->userAgent()
2022-12-15 15:53:25 +08:00
]);
2022-12-13 12:29:23 +08:00
return [
'token' => $this->user->token,
'is_admin' => $this->user->is_admin,
2022-12-15 15:53:25 +08:00
'auth_data' => $authData
2022-12-13 12:29:23 +08:00
];
}
public static function decryptAuthData($jwt)
{
try {
if (!Cache::has($jwt)) {
$data = (array)JWT::decode($jwt, new Key(config('app.key'), 'HS256'));
2022-12-15 15:53:25 +08:00
if (!self::checkSession($data['id'], $data['session'])) return false;
2022-12-13 12:29:23 +08:00
$user = User::select([
'id',
'email',
'is_admin',
'is_staff'
])
->find($data['id']);
if (!$user) return false;
Cache::put($jwt, $user->toArray(), 3600);
}
return Cache::get($jwt);
} catch (\Exception $e) {
return false;
}
}
2022-12-15 15:53:25 +08:00
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;
2022-12-18 16:06:51 +08:00
return true;
2022-12-15 15:53:25 +08:00
}
2022-12-15 16:05:31 +08:00
public function getSessions()
{
return (array)Cache::get(CacheKey::get("USER_SESSIONS", $this->user->id), []);
}
2022-12-18 16:06:51 +08:00
2023-02-03 23:39:31 +08:00
public function removeSession($sessionId)
2022-12-18 16:06:51 +08:00
{
$cacheKey = CacheKey::get("USER_SESSIONS", $this->user->id);
$sessions = (array)Cache::get($cacheKey, []);
unset($sessions[$sessionId]);
if (!Cache::put(
$cacheKey,
$sessions
)) return false;
return true;
}
2023-02-03 23:39:31 +08:00
public function removeAllSession()
{
$cacheKey = CacheKey::get("USER_SESSIONS", $this->user->id);
return Cache::forget($cacheKey);
}
2022-12-13 12:29:23 +08:00
}