Reputation: 57
It looks pretty simple and I'm a begginer with Symfony, but couldn't figure it out.
I'm using FOSUserBundle, and I'm trying to add a specific role (ROLE_ADMIN) to a specific user (e.g. me), so when the user logs in that role is assigned and he can access certain pages.
I tried putting something like this in the __construct()
method of my User entity, but it didn't work:
if($this->getUsername()=='johndoe') $this->addRole('ROLE_ADMIN');
When I log in as that user, the debugging utilities show only the 'ROLE_USER', os it is not working.
Is that a right code? Where should I put it?
Update:
There was a silly error that accidentally found. I had created the User entity before isntalling FOSUserBundle, and somehow the user I was trying to promote gave me errors through CLI. Maybe it wasn't properly stored in the database. Once I created a new one and tried again, the command worked as expected.
Upvotes: 5
Views: 14053
Reputation: 24280
In case you can access the database, just update the roles
column:
["ROLE_ADMIN"]
Upvotes: 7
Reputation: 4089
You shouldn't add the role during runtime, please add it to the user e.g. with CLI command (or by directly changing it in the database) as written in the documentation:
php bin/console fos:user:promote testuser ROLE_ADMIN
If you insist on changing the role during runtime it'd be great to understanding what you're exactly aiming for and why.
Another option would be load the single special user as an in-memory user as written here:
# app/config/security.yml
security:
providers:
in_memory:
memory:
users:
johndoe:
password: somepassword
roles: 'ROLE_ADMIN'
Upvotes: 2
Reputation: 3483
try this
$userObject=$this->getUser();
$username = $userObject->getUsername();
if($username == 'johndoe')
{
$user = $this->get('fos_user.user_manager')->findUserByUsernameOrEmail($username);
$user->setRoles( array('ROLE_ADMIN') );
$userManager->updateUser($user, true);
}
Upvotes: 3