<?php
/*
* Author: Dominik Piekarski <code@dompie.de>
* Created at: 2020/08/06 12:16
*/
declare(strict_types=1);
namespace App\EventSubscriber;
use App\Dictionary\SessionVars;
use App\Security\ApiUser;
use Frivol\Common\Service\CacheService;
use App\Service\Client\SecurityService;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpFoundation\Cookie;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Http\Event\LogoutEvent;
class LogoutSubscriber implements EventSubscriberInterface
{
protected SecurityService $service;
protected CacheService $cacheService;
public function __construct(CacheService $cacheService, SecurityService $service)
{
$this->cacheService = $cacheService;
$this->service = $service;
}
public static function getSubscribedEvents()
{
return [
LogoutEvent::class => [
['onLogoutCallApi', 1],
['onLogoutClearMemberOnlineSidebarCache', 1],
['onLogoutDeleteLocalStorage', 3]
]
];
}
/**
* @param LogoutEvent $event
* @return void
* @throws \Psr\Cache\InvalidArgumentException
*/
public function onLogoutClearMemberOnlineSidebarCache(LogoutEvent $event)
{
$this->cacheService->clearMemberOnlineCache();
}
public function onLogoutCallApi(LogoutEvent $event)
{
$token = $event->getToken();
/** @var $user ApiUser */
$user = $token?->getUser();
if (!$user instanceof ApiUser || $user->getMemberId() === null) {
return;
}
$this->service->logout($user->getMemberId());
}
/**
* @param LogoutEvent $event
*/
public function onLogoutDeleteLocalStorage(LogoutEvent $event)
{
$cookie = $this->getClearLocalStorageCookie($event->getRequest());
$event->getResponse()->headers->setCookie($cookie);
$event->getResponse()->headers->clearCookie(SessionVars::COOKIE_CHAT_APP_CONFIG);
$event->getResponse()->headers->clearCookie(SessionVars::COOKIE_USERTOKEN);
}
/**
* Copied to LoginSubscriber aswell
*
* @param Request $request
* @return Cookie
*/
protected function getClearLocalStorageCookie(Request $request): Cookie
{
$name = SessionVars::COOKIE_CLEAR_LOCALSTORAGE;
return new Cookie($name, '1', time() + 10, '/', null,
$request->isSecure(), false, false);
}
}