1

I use "success_handler" (in Symfony security.yml) and onLogoutSuccess() with FOSUserBundle. But I want to getUser() for add his name in flash message.

Service and PHP Classe :

services: utilisateur_deconnexion: class: UtilisateurBundle\Handler\Deconnexion arguments: [@router] class Deconnexion implements LogoutSuccessHandlerInterface { private $router; public function __construct(RouterInterface $router) { $this->router = $router; } public function onLogoutSuccess(Request $request) { $request->getSession()->getFlashBag()->add('success', 'Vous êtes à présent déconnecté.'); return new RedirectResponse($this->router->generate('dometech_index_index')); } } 

Can you help me ?

1

2 Answers 2

2

You can inject @security.context service into your logout handler. From the SecurityContext you will be able to get currently set token object which is instance of TokenInterface. From the instance of TokenInterface you will be able to get the current user. See below.

services.yml

services: utilisateur_deconnexion: class: UtilisateurBundle\Handler\Deconnexion arguments: ["@router", "@security.context"] 

Logout success handler:

use Symfony\Component\Security\Core\SecurityContextInterface; use Symfony\Component\Routing\RouterInterface; class Deconnexion implements LogoutSuccessHandlerInterface { private $router; private $securityContext; public function __construct(RouterInterface $router, SecurityContextInterface $securityContext) { $this->router = $router; $this->securityContext = $securityContext; } public function onLogoutSuccess(Request $request) { // let's assume your user object has getUsername method $username = $this->securityContext->getToken()->getUser()->getUsername(); $request->getSession()->getFlashBag()->add( 'success', sprintf('%s - Vous êtes à présent déconnecté.', $username) ); return new RedirectResponse($this->router->generate('dometech_index_index')); } } 
Sign up to request clarification or add additional context in comments.

Comments

0

To complete/update the post of @takeit for Symfony 3.x

Replace @security.context to @security.token_storage

services.yml

services: utilisateur_deconnexion: class: UtilisateurBundle\Handler\Deconnexion arguments: ["@router", "@security.token_storage"] 

Logout success handler:

[...] public function onLogoutSuccess(Request $request) { // let's assume your user object has getUsername method $username = $this->tokenStorage->getToken()->getUsername(); [...] } [...] 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.