Symfony 2& FOSUserBundle:重置密码后验证用户身份

时间:2012-05-22 12:22:00

标签: authentication symfony fosuserbundle

当覆盖FOSUserBundle重置密码控制器时,有一个函数调用“authenticateUser”方法(第104行):

https://github.com/FriendsOfSymfony/FOSUserBundle/blob/master/Controller/ResettingController.php#L104

....
$this->authenticateUser($user);
....

我的问题是我已经覆盖了Symfony身份验证处理程序,并在用户登录时拥有自己的逻辑。

修改 这是我的身份验证处理程序:

<?php

/* ... all includes ... */

class AuthenticationHandler implements AuthenticationSuccessHandlerInterface, LogoutSuccessHandlerInterface
{
    private $router;
    private $container;

    public function __construct(Router $router, ContainerInterface $container)
    {
        $this->router = $router;
        $this->container = $container;
    }

    public function onAuthenticationSuccess(Request $request, TokenInterface $token)
    {
        // retrieve user and session id
        $user = $token->getUser();

        /* ... here I do things in database when logging in, and dont want to write it again and again ... */

        // prepare redirection URL
        if($targetPath = $request->getSession()->get('_security.target_path')) {
            $url = $targetPath;
        }
        else {
            $url = $this->router->generate('my_route');
        }

        return new RedirectResponse($url);
    }

}

那么,我如何从ResettingController中的身份验证处理程序调用“onAuthenticationSuccess”方法? 为了避免重写相同的代码...

感谢您的帮助!

斯坦

1 个答案:

答案 0 :(得分:1)

您应该调用onAuthenticationSuccess方法将其作为服务加载。在你的config.yml:

authentication_handler:
    class: Acme\Bundle\Service\AuthenticationHandler
    arguments:
        container: "@service_container"

然后,在authenticateUser函数中调用它:

protected function authenticateUser(UserInterface $user) {
      try {
        $this->container->get('fos_user.user_checker')->checkPostAuth($user);
      } catch (AccountStatusException $e) {
          // Don't authenticate locked, disabled or expired users
          return;
      }

      $providerKey = $this->container->getParameter('fos_user.firewall_name');
      $token = new UsernamePasswordToken($user, null, $providerKey, $user->getRoles());
      $this->container->get('security.context')->setToken($token);
      $request = $this->container->get('request');
      $this->container->get('authentication_handler')->onAuthenticationSuccess($request, $token);
}

这样做可以通过您的自定义身份验证处理程序。 More info