This commit is contained in:
MeghdadFadaee committed 2026-09-05 15:54:33 +03:30
commit 8416b02b4f
54 files changed
+4604

No files matched your search

+89
View File
@@ -0,0 +1,89 @@
<?php
declare(strict_types=1);
namespace App\Security;
use App\Http\HttpException;
final class Session
{
public function __construct(private readonly string $directory, private readonly int $lifetime)
{
}
public function start(bool $https): void
{
if (!is_dir($this->directory) || !is_writable($this->directory)) {
throw new \RuntimeException('Session storage is unavailable.');
}
ini_set('session.use_strict_mode', '1');
ini_set('session.use_only_cookies', '1');
ini_set('session.gc_maxlifetime', (string) $this->lifetime);
session_name('app_session');
session_save_path($this->directory);
session_set_cookie_params([
'lifetime' => 0, 'path' => '/', 'secure' => $https,
'httponly' => true, 'samesite' => $https ? 'None' : 'Lax',
]);
if (!session_start()) {
throw new \RuntimeException('Could not start session.');
}
$_SESSION['csrf'] ??= bin2hex(random_bytes(32));
if (isset($_SESSION['expires']) && $_SESSION['expires'] <= time()) {
$this->logout();
}
}
public function csrf(): string
{
return $_SESSION['csrf'];
}
public function user(): array
{
if (!isset($_SESSION['user'], $_SESSION['expires']) || $this->expiresAt() <= time()) {
throw new HttpException('ابتدا از داخل ایتا وارد شوید و هویت خود را تأیید کنید.', 401);
}
return $_SESSION['user'];
}
public function launch(): array
{
return $_SESSION['launch'] ?? [];
}
public function expiresAt(): int
{
return $_SESSION['expires'] ?? 0;
}
public function isRemoteVerified(): bool
{
return $_SESSION['remote_verified'] ?? false;
}
public function markRemoteVerified(): void
{
$_SESSION['remote_verified'] = true;
}
public function login(array $user, array $launch, bool $remoteVerified): void
{
session_regenerate_id(true);
$_SESSION['user'] = $user;
$_SESSION['launch'] = $launch;
$_SESSION['expires'] = time() + $this->lifetime;
$_SESSION['remote_verified'] = $remoteVerified;
}
public function logout(): void
{
$_SESSION = ['csrf' => bin2hex(random_bytes(32))];
session_regenerate_id(true);
}
public function close(): void
{
session_write_close();
}
}