Bonjour,

J'essaie de chiffrer les mots de passe avec la version 3.5.9 de Symfony mais je n'obtiens aucun résultat donc mon mot de passe reste en clair:

Dans mon controller:

<?php

namespace App\Controller;

use App\Entity\User;
use App\Form\RegisterType;
use Doctrine\ORM\EntityManagerInterface;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;

class SecurityController extends AbstractController
{
    private $passwordHasher;

    public function __construct(UserPasswordHasherInterface $passwordHasher)
    {
        $this->passwordHasher = $passwordHasher;
    }

    #[Route('/register', name: 'security_register')]
    public function register(Request $request, UserPasswordHasherInterface $encodage): Response
    {
        $user = new User();
        $form = $this->createForm(RegisterType::class, $user);

        if ($form->isSubmitted() && $form->isValid()) {
            // $user->setRoles(['ROLE_USER']);

            $user->setPassword($this->passwordHasher->hashPassword($user, $user->getPassword()));

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

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

        return $this->render('security/index.html.twig', [
            'controller_name' => "Formulaire d'inscription",
            'form' => $form->createView(),
        ]);
    }
}

Mon form:

<?php

namespace App\Form;

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

class RegisterType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options): void
    {
        $builder
            ->add('username')
            ->add('firstname')
            ->add('lastname')
            ->add('email')
            ->add('password',PasswordType::class)
            ->add('passwordConfirm',PasswordType::class)
            // ->add('createdAt')
        ;
    }

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

Mon Entity:

<?php

namespace App\Entity;

use App\Repository\UserRepository;
use Doctrine\Common\Collections\ArrayCollection;
use Doctrine\Common\Collections\Collection;
use Doctrine\ORM\Mapping as ORM;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;
use Symfony\Component\Security\Core\User\PasswordAuthenticatedUserInterface;
use Symfony\Component\Security\Core\User\UserInterface;
//Pour la validation du formulaire d'inscription:
use Symfony\Component\Validator\Constraints as Assert;

 /**
 * @ORM\Entity(repositoryClass=UserRepository::class)
 * @method string getUserIdentifier()
 */
class User implements UserInterface, PasswordAuthenticatedUserInterface
{
    /**
     * @ORM\Id
     * @ORM\GeneratedValue
     * @ORM\Column(type="integer")
     */
    private $id;

    /**
     * @Assert\Length(min=3,max=50)
     * @ORM\Column(type="string", length=255)
     */
    private $username;

    /**
     * @Assert\Length(min=3,max=50)
     * @ORM\Column(type="string", length=255)
     */
    private $firstname;

    /**
     * @Assert\Length(min=3,max=50)
     * @ORM\Column(type="string", length=255)
     */
    private $lastname;

    /**
     * @Assert\Email(message="L'email saisi n'est pas valide")
     * @ORM\Column(type="string", length=255)
     */
    private $email;

    /**
     * @Assert\Length(min=8,max=50)
     * @ORM\Column(type="string", length=255)
     */
    private $password;

    /**
     * @ORM\Column(type="datetime_immutable")
     */
    private $createdAt;

    /**
     * @ORM\OneToMany(targetEntity=Article::class, mappedBy="author")
     */
    private $articles;

    //////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    public function __toString()
    {
    /*Pour accepter la sélection dans les zones de liste (Fiche article->author...)*/
    return $this->firstname. ' ' .$this->lastname;
    //Ajout pour l'erreur de conversion en chaine à l'affichage du nom de l'auteur en page home ({{ article.author }})
    return (string) $this->getUsername();
    }
    //////////////////////////////////////////////////////////////////////////////////////////////////////////////////

    /**
     * @Assert\EqualTo(propertyPath="password", message="Les 2 mots de passe doivent être identiques")
     */
    private $passwordConfirm;

