Files
zyt/identity-admin/server/app/service/shared/SessionStore.php
T
2026-11-11 13:53:14 +08:00

127 lines
5.1 KiB
PHP

<?php
declare(strict_types=1);
namespace app\service\shared;
use app\exception\ApiError;
use app\service\Settings;
/** Bridge sessions never contain submitted account passwords. */
class SessionStore
{
private string $directory;
private \Closure $clock;
public function __construct(?string $directory = null, ?callable $clock = null)
{
$this->directory = $directory ?? Settings::runtimePath() . '/shared-sessions';
$this->clock = $clock === null ? static fn (): int => time() : \Closure::fromCallable($clock);
}
public function create(string $source, string $sourceToken, int $adminId, int $ttl): string
{
return $this->locked(function () use ($source, $sourceToken, $adminId, $ttl): string {
foreach (glob($this->directory . '/*.json') ?: [] as $expiredPath) {
$expired = $this->read($expiredPath);
if ($expired && (int) ($expired['expire_time'] ?? 0) <= ($this->clock)()) { unlink($expiredPath); }
}
$token = bin2hex(random_bytes(32));
$record = ['source' => $source, 'source_token' => $sourceToken, 'admin_id' => $adminId,
'expire_time' => ($this->clock)() + $ttl];
$path = $this->path($token);
$file = fopen($path, 'x+b');
if (!$file) { throw new ApiError(503, '无法保存登录会话'); }
try {
chmod($path, 0600);
$json = json_encode($record, JSON_THROW_ON_ERROR);
if (fwrite($file, $json) !== strlen($json) || !fflush($file)) {
throw new ApiError(503, '无法保存登录会话');
}
} catch (\Throwable $error) {
fclose($file);
unlink($path);
throw $error;
}
fclose($file);
return $token;
});
}
public function resolve(string $token, string $source): array
{
$this->validateToken($token);
return $this->resolveReference(hash('sha256', $token), $source);
}
/** 仅供服务端短期授权码引用会话,授权码不再复制 bearer 或上游 token。 */
public function resolveReference(string $reference, string $source): array
{
if (!preg_match('/^[a-f0-9]{64}$/D', $reference)) { throw new ApiError(401, '登录会话无效'); }
return $this->locked(function () use ($reference, $source): array {
$path = $this->directory . '/' . $reference . '.json';
$record = $this->read($path);
if (!$record || ($record['source'] ?? '') !== $source || (int) ($record['expire_time'] ?? 0) <= ($this->clock)()
|| !is_string($record['source_token'] ?? null) || $record['source_token'] === '' || (int) ($record['admin_id'] ?? 0) < 1) {
if (is_file($path) && !is_link($path)) { unlink($path); }
throw new ApiError(401, '登录已失效,请重新登录');
}
return $record;
});
}
public function revoke(string $token): void
{
$this->validateToken($token);
$this->locked(function () use ($token): void {
$path = $this->path($token);
if (is_file($path) && !is_link($path)) { unlink($path); }
});
}
public function revokeAll(string $source, int $adminId): void
{
$this->locked(function () use ($source, $adminId): void {
foreach (glob($this->directory . '/*.json') ?: [] as $path) {
$record = $this->read($path);
if ($record && ($record['source'] ?? '') === $source && (int) ($record['admin_id'] ?? 0) === $adminId) {
unlink($path);
}
}
});
}
private function path(string $token): string
{
return $this->directory . '/' . hash('sha256', $token) . '.json';
}
private function validateToken(string $token): void
{
if (!preg_match('/^[a-f0-9]{64}$/D', $token)) { throw new ApiError(401, '请先登录'); }
}
private function read(string $path): ?array
{
if (!is_file($path) || is_link($path) || filesize($path) > 8192) { return null; }
try { $value = json_decode((string) file_get_contents($path), true, 8, JSON_THROW_ON_ERROR); }
catch (\JsonException $error) { return null; }
return is_array($value) ? $value : null;
}
private function locked(callable $callback): mixed
{
if (is_link($this->directory) || (!is_dir($this->directory) && !mkdir($this->directory, 0700, true) && !is_dir($this->directory))) {
throw new ApiError(503, '登录会话目录不可用');
}
chmod($this->directory, 0700);
$path = $this->directory . '/.lock';
if (is_link($path)) { throw new ApiError(503, '登录会话目录不可用'); }
$lock = fopen($path, 'c+b');
if (!$lock) { throw new ApiError(503, '无法锁定登录会话'); }
chmod($path, 0600);
try {
if (!flock($lock, LOCK_EX)) { throw new ApiError(503, '无法锁定登录会话'); }
return $callback();
} finally { flock($lock, LOCK_UN); fclose($lock); }
}
}