Search code examples
phpsymfonysecuritycontrollerrestriction

Access forbidden based user role after change it


In my website I want to give to some users the ability to change their role clicking a button. I implemented it in the following way:

$post = Request::createFromGlobals();
if($post->request->has('change') && $user->hasRole('ROLE_MEDIA') == False){
        $em = $this->getDoctrine()->getManager();
        $user->setRoles(array('ROLE_MEDIA'));
        $em->flush();
 }

It is working fine, after check the database and I can recover in the main controller the flag without problems. The problem is the following: after clicking the button and access to restricted pages to users who have the ROLE_MEDIA,I am getting a 403 error. It seems that Symfony doesn't detect the new user role. I am restricting some pages using the following code:

/**
*
* @Security("has_role('ROLE_MEDIA')")
*/

I don't understand the problem because I can access the right values in my controller... Thanks in advance


Solution

  • I found that the easiest solution is to refresh session by regenerating session ID:

    $post = Request::createFromGlobals();
    if($post->request->has('change') && $user->hasRole('ROLE_MEDIA') == False){
            $em = $this->getDoctrine()->getManager();
            $user->setRoles(array('ROLE_MEDIA'));
            $em->flush();
            $this->get('session')->migrate();
     }