src/Service/Auth/UserAuthManager.php line 58

Open in your IDE?
  1. <?php
  2. declare(strict_types=1);
  3. namespace App\Service\Auth;
  4. use App\Api\BrcBackend\BrcClient;
  5. use App\Api\BrcBackend\DTO\Credentials;
  6. use Symfony\Component\HttpFoundation\Session\SessionInterface;
  7. use GuzzleHttp\Exception\GuzzleException;
  8. final class UserAuthManager
  9. {
  10.     private const KEY_TOKEN 'brc.auth.token';
  11.     private const KEY_EXPIRES 'brc.auth.expires_at';
  12.     private SessionInterface $session;
  13.     private BrcClient $client;
  14.     /**
  15.      * @param SessionInterface $session
  16.      * @param BrcClient $client
  17.      */
  18.     public function __construct(SessionInterface $sessionBrcClient $client)
  19.     {
  20.         $this->session $session;
  21.         $this->client $client;
  22.     }
  23.     /**
  24.      * @param Credentials $dto
  25.      *
  26.      * @return void
  27.      *
  28.      * @throws GuzzleException
  29.      */
  30.     public function login(Credentials $dto): void
  31.     {
  32.         $authData $this->client->login($dto);
  33.         $this->session->set(self::KEY_TOKEN$authData->getToken());
  34.         $this->session->set(self::KEY_EXPIRES$authData->getExpiresAt());
  35.     }
  36.     /**
  37.      * @return string|null
  38.      */
  39.     public function getToken(): ?string
  40.     {
  41.         return $this->session->get(self::KEY_TOKEN);
  42.     }
  43.     /**
  44.      * @return int|null
  45.      */
  46.     public function getExpiresAt(): ?int
  47.     {
  48.         return $this->session->get(self::KEY_EXPIRES);
  49.     }
  50.     /**
  51.      * @return bool
  52.      */
  53.     public function isAuthenticated(): bool
  54.     {
  55.         $token $this->getToken();
  56.         $expires $this->getExpiresAt();
  57.         return $token !== null
  58.             && $expires !== null
  59.             && $expires time();
  60.     }
  61.     /**
  62.      * @return void
  63.      */
  64.     public function clear(): void
  65.     {
  66.         $this->session->remove(self::KEY_TOKEN);
  67.         $this->session->remove(self::KEY_EXPIRES);
  68.     }
  69. }