Search code examples
phpsymfonysymfony4symfony-security

How to encode the password for an arbitrary entity in Symfony?


I'm creating organizations table in mysql.

The entity is called Organisation and it has a password field.

When I try to use UserPasswordEncoderInterface it expects the user entity, so this doesn't work. I tried using PasswordEncoderInterface, but it says that the service is not exist. What can be done here ?

This is my code:

   public function register(Request $request, EntityManagerInterface $entityManager, PasswordEncoderInterface $encoder)
    {
        $organisation = new Organisation();

        $form = $this->createForm(OrganisationRegisterType::class, $organisation);

        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $plainPassword = $form->getData()->getPassword();
            $encoded = $encoder->encodePassword($plainPassword, null);
            $organisation->setPassword($encoded);

            $entityManager = $this->getDoctrine()->getManager();
            $entityManager->persist($organisation);
            $entityManager->flush();

            $this->addFlash(
                'success',
                'Organizacija sukurta sėkmingai. Nurodytu el. paštu buvo išsiųsta prisijungimo informacija'
            );
        }

This is the error I get:

Cannot autowire argument $encoder of "App\Controller\OrganisationController::register()": it references interface "Symfony\Component\Security\Core\Encoder\PasswordEncoderInterface" but no such service exists. Did you create a class that implements this interface?`


Solution

  • The PasswordEncoderInterface does not exist.

    The simplest solution would be to make your Organisation class implement the UserInterface.

    The UserPasswordEncoder does not expect a User object, but an object that implements that interface. Even if your organization class is not a "user" per-se, it looks like you want it to have the same interface (username, password...).

    Just change your organization class to implement that interface, and inject the UserPasswordEncoderInterface as usual.