Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

symfony2 logout

Tags:

php

symfony

login

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'));
}

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

like image 267
paradita Avatar asked Oct 05 '12 09:10

paradita


1 Answers

To get token, you must inject with security context.

1. Create class Logout listener, something like this:

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. And then in service.yml, add this line:

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

That's it, may it helps.

like image 138
tesmojones Avatar answered Oct 03 '22 23:10

tesmojones