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?
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\UserInterfaceThe token (
getToken()), could benullas 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.