TeoM
TeoM

Reputation: 105

Symfony3 get security token after authentication

I'm trying to make a modal login and after the user enters the correct email & password, I need to get the ID of the logged user (while the modal is still open, without refreshing the page). The id from the users table from the database.

Normally, I get the id with the following line:

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

In the modal situation, I am sending the form to LoginController and inside the controller I have:

/** @var AuthenticationUtils $authenticationUtils */
$authenticationUtils = $this->get('security.authentication_utils');
$error = $authenticationUtils->getLastAuthenticationError();

If I enter bad credentials, it works fine, displaying: Bad credentials If I enter correct credentials and I do var_dump($error) I get NULL.

If I do $error = $authenticationUtils->getLastAuthenticationError()->getToken();

I get an error, saying that I try to apply getToken on null object.

If I try to do this:

/** @var Accounts $account */
$account = $this->get('security.token_storage')->getToken()->getUser();
var_dump($account);

I get the same error. If I refresh the page, I am logged in.

My scope is to obtain the $account object.

How can I get the User (entity) without refreshing the page? In the same controller, right after $authenticationUtils->getLastAuthenticationError()?

Thanks,

Upvotes: 1

Views: 1774

Answers (2)

walidtlili
walidtlili

Reputation: 1090

in symfony 3 : $id =$this->getUser()->getId()

Upvotes: 0

Frank B
Frank B

Reputation: 3697

I'm trying to make a modal login and after the user enters the correct email & password, I need to get the ID of the logged user (while the modal is still open, without refreshing the page). The id from the users table from the database.

So you will need to login through AJAX. Otherwise your page will be refreshed. Using AJAX there will be another issue. You will be redirected after the login to another page depending on some circumstances and that is not what you want because you want a response containing some user information. Therefore you will need to write your own authentication handler. This article explains how: http://www.webtipblog.com/adding-an-ajax-login-form-to-a-symfony-project/

Upvotes: 1

Related Questions