m.deye
m.deye

Reputation: 51

how to manage roles in symfony

I have a registration form allowing the administratuer to create a user and to assign him a well-defined role. after creation if I try to connect with the role I have, the application shows me a resource access error

secyrity.yaml

security:
    encoders:
        App\Entity\User:
            algorithm: bcrypt
    # https://symfony.com/doc/current/security.html#where-do-users-come-from-user-providers
    providers:
        in_memory: { memory: ~ }
        in_database:
            entity:
                class: App\Entity\User
                property: name
    role_hierarchy:
        # Un admin hérite des droits d'utilisateur et de souscommission
        ROLE_ADMIN:       ROLE_SOUSCOMMISSION
        # On garde ce rôle superadmin, il nous resservira par la suite
        #ROLE_SUPER_ADMIN: [ROLE_ADMIN, ROLE_ALLOWED_TO_SWITCH]

    firewalls:
        dev:
            pattern: ^/(_(profiler|wdt)|css|images|js)/
            security: false
        main:
            anonymous: true

            provider:
                in_database

            form_login:
                login_path: security_login
                check_path: security_login
            logout:
                path: security_logout
                target: home

            # activate different ways to authenticate

            # http_basic: true
            # https://symfony.com/doc/current/security.html#a-configuring-how-your-users-will-authenticate

            # form_login: true
            # https://symfony.com/doc/current/security/form_login_setup.html

    # Easy way to control access for large sections of your site
    # Note: Only the *first* access control that matches will be used
    access_control:
        - { path: ^/admin, roles: ROLE_ADMIN }
        - { path: ^/admin/traitement, roles: ROLE_SOUSCOMMISSION }

actions on my cotroller In my controller I defined his actions

 /**
     * @Route("/inscription", name="security")
    */
    public function inscription(Request $request, ObjectManager $manager, UserPasswordEncoderInterface $encoder)
    {
        $user= new User();
        $form = $this->createForm(UserType::class, $user);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $hash = $encoder->encodePassword($user, $user->getPassword());
            $user->setPassword($hash);
            $manager->persist($user);
            $manager->flush();

            return $this->redirectToRoute('security_login');
        }



        return $this->render('security/inscrie.html.twig', [

            'form' => $form->createView(),
        ]);
    }

     /**
     * @Route("/login", name="security_login")
    */
    public function login(AuthenticationUtils $authenticationUtils)
    {
        $error = $authenticationUtils->getLastAuthenticationError();
        $lastUsername = $authenticationUtils->getLastUsername();

        return $this->render('security/login.html.twig', [ 

        'last_username'=>$lastUsername,

        'error' =>$error
    ]);
}

UserType.php

<?php

namespace App\Form;

use App\Entity\User;
use Symfony\Component\Form\AbstractType;
use Symfony\Component\Form\FormBuilderInterface;
use Symfony\Component\OptionsResolver\OptionsResolver;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
use Symfony\Component\Form\Extension\Core\Type\PasswordType;

class UserType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('email')
            ->add('name')
            ->add('password',  PasswordType::class)
            ->add('password_confirme', PasswordType::class)
            ->add('roles', ChoiceType::class, [
                'label' =>'Role',
                'placeholder'=>'',
                'multiple'=>true,
                'choices' =>[
                    'Administrateur'=>'ROLE_ADMIN',
                    'Traiteur ' =>'ROLE_SOUSCOMMISSION',
                ],
            ])
        ;
    }

    public function configureOptions(OptionsResolver $resolver)
    {
        $resolver->setDefaults([
            'data_class' => User::class,
        ]);
    }
}

User.php

<?php

namespace App\Entity;

use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\Validator\Constraints\EqualTo;
use Symfony\Component\Validator\Constraints as Assert;
use Symfony\Component\Security\Core\User\UserInterface;

/**
 * @ORM\Entity(repositoryClass="App\Repository\UserRepository")
 */
class User implements UserInterface
{
    /**
     * @ORM\Id()
     * @ORM\GeneratedValue()
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @ORM\Column(type="string", length=255)
     */
    private $name;

    /**
     * @ORM\Column(type="string", length=255)
     * @Assert\EqualTo(propertyPath= "password_confirme")
     */
    private $password;
    /**
     * @Assert\EqualTo(propertyPath= "password", message="Vous n'avez pas taper le meme mot de passe")
     */
    public $password_confirme;

    /**
     * @ORM\Column(type="string", length=255)
     */
    private $email;

    /**
     * @ORM\Column(type="array", nullable=true)
     */
    private $roles = [];



    public function getId(): ?int
    {
        return $this->id;
    }

    public function getName(): ?string
    {
        return $this->name;
    }

    public function setName(string $name): self
    {
        $this->name = $name;

        return $this;
    }

    public function getPassword(): ?string
    {
        return $this->password;
    }

    public function setPassword(string $password): self
    {
        $this->password = $password;

        return $this;
    }

    public function getEmail(): ?string
    {
        return $this->email;
    }

    public function setEmail(string $email): self
    {
        $this->email = $email;

        return $this;
    }


    public function getUserName(){}

    public function eraseCredentials(){}
    public function getSalt(){}

        public function getRoles(){
            return $this->roles;
        }

        public function setRoles(?array $roles): self
        {
            $this->roles = $roles;

            return $this;
        }




}

when I try to connect with the role ROLE_SOUCOMMISSION I have a type error Access Denied. help please!!

Upvotes: 0

Views: 434

Answers (2)

rapaelec
rapaelec

Reputation: 1330

just change position of access control in security.yaml to add access with user to had ROLE_SOUSCOMMISSION because :

Symfony starts at the top of the list and stops when it finds the first match

documentation : access_control

access_control:
    - { path: ^/admin/traitement, roles: ROLE_SOUSCOMMISSION }
    - { path: ^/admin, roles: ROLE_ADMIN }

thanks

Upvotes: 1

It's because /admin/traitement is under /admin, so it's impossible to go to this page because you need the role ROLE_ADMIN to go to /admin and after. You need to inverse them or set /admin with role ROLE_SOUSCOMMISSION

Upvotes: 1

Related Questions