    public function __construct()
    {
        $this->articles = new ArrayCollection();

        //Pour insérer la date par défaut en création d'un user
        //////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        $this->createdAt = new \DatetimeImmutable();
        //////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        }

        //Pour insérer la confirmation du mot de passe
        //////////////////////////////////////////////////////////////////////////////////////////////////////////////////
        public function getPasswordConfirm(): ?string
        {
            return $this->passwordConfirm;
        }

        public function setPasswordConfirm(string $passwordConfirm): string
        {
            $this->passwordConfirm = $passwordConfirm;

            return $passwordConfirm;
        }
        //////////////////////////////////////////////////////////////////////////////////////////////////////////////////

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

    public function getUsername(): ?string
    {
        return $this->username;
    }

    public function setUsername(string $username): self
    {
        $this->username = $username;

        return $this;
    }

    public function getFirstname(): ?string
    {
        return $this->firstname;
    }

    public function setFirstname(string $firstname): self
    {
        $this->firstname = $firstname;

        return $this;
    }

    public function getLastname(): ?string
    {
        return $this->lastname;
    }

    public function setLastname(string $lastname): self
    {
        $this->lastname = $lastname;

        return $this;
    }

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

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

        return $this;
    }

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

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

        return $this;
    }

    public function getCreatedAt(): ?\DateTimeImmutable
    {
        return $this->createdAt;
    }

    public function setCreatedAt(\DateTimeImmutable $createdAt): self
    {
        $this->createdAt = $createdAt;

        return $this;
    }

    /**
     * @return Collection|Article[]
     */
    public function getArticles(): Collection
    {
        return $this->articles;
    }

    public function addArticle(Article $article): self
    {
        if (!$this->articles->contains($article)) {
            $this->articles[] = $article;
            $article->setAuthor($this);
        }

        return $this;
    }

    public function removeArticle(Article $article): self
    {
        if ($this->articles->removeElement($article)) {
            // set the owning side to null (unless already changed)
            if ($article->getAuthor() === $this) {
                $article->setAuthor(null);
            }
        }

        return $this;
    }

    public function getRoles()
    {
        return ['ROLE_USER'];
    }
    public function setRoles()
    {
        return ['ROLE_USER'];
    }
    /**
     * Returning a salt is only needed, if you are not using a modern
     * hashing algorithm (e.g. bcrypt or sodium) in your security.yaml.
     *
     * @see UserInterface
     */
    public function getSalt(): ?string
    {
        return null;
    }

    /**
     * @see UserInterface
     */
    public function eraseCredentials()
    {
        // If you store any temporary, sensitive data on the user, clear it here
        // $this->plainPassword = null;
    }
}

Je vous remercie de votre aide

1 réponse


barpoi78
Auteur
Réponse acceptée

C'est bon pour moi.

Mon securityController.php:

<?php

namespace App\Controller;

use App\Entity\User;
use App\Form\RegisterType;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Routing\Annotation\Route;
use Symfony\Bundle\FrameworkBundle\Controller\AbstractController;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\PasswordHasher\Hasher\UserPasswordHasherInterface;

class SecurityController extends AbstractController
{
private $passwordHasher;

public function __construct(UserPasswordHasherInterface $passwordHasher)
{
    $this->passwordHasher = $passwordHasher;
}

#[Route('/register', name: 'security_register')]
public function register(Request $request, UserPasswordHasherInterface $encoder): Response
{
    $user = new User();
    $form = $this->createForm(RegisterType::class, $user);

    // Analyse de la requête par le formulaire
    $form->handleRequest($request);
    if($form->isSubmitted() && $form->isValid()){
         //Traitement des données reçues du formulaire
        $user->setPassword($this->passwordHasher->hashPassword($user, $user->getPassword()));

        $entityManager = $this->getDoctrine()->getManager();
        $entityManager->persist($user);
        $entityManager->flush();
        return $this->redirectToRoute('home');
        // dd($user);
    }

        return $this->render('security/index.html.twig', [
            'controller_name' => "Formulaire d'inscription",
            'form' => $form->createView(),
        ]);
}

}