You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

64 lines
1.4 KiB

<?php
declare(strict_types=1);
namespace Silex\Security;
use Silex\Gateway\UserGateway;
use Silex\Model\User;
const USER = 'USER';
class Security
{
private array $session;
private UserGateway $userGateway;
private ?User $user = null;
public function __construct(UserGateway $userGateway, array &$session)
{
$this->userGateway = $userGateway;
$this->session = &$session;
}
public function initLogin(string $login, string $rawPassword): bool
{
$user = $this->userGateway->getByLogin($login);
if ($user === null || !password_verify($rawPassword, $user->getPasswordHash())) {
return false;
}
$this->session[USER] = $user->getId();
$this->user = $user;
return true;
}
public function logout()
{
$this->user = null;
unset($this->session[USER]);
}
public function getCurrentUserId(): ?int
{
return $this->session[USER] ?? null;
}
public function getCurrentUser(): ?User
{
if (!empty($this->session[USER]) && $this->user === null) {
$this->user = $this->userGateway->getById($this->session[USER]);
}
return $this->user;
}
public function register(User $user): ?User
{
if (!$this->userGateway->insert($user)) {
return null;
}
$this->session[USER] = $user->getId();
$this->user = $user;
return $user;
}
}