Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony2: After successful login event, perform set of actions

Tags:

php

symfony

I need to perform a set of actions after a user successfully logs in. This includes loading data from the database and storing it in the session.

What is the best approach to implementing this?

like image 345
jbsound Avatar asked Jun 24 '12 19:06

jbsound


2 Answers

You can add a listener to the security.interactive_login event.

attach your listener like so. In this example I also pass the security context and session as dependencies.

Note: SecurityContext is deprecated as of Symfony 2.6. Please refer to http://symfony.com/blog/new-in-symfony-2-6-security-component-improvements

parameters:
   # ...

   account.security_listener.class: Company\AccountBundle\Listener\SecurityListener

services:
   # ...

   account.security_listener:
        class: %account.security_listener.class%
        arguments: ['@security.context', '@session']
        tags:
            - { name: kernel.event_listener, event: security.interactive_login, method: onSecurityInteractiveLogin }

and in your listener you can store whatever you want on the session. In this case I set the users timezone.

<?php

namespace Company\AccountBundle\Listener;

use Symfony\Component\Security\Core\SecurityContextInterface;
use Symfony\Component\HttpFoundation\Session\Session;
use Symfony\Component\Security\Http\Event\InteractiveLoginEvent;

class SecurityListener
{

   public function __construct(SecurityContextInterface $security, Session $session)
   {
      $this->security = $security;
      $this->session = $session;
   }

   public function onSecurityInteractiveLogin(InteractiveLoginEvent $event)
   {
        $timezone = $this->security->getToken()->getUser()->getTimezone();
        if (empty($timezone)) {
            $timezone = 'UTC';
        }
        $this->session->set('timezone', $timezone);
   }

}
like image 105
MDrollette Avatar answered Oct 30 '22 22:10

MDrollette


You can even fetch the user instance from the event itself, no need to inject the token storage!

public function onSecurityInteractiveLogin(InteractiveLoginEvent $event)
{
    $event->getAuthenticationToken()->getUser()
}
like image 20
robinvdvleuten Avatar answered Oct 30 '22 22:10

robinvdvleuten