4
votes

I'm trying to find a good way for handling my access controls in Symfony2.

My requirements:

  • 90% of my application can only be accessed by authenticated users
  • in many controllers I need to check if the user is the owner
  • there are also some differences for different user roles

What I've done already:

  • installed JMSSecurityExtraBundle to check permissions via annotation
  • defined global ace's for my entity classes
  • I create an ace for the owner for every object during the create process

The check for owner and roles is no Problem. I only want to define in a global way that a user has to be authenticated and for exceptions (sites that can be accessed anonymous) I want to define it separated (best via annotations). I don't want to do this via routing pattern.

2

2 Answers

0
votes

I'm not sure it be what you're looking for, but did you try with Event Listener ?

You can make your verification in the onKernelController method. Then, you will can create different Interfaces and check the type of your controller in the listener.

0
votes

class AceBuilderListener implements EventSubscriber{

private $container;

public function setContainer($container){
    $his->container = $container;
}

public function getSubscribedEvents()
{
    return array(
            Events::prePersist,
            Events::preUpdate,
            Events::preRemove,
            Events::postPersist,
            Events::postUpdate,
            Events::postRemove,
            Events::loadClassMetadata,
    );
}

public function prePersist(){ echo( get_class($entity) ); }
public function preUpdate(){ echo( get_class($entity) ); }
public function preRemove(){ echo( get_class($entity) ); }
public function postPersist(){ echo( get_class($entity) ); }

public function postUpdate(LifecycleEventArgs $args)
{

    $entity = $args->getEntity();
    $entityManager = $args->getEntityManager();

    echo get_class($entity);
    // perhaps you only want to act on some "Product" entity
    if ($entity instanceof Product | x) {
        // ... do something with the Product
    }
}

public function postRemove(){ die( get_class($entity) ); }

public function loadClassMetadata( LoadClassMetadataEventArgs $args ){ 
    $classMetadata = $args->getClassMetadata();
    $entityManager = $args->getEntityManager();

            $user = $this->container->get('security.context')->getToken()->getUser();

            // you can check here if isGranted();
            // and get the entity from the object $classMetadata  
            $this->container->get('security.context')->isGranted('EDIT', $entity);

} 

}