diff --git a/src/Controller/Admin/PostCrudController.php b/src/Controller/Admin/PostCrudController.php index 5c62d24c4209ab1dd2fe7b1829caf732a2585842..0404bf11124b962210310923f88081cc4564ee40 100644 --- a/src/Controller/Admin/PostCrudController.php +++ b/src/Controller/Admin/PostCrudController.php @@ -3,6 +3,9 @@ namespace App\Controller\Admin; use App\Entity\Post; +use App\Security\Voter\PostVoter; +use EasyCorp\Bundle\EasyAdminBundle\Config\Action; +use EasyCorp\Bundle\EasyAdminBundle\Config\Actions; use EasyCorp\Bundle\EasyAdminBundle\Config\Crud; use EasyCorp\Bundle\EasyAdminBundle\Config\Filters; use EasyCorp\Bundle\EasyAdminBundle\Controller\AbstractCrudController; @@ -56,4 +59,15 @@ class PostCrudController extends AbstractCrudController return $filters->add(ChoiceFilter::new('status') ->setChoices(['draft' => 'draft', 'published' => 'published'])); } + + public function configureActions(Actions $actions): Actions + { + return $actions->update(Crud::PAGE_INDEX, Action::EDIT, + function (Action $action) { + return $action->displayIf(fn($entity) => $this->isGranted(PostVoter::POST_OWNER_EDIT, $entity)); + })->update(Crud::PAGE_INDEX, Action::DELETE, + function (Action $action) { + return $action->displayIf(fn($entity) => $this->isGranted(PostVoter::POST_OWNER_DELETE, $entity)); + }); + } } diff --git a/src/Security/Voter/PostVoter.php b/src/Security/Voter/PostVoter.php index 8f319d692ac536f6cfd466ea48b34cc716a104b6..daa469efa0fea5e025631b17edb159fc09053324 100644 --- a/src/Security/Voter/PostVoter.php +++ b/src/Security/Voter/PostVoter.php @@ -5,12 +5,22 @@ namespace App\Security\Voter; use App\Entity\Post; use Symfony\Component\Security\Core\Authentication\Token\TokenInterface; use Symfony\Component\Security\Core\Authorization\Voter\Voter; +use Symfony\Component\Security\Core\Security; use Symfony\Component\Security\Core\User\UserInterface; class PostVoter extends Voter { const POST_OWNER_EDIT = 'post_owner_edit'; const POST_OWNER_DELETE = 'post_owner_delete'; + /** + * @var Security + */ + private Security $security; + + public function __construct(Security $security) + { + $this->security = $security; + } protected function supports(string $attribute, $subject): bool { @@ -37,7 +47,10 @@ class PostVoter extends Voter case self::POST_OWNER_DELETE: // logic to determine if the user can VIEW // return true or false - if ($subject->getAuthor() == $user){ + if ($this->security->isGranted('ROLE_ADMIN')) { + return true; + } + if ($subject->getAuthor() == $user) { return true; } break;