src/EventListener/AuthTokenSubscriber.php line 27

Open in your IDE?
  1. <?php
  2. namespace App\EventListener;
  3. use Doctrine\DBAL\Connection;
  4. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  5. use Symfony\Component\HttpKernel\Event\RequestEvent;
  6. class AuthTokenSubscriber implements EventSubscriberInterface
  7. {
  8.     /** @var Connection */
  9.     private $db;
  10.     public function __construct(Connection $db) { $this->db $db; }
  11.     public static function getSubscribedEvents(): array
  12.     {
  13.         return [RequestEvent::class => 'onKernelRequest'];
  14.     }
  15.     public function onKernelRequest(RequestEvent $event): void
  16.     {
  17.         $req      $event->getRequest();
  18.         $session  $req->getSession();
  19.         $tokenRaw $req->cookies->get('auth_token');
  20.         if ($session->has('hash') || $tokenRaw === null) {
  21.             return;                                // уже залогинен или cookie нет
  22.         }
  23.         /* фильтруем мусор/атаки  */
  24.         if (!\is_string($tokenRaw) || !\preg_match('/^[a-f0-9]{64}$/'$tokenRaw)) {
  25.             return;
  26.         }
  27.         $tokenHash hash('sha256'$tokenRaw);
  28.         $row $this->db->fetchAssociative(
  29.             'SELECT hash FROM users WHERE auth_token_hash = ?', [$tokenHash]
  30.         );
  31.         if ($row) {
  32.             $session->migrate(true);
  33.             $session->set('hash'$row['hash']);
  34.         }
  35.     }
  36. }