Gaylord.P
Gaylord.P

Reputation: 1468

getUser() in Logout with FOSUserBundle

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 ?

Upvotes: 1

Views: 521

Answers (2)

Breith
Breith

Reputation: 2298

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(); 

         [...]
    }
[...]

Upvotes: 0

takeit
takeit

Reputation: 4081

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

Upvotes: 2

Related Questions