1

I wanna write a custom Security handler and this will be a simple ACL which restrict data by user id. I don't want use a standart ACL, no need to use all functional and create aditional database with permissions.

So I create my new handler and now I recieve $object as Admin class. With Admin class I can restrict access to services but can't restrict any rows in service.

The question is how I can recieve Entities and check permission on Entities like this:

  public function isGranted(AdminInterface $admin, $attributes, $object = null)
  {
    if ($object->getUserId()==5){
      return true
    }
  }
user1156168
  • 936
  • 13
  • 32

1 Answers1

2

Overwrite the security handler in sonata config:

sonata_admin:
    title: "Admin"
    security:
         handler: custom.sonata.security.handler.role  

Create your service:

custom.sonata.security.handler.role:
        class: MyApp\MyBundle\Security\Handler\CustomRoleSecurityHandler
        arguments:
            - @security.context
            - [ROLE_SUPER_ADMIN, ROLE_ADMIN, ROLE_USER]
            - %security.role_hierarchy.roles%

Last step, but not less important is to create your class, retrieve your user and based by his credentials allow/deny access:

/**
* Class CustomRoleSecurityHandler
*/
class CustomRoleSecurityHandler extends RoleSecurityHandler
{
    protected $securityContext;

    protected $superAdminRoles;

    protected $roles;

    /**
     * @param \Symfony\Component\Security\Core\SecurityContextInterface $securityContext
     * @param array $superAdminRoles
     * @param $roles
     */
    public function __construct(SecurityContextInterface $securityContext, array $superAdminRoles, $roles)
    {
        $this->securityContext = $securityContext;
        $this->superAdminRoles = $superAdminRoles;
        $this->roles = $roles;
    }

    /**
     * {@inheritDoc}
     */
    public function isGranted(AdminInterface $admin, $attributes, $object = null)
    {
        /** @var $user User */
        $user = $this->securityContext->getToken()->getUser();

        if ($user->hasRole('ROLE_ADMIN')){
            return true;
        }

        // do your stuff
    }
}
Cristian Bujoreanu
  • 1,147
  • 10
  • 21