Symfony2 : Checking for old ROLE returns true

落爺英雄遲暮 提交于 2019-12-11 22:51:37

问题


I am using FOSUserBundle for my symfony2 project. Upon registration, I check with the function below if the user has the default role ROLE_USER that FOSUB gives.

 /**
  * Returns true if user has ROLE_USER
  *
  * @return boolean 
  */
 public function hasDefaultRole() {
     return ($this->hasRole('ROLE_USER'));
 }

If this function returns true, I set up a new account registration form and on submit the roles are changed and ROLE_USER is removed.

EDIT :

$user = $this->container->get('security.context')->getToken()->getUser();
...
$userManager = $this->container->get('fos_user.user_manager');
$user->removeRole("ROLE_USER");
$user->setRoles(array("ROLE_TEACHER", "ROLE_TEACHER_BASIC"));
$user->setStatus(1);
$userManager->updateUser($user);
$this->resetToken($user);

restetToken does this :

 $token = new UsernamePasswordToken($user, null, 'main', $user->getRoles());
 $this->container->get('security.context')->setToken($token);

I have checked the database and there is no role user anymore. If I logout, and login back again, $user->hasDefaultRole() still returns true. What am I not seeing here? Or is this an expected behaviour?


回答1:


FOSUserBundle always add the default role (ROLE_USER) to the list of roles to ensure that users always have at least on role, so no matter what you do you won't be able to remove it.

FOSUserBundle\Model\User

/**
 * Returns the user roles
 *
 * @return array The roles
 */
public function getRoles()
{
    $roles = $this->roles;

    foreach ($this->getGroups() as $group) {
        $roles = array_merge($roles, $group->getRoles());
    }

    // we need to make sure to have at least one role
    $roles[] = static::ROLE_DEFAULT;

    return array_unique($roles);
}

FOSUserBundle\Model\UserInterface

const ROLE_DEFAULT = 'ROLE_USER';

Also you will never find the ROLE_USER in your database as it never actually adds it.

FOSUserBundle\Model\User

public function addRole($role)
{
    $role = strtoupper($role);
    if ($role === static::ROLE_DEFAULT) {
        return $this;
    }

    if (!in_array($role, $this->roles, true)) {
        $this->roles[] = $role;
    }

    return $this;
}


来源:https://stackoverflow.com/questions/25118177/symfony2-checking-for-old-role-returns-true

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!