Symfony在用户登录时执行操作

时间:2017-02-13 09:04:18

标签: php listener symfony

当用户成功登录时,我不想对数据库执行更新操作(将登录计数添加+1并更新上次登录时间戳)。使用Symfony 3

我添加了lister:

// src/AppBundle/Listener/SecurityListener.php

namespace AppBundle\Listener;
use Symfony\Component\Security\Http\Event\InteractiveLoginEvent;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorage;
#use Doctrine\Bundle\DoctrineBundle\Registry as Doctrine;
use Doctrine\ORM\EntityManager;

class SecurityListener
{
    private $tokenStorage;

    public function __construct(TokenStorage $tokenStorage, EntityManager $doctrine)
    {

    }

    public function onSecurityInteractiveLogin(InteractiveLoginEvent $event)
    {
        if ( $this->tokenStorage->isGranted('IS_AUTHENTICATED_FULLY') ) {
            if( $user = $event->getAuthenticationToken()->getUser() )
                var_dump($user);
            else {
                var_dump('nej');
            }
        }
    /**
     * Update lastLogin and loginCount for user in database
     */
    //  $em->
    }
}

应用程序/配置/ services.yml:

# Learn more about services, parameters and containers at
# http://symfony.com/doc/current/service_container.html
parameters:
#    parameter_name: value
  account.security_listener.class: AppBundle\Listener\SecurityListener

services:
#    service_name:
#        class: AppBundle\Directory\ClassName
#        arguments: ["@another_service_name", "plain_value", "%parameter_name%"]
  account.security_listener:
      class: %account.security_listener.class%
      arguments: ['@security.token_storage', '@doctrine.orm.entity_manager']
      tags:
          - { name: kernel.event_listener, event: security.interactive_login, method: onSecurityInteractiveLogin }

我收到错误Error: Call to a member function isGranted() on null

2 个答案:

答案 0 :(得分:2)

方法isGranted('IS_AUTHENTICATED_FULLY')在Symfony \ Component \ Security \ Core \ Authorization \ AuthorizationChecker上可用。如果您想检查用户是否通过令牌进行了身份验证(如SecurityListener类),请使用以下方法更改onSecurityInteractiveLogin方法:

public function onSecurityInteractiveLogin(InteractiveLoginEvent $event)
{
    if ($event->getAuthenticationToken()->isAuthenticated()) {
        $user = $event->getAuthenticationToken()->getUser();
        var_dump($user);
    }

/**
 * Update lastLogin and loginCount for user in database
 */

//  $em->

}

答案 1 :(得分:0)

你忘了:

public function __construct(TokenStorage $tokenStorage, EntityManager $doctrine)
{
    $this->tokenStorage = $tokenStorage;
}

???