I wanna use the Role Handler security on my Sonata admin dashboard. I work with Symfony 2.3.
In the doc, I have:
Each permission is relative to an admin: if you try to get a list in FooAdmin (declared as sonata.admin.demo.foo service), Sonata will check if the user has the
ROLE_SONATA_ADMIN_DEMO_FOO_EDITrole.
As I understand, if I have services such as:
sonata.admin.articlesonata.admin.usersonata.admin.tagThen I need to create an edit role, being a list of those 3 elements:
ROLE_SONATA_ADMIN_ARTICLE_EDIT and ROLE_SONATA_ADMIN_USER_EDIT and ROLE_SONATA_ADMIN_TAG_EDIT
But I would rather like to create access more generals, for example, in my case, simply do: ROLE_SONATA_ADMIN_EDIT instead and of a list of three.
Is there a simple way to do this with this bundle?
You can easily do this by overriding the Sonata\AdminBundle\Security\Handler\RoleSecurityHandler class and getBaseRole method:
# AppBundle/Security/Handler/MyRoleSecurityHandler.php
namespace AppBundle\Security\Handler;
use Sonata\AdminBundle\Admin\AdminInterface;
use Sonata\AdminBundle\Security\Handler\RoleSecurityHandler;
class MyRoleSecurityHandler extends RoleSecurityHandler
{
/**
* {@inheritDoc}
*/
public function getBaseRole(AdminInterface $admin)
{
return 'ROLE_SONATA_ADMIN_%s';
}
}
overwrites the sonata service related to this class:
# AppBundle/Resources/config/services.yml
services:
#...
sonata.admin.security.handler.role:
class: AppBundle\Security\Handler\MyRoleSecurityHandler
public: false
arguments: [@security.context, [ROLE_SUPER_ADMIN]]
remember declare these roles in your hierarchy:
# app/config/security.yml
security:
role_hierarchy:
# ...
ROLE_SONATA_ADMIN_LIST: ~
ROLE_SONATA_ADMIN_SHOW: ~
ROLE_SONATA_ADMIN_EDIT: ~
ROLE_SONATA_ADMIN_DELETE: ~
# etc.
once you assign these roles to the user, finally you can to check:
# inside of any admin class
protected function configureListFields(ListMapper $listMapper)
{
if ($this->isGranted('EDIT')) {
# ...
}
}
Warning! The previous sonata roles (ROLE_SONATA_ADMIN_ARTICLE_EDIT, ROLE_SONATA_ADMIN_USER_EDIT, etc.) it will no work. So you could also override the class and the corresponding service of
sonata-project/user-bundle/Security/EditableRolesBuilder.phpto return only the hierarchy of roles.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With