Home > Back-end >  Symfony, How to use DenyAccess with Doctrine object?
Symfony, How to use DenyAccess with Doctrine object?

Time:01-04

I want to control the same user access on some methods in my controller. Currently, I use this :

$this->denyAccessUnlessGranted('ACCESS', $this->Player($toolRepository));

However I am forced to use this line and inject the ToolRepository into each method ...

What would be the easiest way to do it? I saw that there was the IsGranted annotation but my subject needs to be a doctrine object to control access with my Vote.

/**
 * @Route("/player")
 */
class PlayerController extends AbstractController
{
    /**
     * @Route("/", name="player")
     * @throws Exception
     */
    public function Player(ToolRepository $toolRepository): \App\Entity\Tool
    {
        $playerTool = 'TestTool2';
        $tool = $toolRepository->findOneBy(array('libelle' => $playerTool));
        if (!$tool) {
            throw new Exception('Tool : ' . $playerTool . 'not found!');
        }
        return $tool;
    }

    /**
     * @Route("/main", name="player")
     * @IsGranted ("ACCESS", subject="tool")
     * @throws Exception
     */
    public function mainPlayer(PlayerRepository $playerRepository, ToolRepository $toolRepository): Response
    {
        $this->denyAccessUnlessGranted('ACCESS', $this->Player($toolRepository));

        $players = $playerRepository->findAll();
        return $this->render('player/player_mainpage.html.twig', ['players'=>$players]);
    }
}

CodePudding user response:

I think this ressource should answer you: Symfony voters.

You'll put your security logic in your custom voter which will be called in every function of your controller (or every methods where you want to control access) isGranted() function.

Calling your Player() function is a easier way to do this for beginner, you can keep like that but you shouldn't put it in Controller and use a Service instead .

Edit:

You may store your ToolRepository as Controller private property and inject it in a __construct() method so you don't have to inject ToolRepository in each method

  •  Tags:  
  • Related