87 lines
2.0 KiB
PHP
87 lines
2.0 KiB
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
namespace App\Core;
|
|
|
|
use App\Repositories\AdminRepository;
|
|
|
|
final class Auth
|
|
{
|
|
private const SESSION_ADMIN_ID = 'admin_id';
|
|
|
|
public static function start(): void
|
|
{
|
|
if (session_status() === PHP_SESSION_ACTIVE) {
|
|
return;
|
|
}
|
|
|
|
session_name('rybstock_admin');
|
|
session_start();
|
|
}
|
|
|
|
public static function requireAdmin(): void
|
|
{
|
|
self::start();
|
|
|
|
if (self::admin() !== null) {
|
|
return;
|
|
}
|
|
|
|
$next = $_SERVER['REQUEST_URI'] ?? '/admin/';
|
|
header('Location: /admin/login.php?next=' . rawurlencode($next));
|
|
exit;
|
|
}
|
|
|
|
/**
|
|
* @return array<string, mixed>|null
|
|
*/
|
|
public static function admin(): ?array
|
|
{
|
|
self::start();
|
|
$adminId = (int) ($_SESSION[self::SESSION_ADMIN_ID] ?? 0);
|
|
|
|
if ($adminId <= 0) {
|
|
return null;
|
|
}
|
|
|
|
$admin = (new AdminRepository())->findActiveById($adminId);
|
|
|
|
if ($admin === null) {
|
|
unset($_SESSION[self::SESSION_ADMIN_ID]);
|
|
}
|
|
|
|
return $admin;
|
|
}
|
|
|
|
public static function attempt(string $email, string $password): bool
|
|
{
|
|
self::start();
|
|
$repository = new AdminRepository();
|
|
$admin = $repository->findActiveByEmail($email);
|
|
|
|
if ($admin === null || !password_verify($password, (string) $admin['password_hash'])) {
|
|
return false;
|
|
}
|
|
|
|
session_regenerate_id(true);
|
|
$_SESSION[self::SESSION_ADMIN_ID] = (int) $admin['id'];
|
|
$repository->touchLastLogin((int) $admin['id']);
|
|
|
|
return true;
|
|
}
|
|
|
|
public static function logout(): void
|
|
{
|
|
self::start();
|
|
$_SESSION = [];
|
|
|
|
if (ini_get('session.use_cookies')) {
|
|
$params = session_get_cookie_params();
|
|
setcookie(session_name(), '', time() - 42000, $params['path'], $params['domain'], (bool) $params['secure'], (bool) $params['httponly']);
|
|
}
|
|
|
|
session_destroy();
|
|
}
|
|
}
|