65 lines
1.4 KiB
PHP
65 lines
1.4 KiB
PHP
<?php
|
|
|
|
|
|
namespace Venom\Security;
|
|
|
|
use \RuntimeException;
|
|
use Venom\Core\Config;
|
|
use Venom\Models\User;
|
|
|
|
class Security
|
|
{
|
|
private static ?Security $instance = null;
|
|
private ?User $user;
|
|
|
|
public function __construct()
|
|
{
|
|
$this->user = new User();
|
|
$this->user->loadUser();
|
|
}
|
|
|
|
public static function get(): Security
|
|
{
|
|
if (self::$instance === null) {
|
|
self::$instance = new self();
|
|
}
|
|
return self::$instance;
|
|
}
|
|
|
|
public function hasRole(string $role): bool
|
|
{
|
|
return $this->user->hasRole($role);
|
|
}
|
|
|
|
public function hasRoles(array $roles): bool
|
|
{
|
|
foreach ($roles as $role) {
|
|
if (!$this->user->hasRole($role)) {
|
|
return false;
|
|
}
|
|
}
|
|
return true;
|
|
}
|
|
|
|
public function login(): void
|
|
{
|
|
if ($this->user->isLoaded()) {
|
|
throw new RuntimeException('Try to re-login!');
|
|
}
|
|
$sec = Config::getInstance()->getSecurity();
|
|
$login = new $sec->securityClass($this->user);
|
|
if ($login instanceof Login) {
|
|
if (!$login->checkCredentials() || !$login->login()) {
|
|
http_response_code(401);
|
|
}
|
|
$login->redirect();
|
|
}
|
|
}
|
|
|
|
public function logout(): void
|
|
{
|
|
unset($_SESSION['userID']);
|
|
$this->user = new User();
|
|
}
|
|
}
|