Tom
Tom

Reputation: 1223

Symfony: Logout in KernelEvents::CONTROLLER Listener

Is there a possibility to logout user in KernelEvents::CONTROLLER Listener? If yes, how?

In this Listener I get some data from database and put it into a service. But if the query returns no data, I would like to add a flash message and logout user. How to achieve this?

Upvotes: 0

Views: 1025

Answers (1)

famas23
famas23

Reputation: 2280

You can create a simple route for logout and configure it under security prarameters (take a look). But if you insiste it depend in what you want to build. You can create an event subscriber to kernel.controller event.

As mentionned here kernel.controller (aka KernelEvents::CONTROLLER) listener gets notified on every request, right before the controller is executed. So, first, you need some way to identify if the controller that matches the request needs.

use Symfony\Component\Security\Core\SecurityContext;
...
    class LogoutSubscriber implements EventSubscriberInterface
    {
        /**
         * @var SecurityContext
         */
        private $securityContext;

        public function __construct(SecurityContext $securityContext)
        {
            $this->securityContext = $securityContext;
        }

        public function onKernelController(FilterControllerEvent $event)
        {
            $controller = $event->getController();

            if (!is_array($controller)) {
                return;
            }

            if ($controller[0] instanceof YourController) {
                 //Log out only if this method returns false
                 $s = $this->someService->init();
                if(false === $s) {
                    //Then logout here
                    //Pass parameters to the controller
                    //which has logout method to invalidate session
                    //null the token and add Flash message
                    $controller = new SecurityController();
                    $controller->setRouter($this->router);
                    $controller->setSession($this->session);
                    $controller->setTokenStorage($this->tokenStorage);
                    $controller->setTranslator($this->translator);
                    $replacementController = array($controller, 'logout');
                    $event->setController($replacementController);
                }
            }
        }

        public static function getSubscribedEvents()
        {
            return array(
                KernelEvents::CONTROLLER => 'onKernelController',
            );
        }
    }

If you want more then logout, just inject the appropriate dependency and use it, for example for flash messages, inject Symfony\Component\HttpFoundation\Session\Session tagged with session and then just call $this->session->getFlashBag()->add('notice', 'You have been successfully been logged out.');

Upvotes: 1

Related Questions