Search code examples
phpsymfonyauthenticationaddeventlistenerflash-message

Symfony2 - Flash messages when redirects to the login page


I have the automated redirect on login page when the route /user/* is accessed. I need to display a flash messages when redirects to the login page.

I read something about Event Listeners but need a real example to implement that.

I was trying:

services:
    listener.requestresponse:
        class: SciForum\Version2Bundle\EventListener\ExceptionListener
        tags:
          - { name: kernel.event_listener, event: kernel.exception, method: onKernelException }

And my ExceptionListener

class ExceptionListener
{
public function onKernelException(GetResponseForExceptionEvent $event)
{
    // You get the exception object from the received event
    $exception = $event->getException();
    $message = sprintf(
            'My Error says: %s with code: %s',
            $exception->getMessage(),
            $exception->getCode()
    );

    // Customize your response object to display the exception details
    $response = new Response();
    $response->setContent($message);

    // HttpExceptionInterface is a special type of exception that
    // holds status code and header details
    if ($exception instanceof HttpExceptionInterface) {
        $response->setStatusCode($exception->getStatusCode());
        $response->headers->replace($exception->getHeaders());
    } else {
        $response->setStatusCode(Response::HTTP_INTERNAL_SERVER_ERROR);
    }

    // Send the modified response object to the event
    $event->setResponse($response);
}
}

But the exception is newer throw when the automated redirect is there.


Solution

  • An EventListener is designed to listen for specific events. You have created an ExceptionListener, which is taking GetResponseForExceptionEvent as an argument. If the redirect is successful, then it won't ever throw any exception.

    You need to create a generic EventListener, or even a InteractiveLoginEvent listener:

    Here is a login listener I made:

        use Symfony\Component\Security\Http\Event\InteractiveLoginEvent;
        use Symfony\Component\Security\Core\SecurityContext;
        use Doctrine\Bundle\DoctrineBundle\Registry as Doctrine; 
    
    class LoginListener
    {
    
        private $securityContext;       
    
        private $em;        
    
        public function __construct(SecurityContext $securityContext, Doctrine $doctrine)
        {
            $this->securityContext = $securityContext;
            $this->em              = $doctrine->getManager();
        }
    
        public function onSecurityInteractiveLogin(InteractiveLoginEvent $event)
        {
                 //do stuff
        }
    }
    

    But, to solve your problem directly, could you not just get the redirect headers in the controller and then display the message?