Call to a member function getId() on string after login

1.7k Views Asked by At

I am accessing a part of the site that requires the user to be logged in. But the system, instead of going to the login, and then to the site I want to access, shows me the error indicating that I am not logged in.

The controller code is as follows:

/**
* @Route("/estrategia/titulares", name="estrategia_titulares")
*/
    public function estrategiaTitularesAction(Request $request)
    {
        $em = $this->getDoctrine()->getManager();
        $logged = $this->get('security.token_storage')->getToken()->getUser();
        $user = $em->getRepository('AppBundle:User')->find($logged->getId());

        if(!$user)
        {
            $messageException = $this->get('translator')->trans('No se ha encontrado el usuario');
            throw $this->createNotFoundException($messageException);
        }

The error that appears is in the line of $user = $em->getRepository

Call to a member function getId() on string

How can I do so that the system first asks me to login, and then does redirect me to the page I want to access?

2

There are 2 best solutions below

7
yivi On

Since you are trying to detect if the user is logged in or not, it is entirely possible that you do not get a user entity at all.

If a user is not logged in, you won't get a "user object" from the token storage service, and you'll get the error you are getting when trying to access its properties.

Additionally, your user has already been refreshed from the DB by that point (if correctly authenticated), so getting it from Doctrine is redundant and you can avoid it.

The correct way of doing this, assuming that your user class implements Symfony\Component\Security\Core\User\UserInterface

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

if (!$user instanceof UserInterface) {
    // failure mode. Throw exception, return RedirectResponse, or what you prefer.
    // We are dealing with an anonymous, non-authenticated user
}

The token (getToken()), could be null as well, so that's something you may want to check.

But, considering your are in a controller, and that the route handled by the controller should be sitting behind one of the firewalls... normally it wouldn't be ever null.

If it were null, something else is amiss in your setup and you better catch it pronto.

5
Frank B On

Above answer is fine except that you have to verify if the getToken() method returns a valid token or NULL. Here the better version:

$user = NULL;
$token = $this->get('security.token_storage')->getToken();

if(NULL !== $token) {
    $user = $token->getUser();
}

if($user instanceof UserInterface) {
    // logged in user
}