src/EventSubscriber/LogoutSubscriber.php line 65

Open in your IDE?
  1. <?php
  2. /*
  3.  * Author: Dominik Piekarski <code@dompie.de>
  4.  * Created at: 2020/08/06 12:16
  5.  */
  6. declare(strict_types=1);
  7. namespace App\EventSubscriber;
  8. use App\Dictionary\SessionVars;
  9. use App\Security\ApiUser;
  10. use Frivol\Common\Service\CacheService;
  11. use App\Service\Client\SecurityService;
  12. use Symfony\Component\EventDispatcher\EventSubscriberInterface;
  13. use Symfony\Component\HttpFoundation\Cookie;
  14. use Symfony\Component\HttpFoundation\Request;
  15. use Symfony\Component\Security\Http\Event\LogoutEvent;
  16. class LogoutSubscriber implements EventSubscriberInterface
  17. {
  18.     protected SecurityService $service;
  19.     protected CacheService $cacheService;
  20.     public function __construct(CacheService $cacheServiceSecurityService $service)
  21.     {
  22.         $this->cacheService $cacheService;
  23.         $this->service $service;
  24.     }
  25.     public static function getSubscribedEvents()
  26.     {
  27.         return [
  28.             LogoutEvent::class => [
  29.                 ['onLogoutCallApi'1],
  30.                 ['onLogoutClearMemberOnlineSidebarCache'1],
  31.                 ['onLogoutDeleteLocalStorage'3]
  32.             ]
  33.         ];
  34.     }
  35.     /**
  36.      * @param LogoutEvent $event
  37.      * @return void
  38.      * @throws \Psr\Cache\InvalidArgumentException
  39.      */
  40.     public function onLogoutClearMemberOnlineSidebarCache(LogoutEvent $event)
  41.     {
  42.         $this->cacheService->clearMemberOnlineCache();
  43.     }
  44.     public function onLogoutCallApi(LogoutEvent $event)
  45.     {
  46.         $token $event->getToken();
  47.         /** @var $user ApiUser */
  48.         $user $token?->getUser();
  49.         if (!$user instanceof ApiUser || $user->getMemberId() === null) {
  50.             return;
  51.         }
  52.         $this->service->logout($user->getMemberId());
  53.     }
  54.     /**
  55.      * @param LogoutEvent $event
  56.      */
  57.     public function onLogoutDeleteLocalStorage(LogoutEvent $event)
  58.     {
  59.         $cookie $this->getClearLocalStorageCookie($event->getRequest());
  60.         $event->getResponse()->headers->setCookie($cookie);
  61.         $event->getResponse()->headers->clearCookie(SessionVars::COOKIE_CHAT_APP_CONFIG);
  62.         $event->getResponse()->headers->clearCookie(SessionVars::COOKIE_USERTOKEN);
  63.     }
  64.     /**
  65.      * Copied to LoginSubscriber aswell
  66.      *
  67.      * @param Request $request
  68.      * @return Cookie
  69.      */
  70.     protected function getClearLocalStorageCookie(Request $request): Cookie
  71.     {
  72.         $name SessionVars::COOKIE_CLEAR_LOCALSTORAGE;
  73.         return new Cookie($name'1'time() + 10'/'null,
  74.             $request->isSecure(), falsefalse);
  75.     }
  76. }