Login event listener in Symfony2

Login event listener in Symfony2

So you have a Symfony2 project under construction. Login works. Now you want to execute some code right after the user successfully logs in.

The solution: Make a custom event listener.

An event listener is actually a service with a proper tag associated with it. So first step is to register the listener. The configuration file shown corresponds to the listener in file Acme/UserBundle/Listener/LoginListener.php. You can read more about services here.

In services.yml:

Let’s go through the configuration.

class defines the listener class.

With arguments we inject services that this listener depends on. In this case the security.context service for retrieving the User object and doctrine service for EntityManager.

tags is important. Every listener must be tagged with kernel.event_listener and must specify it’s event. For successful login that event is security.interactive_login. You can also specify the optional method tag.

Ok, our listener is registered. Let’s create it.

The above code should be pretty self-explanatory. The only required method is onSecurityInteractiveLogin(Event $event). You do not need the other stuff, but you probably will if you want to modify the User object, or something else in the DB.

10 Responses so far.

  1. Ruben de Vries says:

    Thanks for the snippets, really helped me out a lot :)

  2. This is MISTAKEN – you need to put the ->getUser() in the onSecurityInteractiveLogin function. Otherwise, the user isn’t logged in yet!

  3. Dattaya says:

    I’ve got user object this way: $user = $event->getAuthenticationToken()->getUser();
    (sf2.0.9)

  4. bnlab says:

    thanks for this simple but powerful tuti!

  5. Flo says:

    Thanks for the snippets.

    But how to get the container to do this:

    $this->container->get(‘request’)->getSession->setFlashes(‘message’, ………..);

    Thanks

  6. Metod says:

    You should add a new dependency to the service: @session

    Then you can get it in the constructor and do what you need. :)

  7. Paolo says:

    Great tutorial

    Is possible to do the same with logout action ?

    Thanks again