Search code examples
phpsymfony

Symfony check if user is authenticated


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?


Solution

  • 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()
    

    Since Symfony 5.4 this method is deprecated (and removed in 6), so in that case you have to check if getUser() returns null to do the same check.