symfony2注销 [英] symfony2 logout

查看:81
本文介绍了symfony2注销的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

My problem is capture user logout. the code what i have is:

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?

The problem is I can not access the user token TokenInterface when you are running the logout function?

推荐答案

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

To get token, you must inject with security context.

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]

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

That's it, may it helps.

这篇关于symfony2注销的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