<?php
declare(strict_types=1);
namespace App\Service\Auth;
use App\Api\BrcBackend\BrcClient;
use App\Api\BrcBackend\DTO\Credentials;
use Symfony\Component\HttpFoundation\Session\SessionInterface;
use GuzzleHttp\Exception\GuzzleException;
final class UserAuthManager
{
private const KEY_TOKEN = 'brc.auth.token';
private const KEY_EXPIRES = 'brc.auth.expires_at';
private SessionInterface $session;
private BrcClient $client;
/**
* @param SessionInterface $session
* @param BrcClient $client
*/
public function __construct(SessionInterface $session, BrcClient $client)
{
$this->session = $session;
$this->client = $client;
}
/**
* @param Credentials $dto
*
* @return void
*
* @throws GuzzleException
*/
public function login(Credentials $dto): void
{
$authData = $this->client->login($dto);
$this->session->set(self::KEY_TOKEN, $authData->getToken());
$this->session->set(self::KEY_EXPIRES, $authData->getExpiresAt());
}
/**
* @return string|null
*/
public function getToken(): ?string
{
return $this->session->get(self::KEY_TOKEN);
}
/**
* @return int|null
*/
public function getExpiresAt(): ?int
{
return $this->session->get(self::KEY_EXPIRES);
}
/**
* @return bool
*/
public function isAuthenticated(): bool
{
$token = $this->getToken();
$expires = $this->getExpiresAt();
return $token !== null
&& $expires !== null
&& $expires > time();
}
/**
* @return void
*/
public function clear(): void
{
$this->session->remove(self::KEY_TOKEN);
$this->session->remove(self::KEY_EXPIRES);
}
}