<?php
namespace App\Package\Admin\Tools\EventSubscriber\LogoutInactiveAdminSubscriber;
use Symfony\Component\EventDispatcher\EventSubscriberInterface,
Symfony\Component\HttpFoundation\RedirectResponse,
Symfony\Component\HttpKernel\KernelEvents,
Symfony\Component\HttpKernel\Event\ControllerEvent,
Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use App\Package\Admin\Main\EntityInterface\AdminInterface;
use App\Package\Toolkit\ApplicationMode\ApplicationMode,
App\Package\Toolkit\RouteLocalizer\RouteLocalizer;
/**
* LogoutInactiveAdminSubscriber
*
* Redirects user to logout if inactive
*
* @todo include handling xmlHttpRequest and return response to reload front page
* (currently xmlHttpRequests are ignored)
*
* @author Daniel Balowski <d.balowski@openform.pl> (_creator)
* @copyright Openform
* @since 03.2019
*/
class LogoutInactiveAdminSubscriber implements EventSubscriberInterface
{
/**
* @var ApplicationMode
*/
protected $applicationMode;
/**
* @var AdminInterface
*/
protected $admin;
/**
* @var RouteLocalizer
*/
protected $routeLocalizer;
/**
* @var integer
*/
protected $adminLoginSessionMinutes;
/**
* @param ApplicationMode $applicationMode
* @param TokenStorageInterface $tokenStorage
* @param RouteLocalizer $routeLocalizer
* @param integer $adminLoginSessionMinutes
*/
public function __construct(
ApplicationMode $applicationMode,
TokenStorageInterface $tokenStorage,
RouteLocalizer $routeLocalizer,
int $adminLoginSessionMinutes
) {
$this->applicationMode = $applicationMode;
$this->admin =
$tokenStorage->getToken() ?
$tokenStorage->getToken()->getUser() :
null;
$this->routeLocalizer = $routeLocalizer;
$this->adminLoginSessionMinutes = $adminLoginSessionMinutes;
}
/**
* @return array
*/
public static function getSubscribedEvents() : array
{
return [
KernelEvents::CONTROLLER => [
[ 'logoutInactiveAdmin', 384 ],
]
];
}
/**
* Redirects user to logout if inactive
*
* @param ControllerEvent $event
*
* @return void
*/
public function logoutInactiveAdmin(ControllerEvent $event) : void
{
if ($this->applicationMode->getCurrentMode() !== 'admin') {
return;
}
if ($event->getRequest()->isXmlHttpRequest()) {
return;
}
if (
! $this->admin ||
gettype($this->admin) == 'string' ||
! $this->admin->getLastSeen()
) {
return;
}
$lastSeen =
(clone $this->admin->getLastSeen())
->modify('+' . $this->adminLoginSessionMinutes . 'mins');
$now = new \DateTime();
$timeLeft = strtotime( $lastSeen->format('Y-m-d H:i:s') ) - strtotime( $now->format('Y-m-d H:i:s') );
if ($timeLeft > 0) {
return;
}
$logoutRoute = $this->routeLocalizer->generate('admin_logout', [], $event->getRequest()->getLocale());
$event->setController(function() use ($logoutRoute) {
return new RedirectResponse( $logoutRoute );
});
$event->stopPropagation();
return;
}
}