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.
virt/web/app/Services/Cloud/CloudSessionService.php

135 lines
5.6 KiB
PHP

<?php
namespace App\Services\Cloud;
use App\Models\CloudInstance;
use App\Models\CloudSession;
use App\Models\User;
use App\Services\Config;
use App\Services\Jwt;
use App\Services\RedisClient;
use App\Services\LoginSessionRevocationService;
final class CloudSessionService
{
private static function identity(): array
{
$driver = (string) Config::get('authDriver', 'cookie');
$names = match ($driver) {
'redis' => ['sid'], 'jwt' => ['token'], default => ['uid', 'key', 'ip', 'expire_in', 'login_session_version'],
};
$values = [];
foreach ($names as $name) {
$values[$name] = isset($_COOKIE[$name]) && is_string($_COOKIE[$name]) ? $_COOKIE[$name] : '';
}
return [$driver, $values, hash('sha256', json_encode([$driver, $values], JSON_THROW_ON_ERROR))];
}
public static function current(User $user): string
{
[$driver, $values, $fingerprint] = self::identity();
$version = LoginSessionRevocationService::currentVersion($user);
$session = CloudSession::where('fingerprint', $fingerprint)->first();
if ($session !== null) {
if ((int) $session->user_id !== (int) $user->id || !(bool) $session->active
|| (int) $session->version !== $version || (int) $session->expires_at <= time()) {
throw new CloudError('会话已失效,请重新登录', 401);
}
return $session->id;
}
$expiry = time() + 86400;
$reference = null;
if ($driver === 'redis') {
if (($values['sid'] ?? '') === '') {
throw new CloudError('会话已失效', 401);
}
$redis = new RedisClient();
$ttl = (int) $redis->getClient()->ttl($values['sid']);
if ($ttl <= 0) {
throw new CloudError('会话已失效', 401);
}
$expiry = time() + $ttl;
$reference = CloudSecrets::encrypt(['sid' => $values['sid']]);
} elseif ($driver === 'jwt') {
$claims = Jwt::decodeArray($values['token'] ?? '');
$expiry = (int) ($claims->expire_time ?? 0);
} else {
$expiry = (int) ($values['expire_in'] ?? 0);
}
if ($expiry <= time()) {
throw new CloudError('会话已失效', 401);
}
$session = new CloudSession();
$session->id = bin2hex(random_bytes(32));
$session->user_id = $user->id;
$session->version = $version;
$session->fingerprint = $fingerprint;
$session->auth_driver = $driver;
$session->auth_reference = $reference;
$session->active = 1;
$session->expires_at = $expiry;
$session->created_at = time();
try {
$session->save();
} catch (\Illuminate\Database\QueryException $exception) {
// Simultaneous first requests may race on the unique cookie fingerprint.
$existing = CloudSession::where('fingerprint', $fingerprint)->first();
if ($existing === null || !(bool) $existing->active || (int) $existing->version !== $version
|| (int) $existing->user_id !== (int) $user->id || (int) $existing->expires_at <= time()) {
throw $exception;
}
return $existing->id;
}
return $session->id;
}
public static function revokeCurrent(): void
{
if (!(new CloudSession())->getConnection()->getSchemaBuilder()->hasTable('cloud_sessions')) {
return;
}
[, , $fingerprint] = self::identity();
CloudSession::where('fingerprint', $fingerprint)->update(['active' => 0]);
}
public static function active(string $id, ?int $hostId = null, ?string $uuid = null): bool
{
$session = CloudSession::find($id);
if ($session === null || !(bool) $session->active || (int) $session->expires_at <= time()) {
return false;
}
$user = User::find($session->user_id);
if ($user === null || (int) $user->enable !== 1
|| (int) $session->version !== LoginSessionRevocationService::currentVersion($user)) {
return false;
}
if ($session->auth_driver === 'redis') {
$sid = CloudSecrets::decrypt((string) $session->auth_reference)['sid'] ?? '';
$value = (new RedisClient())->get($sid);
$decoded = LoginSessionRevocationService::decodeRedisSession($value);
if ($decoded === null || (int) $decoded['uid'] !== (int) $user->id
|| !LoginSessionRevocationService::snapshotMatches($decoded['version'], (int) $session->version)) {
return false;
}
}
if ($hostId !== null || $uuid !== null) {
$query = CloudInstance::where('host_id', $hostId)->where('uuid', $uuid)->where('status', '<>', 'deleted');
$superAdmin = (bool) $user->is_admin && in_array((int) $user->id,
array_map('intval', explode(',', (string) Config::get('super_admin'))), true);
if (!$superAdmin) {
$now = time();
$query->where('user_id', $user->id)
->where(function ($available) use ($now) {
$available->where('service_status', 'exempt')
->orWhere(function ($paid) use ($now) {
$paid->where('service_status', 'active')
->whereNotNull('expires_at')
->where('expires_at', '>', $now);
});
});
}
return $query->exists();
}
return true;
}
}