Symfony 2 - Adding User Roles to ROLE_USER
I am trying to create a new role in Symfony 2 below the default USER_ROLE (this role will be limited to writeable to some features). I am using FOSUserBundle.
I already wrote the following security settings, but my ROLE_DEMO users still get ROLE_USER.
role_hierarchy:
ROLE_DEMO: []
ROLE_USER: [ROLE_DEMO]
ROLE_ADMIN: [ROLE_USER, ROLE_SONATA_ADMIN]
ROLE_SUPER_ADMIN: [ROLE_USER, ROLE_ADMIN, ROLE_ALLOWED_TO_SWITCH]
Is it possible to create a role under ROLE_USER in Symfony 2. If so, how?
source to share
An even shorter solution I came across was to override const ROLE_DEFAULT
at the beginning of my class User
.
class User extends BaseUser
{
/**
* Override FOSUserBundle User base class default role.
*/
const ROLE_DEFAULT = 'ROLE_DEMO';
[...]
}
This way I didn't even have to override the getRoles()
FOS custom package set method .
source to share
If you are using FOSUserBundle it will provide all users by default ROLE_USER
. ROLE_USER
is present on every single hydrated user by default FOSUserBundle (although not in the database). You can override this implementation by specifying your own method getRoles()
in your class User
. Or change the default role to ROLE_NONE
(it doesn't really matter). Or just don't use ROLE_USER
and come up with a different role name for your real users.
This is from the User
default implementation
/* FOS\UserBundle\Model\User */
...
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);
}
source to share