A
A
Andrew2015-05-30 14:29:03
symfony
Andrew, 2015-05-30 14:29:03

Symfony: how to create and work with roles from the database?

Help clear up.
I can't figure out how to work with roles in the symphony.
For example: I need N roles, according to them I plan access control.
There are respectively Entity: Role and Users.
I add a fixture to the Role, 4 roles: ROLE_USER, ROLE_1, ROLE_2, ROLE_ADMIN
How can I further define roles for the user when registering.
Ie:
1) At the registration stage, I need to provide the user with a choice of ROLE_1, ROLE_2.
To do this, when creating the form, I need to specify "choice" ROLE_1/ROLE_2. But how do you get them?
Do I understand correctly - the form needs to be declared as a service and the EntytyManager passed to it - so I can get
roles from the base.
Is this the correct option?
1.1)
But it's not "nice" to use when making a request and later on when checking for a role
, use a magic string, like
- SELECT * FROM Roles WHERE name = 'ROLE_1'
-if($role->getName == "ROLE_1")
etc
It turns out necessary to create in advance some constants in the project for these roles?
2) When describing the access_control section:
- { path: ^/, roles: ROLE_USER } ROLE_1/ROLE_2 -
{ path: ^/admin, roles: ROLE_ADMIN}
).
Is there any workaround or best practice for these questions/problems?
I apologize for the possible confusion in the description of the problem (s). Perhaps there is a lack of some knowledge, skilochka.
Thanks a lot for the advice.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Denis, 2015-05-30
@prototype_denis

$form->add( 'roles', 'choice', [
    'choices' => $this->container->getParameter('security.role_hierarchy.roles'),
    'multiple'=> true 
]);
    
// $this->get('security.role_hierarchy')

Forget about the form.
Use listeners and dynamically change whatever you want...
Now for the questions "What if I change the role? Do I need to set a constant?".
Give the ROLE entity an additional boolean field to register.
Create your manager who will give them and "draw" the form.
$form->add( 'roles', 'choice', [
    'choices'  => $this->myRoleManager->getRegisterRoles(),
    'multiple' => true | false,
   // ... 
]);

By standard roles...
ROLE_USER, ROLE_ADMIN, ROLE_SUPER_ADMIN etc...
Better leave them.
And in the new roles, make the standard children.
Firstly, in case of a conditional fall of the database with users, you will have a "live" architecture of roles.
When changing roles, they will automatically be is_granted(STANDART_ROLE)
Next... In the controller or templates, already pull your roles.
And probably the first thing to say.
Replace security.role_hierarchy with your service, where you will assign roles from the database.
The question is voluminous ... I tried to explain it as simply as possible.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question