75 lines
1.5 KiB
PHP
75 lines
1.5 KiB
PHP
<?php
|
|
|
|
declare(strict_types=1);
|
|
|
|
namespace App\Core;
|
|
|
|
use App\Models\User;
|
|
|
|
class Auth
|
|
{
|
|
private static ?array $cachedUser = null;
|
|
|
|
public static function init(): void
|
|
{
|
|
if (session_status() === PHP_SESSION_NONE) {
|
|
session_start();
|
|
}
|
|
}
|
|
|
|
public static function check(): bool
|
|
{
|
|
self::init();
|
|
return !empty($_SESSION['user_id']);
|
|
}
|
|
|
|
public static function id(): ?int
|
|
{
|
|
self::init();
|
|
return $_SESSION['user_id'] ?? null;
|
|
}
|
|
|
|
public static function user(): ?array
|
|
{
|
|
self::init();
|
|
if (!self::check()) {
|
|
return null;
|
|
}
|
|
|
|
if (self::$cachedUser === null) {
|
|
self::$cachedUser = User::find((int)$_SESSION['user_id']);
|
|
}
|
|
|
|
return self::$cachedUser;
|
|
}
|
|
|
|
public static function login(array $user): void
|
|
{
|
|
self::init();
|
|
$_SESSION['user_id'] = (int)$user['id'];
|
|
self::$cachedUser = $user;
|
|
}
|
|
|
|
public static function logout(): void
|
|
{
|
|
self::init();
|
|
unset($_SESSION['user_id']);
|
|
self::$cachedUser = null;
|
|
}
|
|
|
|
public static function attempt(string $identifier, string $password): bool
|
|
{
|
|
$user = User::findByIdentifier($identifier);
|
|
if (!$user) {
|
|
return false;
|
|
}
|
|
|
|
if (password_verify($password, $user['password_hash'])) {
|
|
self::login($user);
|
|
return true;
|
|
}
|
|
|
|
return false;
|
|
}
|
|
}
|