81 lines
2.0 KiB
PHP
81 lines
2.0 KiB
PHP
<?php
|
|
declare(strict_types=1);
|
|
|
|
namespace Core\Services;
|
|
|
|
class Auth
|
|
{
|
|
private const SESSION_KEY = 'admin_id';
|
|
private const SESSION_ROLE_KEY = 'admin_role';
|
|
private const SESSION_NAME_KEY = 'admin_name';
|
|
|
|
public static function init(): void
|
|
{
|
|
if (session_status() !== PHP_SESSION_ACTIVE) {
|
|
$secure = !empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off';
|
|
session_start([
|
|
'cookie_httponly' => true,
|
|
'cookie_secure' => $secure,
|
|
'cookie_samesite' => 'Lax',
|
|
'use_strict_mode' => 1,
|
|
]);
|
|
}
|
|
}
|
|
|
|
public static function check(): bool
|
|
{
|
|
self::init();
|
|
return isset($_SESSION[self::SESSION_KEY]);
|
|
}
|
|
|
|
public static function id(): int
|
|
{
|
|
self::init();
|
|
return (int)($_SESSION[self::SESSION_KEY] ?? 0);
|
|
}
|
|
|
|
public static function login(int $adminId, string $role = 'admin', string $name = ''): void
|
|
{
|
|
self::init();
|
|
session_regenerate_id(true);
|
|
$_SESSION[self::SESSION_KEY] = $adminId;
|
|
$_SESSION[self::SESSION_ROLE_KEY] = $role;
|
|
if ($name !== '') {
|
|
$_SESSION[self::SESSION_NAME_KEY] = $name;
|
|
}
|
|
}
|
|
|
|
public static function logout(): void
|
|
{
|
|
self::init();
|
|
unset($_SESSION[self::SESSION_KEY]);
|
|
unset($_SESSION[self::SESSION_ROLE_KEY]);
|
|
unset($_SESSION[self::SESSION_NAME_KEY]);
|
|
}
|
|
|
|
public static function role(): string
|
|
{
|
|
self::init();
|
|
return (string)($_SESSION[self::SESSION_ROLE_KEY] ?? 'admin');
|
|
}
|
|
|
|
public static function name(): string
|
|
{
|
|
self::init();
|
|
return (string)($_SESSION[self::SESSION_NAME_KEY] ?? 'Admin');
|
|
}
|
|
|
|
public static function hasRole(array $roles): bool
|
|
{
|
|
return in_array(self::role(), $roles, true);
|
|
}
|
|
|
|
public static function can(string $permission): bool
|
|
{
|
|
if (!self::check()) {
|
|
return false;
|
|
}
|
|
return Permissions::can(self::role(), $permission);
|
|
}
|
|
}
|