Last Updated: February 25, 2016
·
8.354K
· pix-art

How to reload your User after changes in Symfony2

So about a week ago I was asked why our User entity didn't have the proper roles after we updated the roles. Pretty soon it was clear the session wasn't reinitiated so the user still had his old permissions until you force updated them.

After some searching I came up with this example:

protected function reloadUserPermissions()
{
  $token = new UsernamePasswordToken(
      $this->user,
       null,
       'main',
       $this->user->getRoles()
   );

   $this->securityContext->setToken($token);
}

And then all was good but it didn't feel right to do all this logic each time a changed something.

After a more extensive search I found out Symfony already has a build in solution for this problem and it's called "EquatableInterface". This interface forces you to implement a function called "isEqualTo(UserInterface $user)" this function allows you to check if a certain value of your user object has changed and if so it will reload your user token.

class User implements EquatableInterface
{

   ...

   public function isEqualTo(UserInterface $user)
   {
      if ($user instanceof User) {
          // Check that the roles are the same, in any order
          $isEqual = count($this->getRoles()) == count($user->getRoles());
          if ($isEqual) {
              foreach($this->getRoles() as $role) {
                  $isEqual = $isEqual && in_array($role, $user->getRoles());
              }
          }
          return $isEqual;
      }

       return false;
   }

You can use any field bound to your user to force a reload, all you have to return is false and the user will be reloaded.

source: http://api.symfony.com/2.6/Symfony/Component/Security/Core/User/EquatableInterface.html

All my tips have been moved to my blog www.pix-art.be so come check it out!