Search code examples
sessionsymfonyregistrationfosuserbundle

Keep same session after registration FOSUserBundle


I'm developing a Symfony 3 application in which I'm using FOSUserBundle.

I want the current user (UserA) add new user (userB) and keep session value with UserA. FOSUser changes session with last registered user (UserB).

How do I to keep USerA in session after registering userB?


Solution

  • Solution :

    <?php
    namespace UserBundle\EventListener;
    
    use FOS\UserBundle\Event\FilterUserResponseEvent;
    use FOS\UserBundle\Event\FormEvent;
    use FOS\UserBundle\Event\UserEvent;
    use FOS\UserBundle\FOSUserEvents;
    use Symfony\Component\EventDispatcher\EventSubscriberInterface;
    use Symfony\Component\HttpFoundation\RedirectResponse;
    use Symfony\Component\HttpFoundation\Session\SessionInterface;
    use Symfony\Component\Routing\Generator\UrlGeneratorInterface;
    use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorage;
    
    
    class RegistrationConfirmListener implements EventSubscriberInterface
    {
        private $router;
        private $olduser;
    
        private $token;
    
    
    
        public function __construct(UrlGeneratorInterface $router, TokenStorage $token)
        {
            $this->olduser = $token->getToken()->getUser();
            $this->router = $router;
            $this->token =$token;
        }
    
        /**
         * {@inheritDoc}
         */
        public static function getSubscribedEvents()
        {
            return array(
                FOSUserEvents::REGISTRATION_COMPLETED => 'onRegistrationCompleted'
            );
        }
    
        public function onRegistrationCompleted(FilterUserResponseEvent $event)
        {
            $response = $event->getResponse();
            $this->token->getToken()->setUser($this->olduser);
            $response->setTargetUrl($this->router->generate('immobilier_dashboard'));
        }
    
    
    }
    

    any other solution is appreciated .