<?php
/**
* Created by Mediterranean Develup Solutions.
* User: Carlos.Rojas
* Date: 13/06/2017
* Time: 13:50
*/
namespace App\EventListener;
use App\Entity\User;
use Doctrine\ORM\EntityManager;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\BrowserKit\Response;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpKernel\Exception\HttpException;
use Symfony\Component\HttpKernel\HttpKernel;
use Symfony\Component\HttpKernel\HttpKernelInterface;
use Symfony\Component\HttpFoundation\RedirectResponse;
use Symfony\Component\HttpKernel\Event\RequestEvent;
use Symfony\Component\Routing\RouterInterface;
use Symfony\Component\Security\Core\Exception\BadCredentialsException;
class RequestListener
{
protected $em;
private $router;
function __construct(EntityManager $em, RouterInterface $router)
{
$this->em = $em;
$this->router = $router;
}
public function onKernelRequest(RequestEvent $event)
{
$session = new Session();
$token_session = $session->get('access_token');
$email = $session->get('_security.last_username');
if (!is_null($token_session) && ($email != 'cjdevelup_admin@develup.solutions')){
$repository = $this->em->getRepository(User::class);
$usuario = $repository->findOneByEmail($email);
$token_database = $usuario->getAccessKey();
/*
* Si el token almacenado en sesion es distinto al token que esta en ese momento en
* la base de datos significa que alguien (en otra sesion) ha echo login con ese
* usuario.
*/
if ($token_session !== $token_database){
$session->set('access_token', null);
$url = $this->router->generate('kickout');
$event->setResponse(new RedirectResponse($url));
}
}
}
}