Last Updated: September 09, 2019
·
7.11K
· pleone

Symfony2 catch FOSUser onLogin event

If you want to do some action after the user login, you need to create a listener to that event.
The code above should work, just add your logic where needed.

1- Create the listener Class: you can place it in a folder of your bundle, called Listener

 // Listener/LoginListener.php
/*** Custom login listener.***/
class LoginListener{
    protected $userManager;
}

public function __construct(UserManagerInterface $userManager){
    $this->userManager = $userManager;
}
public function onSecurityInteractiveLogin( InteractiveLoginEvent $event )
{
    $user = $event->getAuthenticationToken()->getUser();
    //do something
    return new Response(); 
}

2- Configure your listener as a service:

#src/Acme/HelloBundle/Resources/config/services.yml
parameters:
  interactive_login_listener.class:
    Acme\UserBundle\Listener\LoginListener
services:
  login_listener:
    class: %interactive_login_listener.class%
    arguments:
      userManager: "@fos_user.user_manager"
    tags:
     - { name: kernel.event_listener, event: security.interactive_login, method: onSecurityInteractiveLogin }

That's it!