Symfony2:检查旧的ROLE返回true [英] Symfony2 : Checking for old ROLE returns true
问题描述
我将FOSUserBundle
用于我的symfony2 项目.注册后,我将使用以下功能检查用户是否具有FOSUB赋予的默认角色ROLE_USER
.
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'));
}
如果此函数返回true,我将建立一个新的帐户注册表格,并在提交后更改角色并删除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.
编辑:
$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这样做:
restetToken does this :
$token = new UsernamePasswordToken($user, null, 'main', $user->getRoles());
$this->container->get('security.context')->setToken($token);
我已经检查了数据库,并且不再有角色用户.如果我注销并再次登录,$user->hasDefaultRole()
仍返回true.我在这里没看到什么?还是这是预期的行为?
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?
推荐答案
FOSUserBundle始终将默认角色(ROLE_USER
)添加到角色列表中,以确保用户始终至少具有角色,因此无论您做什么您将无法删除它.
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';
此外,您将永远不会在数据库中找到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;
}
这篇关于Symfony2:检查旧的ROLE返回true的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!