Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

symfony 3: how to add role to specific user

Tags:

roles

symfony

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.

like image 302
FabiánV Avatar asked Nov 06 '17 13:11

FabiánV


People also ask

Can we assign role to user?

To assign a user to a user role In the Edit User Role dialog box, click Users. On the Users page, click Add. In the Select Users or Groups dialog box, type the name of a user or group that you want to add to this user role, click Check Names, and then click OK. In the Edit User Role dialog box, click OK.

How do I assign a role to a user in auth0?

Assign roles in user profile Go to Dashboard > User Management > Users and click the name of the user. Click the Roles view, and click Assign Role. Choose the role you wish to assign and click Assign.


2 Answers

In case you can access the database, just update the roles column:

["ROLE_ADMIN"]
like image 153
Tomas Votruba Avatar answered Nov 15 '22 08:11

Tomas Votruba


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);
    }
like image 28
Robert Avatar answered Nov 15 '22 09:11

Robert