Perhaps this will help people solve this problem.
This is a kind of solution, but there is a problem: If the user session is killed by php (for example, after too little time without action), you need to go to your database to reset the "registered" value to 0.
So my solution is:
-add field "logged" (logical) for the user user.
- in YourSite \ UserBundle \ Listener create: YourSiteLoginListener.php using this code
namespace YourSite\UserBundle\Listener; use FOS\UserBundle\Model\UserManagerInterface; use FOS\UserBundle\Model\UserInterface; use Symfony\Component\Security\Http\Event\InteractiveLoginEvent; use Symfony\Component\Security\Core\Exception\AuthenticationException; use Symfony\Component\Security\Core\SecurityContext; class YourSiteLoginListener { private $userManager; public function __construct(UserManagerInterface $userManager) { $this->userManager = $userManager; } public function onSecurityInteractiveLogin(InteractiveLoginEvent $event) { $user = $event->getAuthenticationToken()->getUser(); if($user->getLogged()){ throw new AuthenticationException('this user is already logged'); }else{ $user->setLogged(true); $this->userManager->updateUser($user); } } }
- then in the same directory create an exit handler: YourSiteLogoutHandler.php
namespace YourSite \ UserBundle \ Listener;
use FOS\UserBundle\Model\UserManagerInterface; use FOS\UserBundle\Model\UserInterface; use Symfony\Component\Security\Core\Authentication\Token\TokenInterface; use Symfony\Component\HttpFoundation\Response; use Symfony\Component\HttpFoundation\Request; use Symfony\Component\Security\Http\Logout\LogoutHandlerInterface; class YourSiteLogoutHandler implements LogoutHandlerInterface { private $userManager; public function __construct(UserManagerInterface $userManager) { $this->userManager = $userManager; } public function logout (Request $request, Response $response, TokenInterface $token){ $user = $token->getUser(); if($user->getLogged()){ $user->setLogged(false); $this->userManager->updateUser($user); } } }
-finaly declare these services in your /config.yml application, for example:
services: yoursite_login_listener: class: YourSite\UserBundle\Listener\YourSiteLoginListener arguments: [@fos_user.user_manager] tags: - { name: kernel.event_listener, event: security.interactive_login, method :onSecurityInteractiveLogin } yoursite_logout_handler: class: YourSite\UserBundle\Listener\YourSiteLogoutHandler arguments: [@fos_user.user_manager]
sllly
source share