<?php
namespace App\EventSubscriber;
use App\Entity\WhiteList;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Symfony\Component\HttpKernel\Event\ExceptionEvent;
use Symfony\Component\HttpKernel\KernelEvents;
use Symfony\Component\HttpKernel\Event\ControllerEvent;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
class RequestSubscriber implements EventSubscriberInterface
{
public function __construct(EntityManagerInterface $entityManager, TokenStorageInterface $tokenStorage)
{
$this->em = $entityManager;
$this->tokenStorage = $tokenStorage;
}
public static function getSubscribedEvents()
{
// return the subscribed events, their methods and priorities
return [
KernelEvents::CONTROLLER => [
['logException', 0],
],
];
}
/**
* @param ControllerEvent $event
*/
public function logException($event)
{
$token = $this->tokenStorage->getToken();
$domain = $_SERVER['DOMAIN'];
$firewall = $_SERVER['FIREWALL'];
if(
!is_null($token) and
$firewall === 'true'
) {
$user_ip = $_SERVER['REMOTE_ADDR'];
$logout = true;
$white_list = $this->em->getRepository(WhiteList::class)->findBy([
'ip' => $user_ip,
'type' => 1
]);
if ($white_list) {
foreach ($white_list as $white){
$status_user = $white->checkUser($token->getUser());
if($status_user) {
$logout = false;
break;
}
}
}
if($logout){
if(isset($_SESSION))
session_destroy();
$event->setController(function () {
return new RedirectResponse('/logout/no/valid/ip');
});
}
}
}
}