70 lines
1.5 KiB
PHP
70 lines
1.5 KiB
PHP
<?php
|
|
|
|
namespace App\Services;
|
|
|
|
use App\Models\User;
|
|
use App\Support\PasswordHasher;
|
|
|
|
class AuthService
|
|
{
|
|
private static ?self $instance = null;
|
|
private ?User $user = null;
|
|
|
|
private function __construct()
|
|
{
|
|
if (session_status() === PHP_SESSION_NONE) {
|
|
session_start();
|
|
}
|
|
|
|
if (isset($_SESSION['user_id'])) {
|
|
$this->user = User::find((int) $_SESSION['user_id']);
|
|
}
|
|
}
|
|
|
|
public static function getInstance(): self
|
|
{
|
|
if (self::$instance === null) {
|
|
self::$instance = new self();
|
|
}
|
|
|
|
return self::$instance;
|
|
}
|
|
|
|
public function attempt(string $email, string $password): bool
|
|
{
|
|
$user = User::findByEmail($email);
|
|
if (!$user || !$user->is_active) {
|
|
return false;
|
|
}
|
|
|
|
if (!PasswordHasher::verify($password, $user->pass_hash)) {
|
|
return false;
|
|
}
|
|
|
|
$_SESSION['user_id'] = $user->id;
|
|
$this->user = $user;
|
|
return true;
|
|
}
|
|
|
|
public function logout(): void
|
|
{
|
|
$_SESSION = [];
|
|
if (ini_get('session.use_cookies')) {
|
|
$params = session_get_cookie_params();
|
|
setcookie(session_name(), '', time() - 42000, $params['path'], $params['domain'], $params['secure'], $params['httponly']);
|
|
}
|
|
session_destroy();
|
|
$this->user = null;
|
|
}
|
|
|
|
public function check(): bool
|
|
{
|
|
return $this->user !== null;
|
|
}
|
|
|
|
public function user(): ?User
|
|
{
|
|
return $this->user;
|
|
}
|
|
}
|