Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

denyAccessUnlessGranted in controller multiple roles

Tags:

php

roles

symfony

I found this controller method that helps filtering access with a role name :

$this->denyAccessUnlessGranted('ROLE_EDIT', $item, 'You cannot edit this item.');

Is it possible to use the same method with multiple roles. I tried something like this but it doesnt seems to work :

$this->denyAccessUnlessGranted(array('ROLE_EDIT', 'ROLE_WHATEVER'), $item, 'You cannot edit this item.');
like image 896
Python Avatar asked Jan 12 '16 15:01

Python


2 Answers

looking into the method shows how it works

protected function denyAccessUnlessGranted($attributes, $object = null, $message = 'Access Denied.')
{
    if (!$this->isGranted($attributes, $object)) {
        throw $this->createAccessDeniedException($message);
    }
}

so you could easily adapt this to your case

in your controller sth. like:

if(!$this->isGranted('ROLE_EDIT', $item) && !$this->isGranted('ROLE_OTHER', $item)){
    throw $this->createAccessDeniedException('not allowed');
}
like image 193
john Smith Avatar answered Oct 24 '22 01:10

john Smith


denyAccessUnlessGranted accepts an array of Role Names, so

$this->denyAccessUnlessGranted(['ROLE_EDIT', 'ROLE_ADMIN'], $item, 'You cannot edit this item.');

so, you should be able to pass all your roles.

Craig

like image 23
Craig Rayner Avatar answered Oct 24 '22 02:10

Craig Rayner