Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
439 views
Welcome To Ask or Share your Answers For Others

1 Answer

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: CompanyAccountBundleListenerSecurityListener

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 CompanyAccountBundleListener;

use SymfonyComponentSecurityCoreSecurityContextInterface;
use SymfonyComponentHttpFoundationSessionSession;
use SymfonyComponentSecurityHttpEventInteractiveLoginEvent;

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);
   }

}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...