getting authenticated user onAuthenticationSuccess
Asked Answered
F

4

5

I have the following authentication handler:

class LoginAuthSuccessHandler implements AuthenticationSuccessHandlerInterface, AuthenticationFailureHandlerInterface
{
    private $router;
    private $container;

    /**
    * Constructor
    * @param RouterInterface   $router
    */
    public function __construct(RouterInterface $router, $container)
    {
        $this->router = $router;
        $this->container = $container;
    }

    public function onAuthenticationSuccess(Request $request, TokenInterface $token)
    {
        if ($request->isXmlHttpRequest()) {
            $user =  $this->container->get('security.context')->getToken()->getUser();
            $result = array('success' => true, 'user' => $user);
            return new Response(json_encode($result));
        } else {
            $route = $this->router->generate('ShopiousMainBundle_profile');

            $referrer_url = $request->server->get('HTTP_REFERER');
            if (strstr($referrer_url, '/items/')) {
                 $route = $referrer_url;
            }

            return new RedirectResponse($route);
        }
    }

    public function onAuthenticationFailure(Request $request, AuthenticationException $exception)
    {
        if ($request->isXmlHttpRequest()) {
            $result = array('success' => false, 'message' => $exception->getMessage());
            return new Response(json_encode($result));
        } else {
            // Handle non XmlHttp request here
        }
    }
}

why is it that:

$user =  $this->container->get('security.context')->getToken()->getUser();

returns null? how do i get the authenticated user at this point?

Fictionalize answered 30/8, 2013 at 14:55 Comment(0)
E
9

You should use the $token variable you are receiving as an argument instead of $this->container->get('security.context')->getToken().

$user = $token->getUser();
Emie answered 30/8, 2013 at 16:14 Comment(0)
M
3
public function onAuthenticationSuccess(Request $request, TokenInterface $token)
{
    $user = $token->getUser();
}

that's all ;)

Multiplicity answered 6/10, 2016 at 7:20 Comment(0)
O
0

maibe you don't set your provider in security.yml.

security:
 provider:
  example:
   entity: {class Acme\AuctionBundle\Entity\User, property: username}

Replace the Bundle and the entity by yours.

Orifice answered 30/8, 2013 at 15:4 Comment(1)
i did set the providerFictionalize
V
0

The only way I found was to inject the entityManager,

calls:
    - [setEntityManager,[@doctrine.orm.entity_manager]]

get the username from the request and query for the user, using that username.

$userRepo->findByEmail($request->get('_username'));
Vishinsky answered 3/11, 2015 at 22:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.