symfony2注销

时间:2012-10-05 09:18:36

标签: php symfony login

我的问题是捕获用户注销。我所拥有的代码是:

public  function onAuthenticationFailure(Request $request, AuthenticationException $exception){

    return new Response($this->translator->trans($exception->getMessage()));
}

public function logout(Request $request, Response $response, TokenInterface $token)
{
    $empleado = $token->getUser();
    $log = new Log();
    $log->setFechalog(new \DateTime('now'));
    $log->setTipo("Out");
    $log->setEntidad("");
    $log->setEmpleado($empleado);
    $this->em->persist($log);
    $this->em->flush();
}

public function onLogoutSuccess(Request $request) {
    return new RedirectResponse($this->router->generate('login'));
}

问题是当您运行注销功能时我无法访问用户令牌TokenInterface

3 个答案:

答案 0 :(得分:12)

要获取令牌,您必须注入安全上下文。

<强> 1。创建类Logout侦听器,如下所示:

namespace Yourproject\Yourbundle\Services;
...
use Symfony\Component\Security\Http\Logout\LogoutSuccessHandlerInterface;
use Symfony\Component\Security\Core\SecurityContext;

class LogoutListener implements LogoutSuccessHandlerInterface {

  private $security;  

  public function __construct(SecurityContext $security) {
    $this->security = $security;
  }

  public function onLogoutSuccess(Request $request) {
     $user = $this->security->getToken()->getUser();

     //add code to handle $user here
     //...

     $response =  RedirectResponse($this->router->generate('login'));

    return $response;
  }
}

<强> 2。然后在service.yml中添加以下行:

....
logout_listener:
   class:  Yourproject\Yourbundle\Services\LogoutListener
   arguments:  [@security.context]

就是这样,可能会有所帮助。

答案 1 :(得分:6)

请参阅http://symfony.com/doc/current/reference/configuration/security.html

security.yml

secured_area:

    logout:
        path:   /logout
        **success_handler: logout_listener** 

答案 2 :(得分:0)

看看你可以覆盖捆绑包的任何控制器:

http://symfony.com/doc/current/cookbook/bundles/inheritance.html