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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With