Change role of one user no working with Symfony2

483 views Asked by At

Sorry if this question has been asked many times but I didn't found any solution on the Web. So, I just have installed FOSUserBundle and I've created 2 users on my application with the console. The problem is they don't have any role. So in on controller, I get the user Entity and y set his role but when I try to access to a page restricted for admin, it says access denied. Moreover, the roles has no changed on the databse. My code in the controller :

$user = $this->container->get('security.context')->getToken()->getUser();
$user->setRoles('ROLE_ADMIN');
if (!$this->get('security.context')->isGranted('ROLE_ADMIN')){
    throw new AccessDniedException('Access Denied !');
}

Anyone have an idea ? Thanks in advance !

1

There are 1 answers

1
AudioBubble On BEST ANSWER

It is a very bad practice to set a user role in your controller if you want to keep them away from the controller in the first place. I hope you use this line of code for testing only.

The FOSUserBundle provides a number of command line utilities to help manage your application's users.

The one you need is:

$ php app/console fos:user:promote testuser ROLE_ADMIN

Replace testuser with your username.

Did you also define your roles in your firewall?