Answer the question
In order to leave comments, you need to log in
How to make authorization on no more than one device in Symfony 2?
How to make authorization on only one device in Symfony 2? When a user logs in from one computer, they must be logged out on other computers. What is the best way to do this?
Answer the question
In order to leave comments, you need to log in
symfony.com/doc/current/components/http_foundation...
Well, either remember the token issued during authorization and check if the token stored in the session matches the one you remember.
I'll answer my own question. Here is my solution.
Create the EventListener.php file
namespace project\UserBundle\EventListener;
use Symfony\Component\HttpKernel\Event\GetResponseEvent;
use Symfony\Component\HttpFoundation\Cookie;
use Symfony\Component\HttpFoundation\Response;
class UserListener {
protected $container;
public function __construct($container = null) {
if (!is_null($container)) {
$this->container = $container;
}
}
public function onAuthenticationSuccess() {
$user = $this->container->get('security.token_storage')->getToken()->getUser();
$x = md5(rand(0, 1000));
$user->setToken($x);
$em = $this->container->get('doctrine')->getManager();
$em->persist($user);
$em->flush();
$cookie = new Cookie('_token', $x, time() + 3600 * 24 * 7);
$response = new Response();
$response->headers->setCookie($cookie);
$response->send();
}
public function onKernelRequest(GetResponseEvent $event) {
$user = $this->container->get('security.token_storage')->getToken()->getUser();
if (!is_object($user)) {
return;
}
$x = $user->getToken();
$request = $this->container->get('request_stack')->getCurrentRequest();
$cookies = $request->cookies->all();
if (!isset($cookies['_token']) || $cookies['_token'] !== $x) {
$this->container->get('request')->getSession()->invalidate();
$this->container->get('security.context')->setToken(null);
$event->setResponse($this->container->get('templating')->renderResponse('UserBundle:Login:login2.html.twig', array(), null));
}
}
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question