0
votes

In my Symfony project I'm using UserInterface in my User entity to handle authentication. I also use EquatableInterface to check if user's email is changed while he's logged in.

public function isEqualTo(UserInterface $user)
{
    if (!$user instanceof Account) {
        return false;
    }
    if ($this->email !== $user->getEmail()) {
        return false;
    }
    return true;
}

All works as expected, but when I change user's email in DB I'm not logged out, just not authenticated as you can see in the following screenshot.

https://s15.postimg.org/6md5htszf/22781921b8.png

So I would know how can I check in a controller if user is authenticated? And how can I force user to log out when isEqualTo returns false?

2

2 Answers

3
votes

I found the solution and I want to share it if someone else have the same problem.

To check if user is authenticated, we need TokenInterface which is implemented by TokenStorage. Then we just need to call isAuthenticated() method.

$tokenInterface = $this->get('security.token_storage')->getToken();
$isAuthenticated = $tokenInterface->isAuthenticated()
0
votes

Fast Method: see method getUser in Symfony\Bundle\FrameworkBundle\Controller at link. If you need this behavior somewhere in the service, then use the security.token_storage service as a dependency.

Try way method (symfony-like): you need use Symfony Security Voters