D
D
drboboev2018-10-31 11:00:57
symfony
drboboev, 2018-10-31 11:00:57

How to organize roles in Symfony?

Good afternoon.
Essence of a question: there is an application, there are users. Each user belongs to some user group, I want to store these groups in the database. Each group has a set of rights. The scheme is not hierarchical, the groups are completely different and these groups (roles) can be changed in the admin panel, that is, to give and take away any rights.
Actually a question - how to make it in Symfony?
I looked at the docks, I saw that this can be done in security.yaml, but there will be quite a lot of rights, and there will be an inexact set of roles, maybe 10, or maybe 20. And every time a role appears, I would not want to go into secutiry .yaml to add roles.
It seems that something like checking isGranted when a route is requested, and if there are rights, the user sees the page.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
B
BoShurik, 2018-10-31
@BoShurik

security.yml

security:
    access_control:
        - { path: ^/ }

use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\Security\Core\Authentication\Token\TokenInterface;
use Symfony\Component\Security\Core\Authorization\Voter\VoterInterface;
use Symfony\Component\Security\Core\Security;

class RequestVoter implements VoterInterface
{
    /**
     * @var Security
     */
    private $security;

    public function __construct(Security $security)
    {
        $this->security = $security;
    }

    /**
     * @inheritDoc
     */
    public function vote(TokenInterface $token, $subject, array $attributes)
    {
        if (!$subject instanceof Request) {
            return self::ACCESS_ABSTAIN;
        }

        $route = $subject->attributes->get('_route');
        $routeRole = $this->getRoleByRoute($route);

        if ($this->security->isGranted($routeRole)) {
            return self::ACCESS_GRANTED;
        }

        return self::ACCESS_DENIED;
    }

    protected function getRoleByRoute(string $route): string
    {
        // ...
    }
}

I
Ivan Shumov, 2018-10-31
@inoise

Give me a sec. Symfony still doesn't have normal RBAC/ACL?

O
Oleg Bondarenko, 2018-10-31
@overking

In any case, you should specify the roles (more precisely, the hierarchy of roles) in security.yaml, as well as indicate in the is_granted (ROLE_XXXX) code. In the admin panel, you can add and remove roles (a couple of lines sonata admin). If you want to do all this through some kind of ready-made interface - cut it yourself or look for a bundle for this, I've already seen this somewhere.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question