M
M
Mysterion2018-12-11 11:58:26
symfony
Mysterion, 2018-12-11 11:58:26

What is a good practice for defining write access in Symfony 4?

Hello.
Access to pages in general is defined via security.yaml:

access_control:
        - { path: ^/cp/login, roles: IS_AUTHENTICATED_ANONYMOUSLY }
        - { path: ^/cp/register, roles: IS_AUTHENTICATED_ANONYMOUSLY }
        - { path: ^/cp/forgot-password, roles: IS_AUTHENTICATED_ANONYMOUSLY }
        - { path: ^/console, roles: IS_AUTHENTICATED_FULLY }

Thus, only authorized users have access to all /console routes.
But there is a /console/{item<[1-9]\d*>} route, where only the owner of the entry in the database should have access. These records have a user_id column where the owner is determined through a many-to-one relationship.
Here is the controller method itself:
/**
     * @Route("/{item<[1-9]\d*>}", name="console_item")
     */
    public function actionConsoleItem(Console $console)
    {
        return $this->render('console/console_item.html.twig', [
            'console' => $console,
        ]);
    }

Thus, through ParamConverter, a record is taken from the database by the item parameter, but how to check if the value from user corresponds to the $this-getUser() object?
Maybe there is some possibility for the controller class as a whole to specify a method for determining the presence of access?
In the same controller, I have a method where I display all user items according to the condition ['user' => $this->getUser()]
In Entity:
/**
     * @ORM\ManyToOne(targetEntity="App\Entity\User", inversedBy="id")
     */
    private $user;
...
    public function getUser(): User
    {
        return $this->user;
    }

    public function setUser(User $user): self
    {
        $this->user = $user;

        return $this;
    }

Answer the question

In order to leave comments, you need to log in

2 answer(s)
D
Dmitry, 2018-12-11
@Mysterion

Maybe you can write directly in the controller?

if ($this->getUser()->getId() !== $console->getUser()->getId()) {
    throw new UnauthorizedHttpException('Access denied');
}

I
ig0r88, 2018-12-11
@ig0r88

https://symfony.com/doc/current/security/voters.html
Abstract: https://symfony.com/doc/current/best_practices/sec...

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question