如何获得自定义用户类

时间:2016-02-26 10:46:54

标签: symfony authentication

也许问题很简单,但现在是:

我使用自己的User类和UserProvider类进行了身份验证。我扩展了DefaultAuthenticationSuccessHandler来修改连接的用户。
这应该发生在这个方法中:

public function onAuthenticationSuccess(Request $request, TokenInterface $token)

在我的自定义类User中,我有一个addRole方法。

如何从onAuthenticationSuccess函数中作为参数提供的令牌中获取此方法?

1 个答案:

答案 0 :(得分:0)

首先,您需要检索经过身份验证的用户:

$user = $token->getUser();

然后,您应该可以致电$user->addRole()

但是,您需要将更改存储在db中 为此,您需要在服务中注入原则EntityManager

更改服务声明:

# services.yml
    your_authentication_success_handler: 
    # ...
    arguments:
        entityManager: "@doctrine.orm.entity_manager"

在服务的构造函数中设置entityManager

// Authentication success handler
public function __construct(\Doctrine\ORM\EntityManager $entityManager = null)
{
    $this->_em = $entityManager;
}

现在,您可以使用onAuthenticationSuccess方法更新用户,如下所示:

public function onAuthenticationSuccess(Request $request, TokenInterface $token) 
{
    $user = $token->getUser();
    $user->addRole('YOUR_ROLE');
    $this->_em->flush();
}

<强>更新

由于返回的User不是您的自定义User实体的实例,因此您必须使用实体的Repository检索它。

use YourBundle\Entity\User;
// ...

$user = $token->getUser();

if (!($tokenUser instanceof User) {
    $repository = $this->_em->getRepository('YourBundle:User');
    $user = $repository->findBy(array(
        'username' => $tokenUser->getUsername(), // Assuming the 'username' property is unique
    ));
}

$user->addRole('YOUR_ROLE'); // Now you can access the method
$this->_em->flush();
相关问题