leobrl
leobrl

Reputation: 969

Symfony Validator - Check password length and content BEFORE hashing

I created a password validation, but when I insert a new user, this validation is triggered after encrypting the password ...

I am using Argon2Id so the password will be longer than 30 characters ...

My validator (config/validator/validation.yaml) :

App\Entity\Utilisateur:
  properties:
    mdp:
      - Length:
          min: 6
          max: 30
          minMessage: 'Votre mot de passe doit faire au moins {{ limit }} caractères'
          maxMessage: 'Votre mot de passe doit faire moins de {{ limit }} caractères'

setMdp in Utilisateur.php :

public function setMdp(string $mdp): self
    {
        $this->mdp = password_hash($mdp, PASSWORD_ARGON2ID);
        return $this;
    }

So, when I insert the new user, I got an error from Symfony validator who tell me my password exceed 30 characters.

How can I trigger this validator before encrypting my password?

Thanks!

Upvotes: 1

Views: 1565

Answers (1)

GasKa
GasKa

Reputation: 663

Your approach is not correct! You should let set method to be as-is:

public function setMdp(string $mdp): self
{
    $this->mdp = $mdp;
    return $this;
}

Instead, you can encode password after validating form in your controller like this:

public function createAccount(Request $request, UserPasswordEncoderInterface $passwordEncoder) {
    ...
    $createAccountForm = $this->createForm(CreateAccountFormType::class);
    $createAccountForm->handleRequest($request);
    if ($createAccountForm->isSubmitted() && $createAccountForm->isValid()) {
        $user = $createAccountForm->getData();
        $user->setPassword($passwordEncoder->encodePassword($user, $user->getPlainPassword()));

        // flush, persist and other changes
    }
}

But, as you can see in my example, I'm encoding $user->getPlainPassword() which a getter for an unmapped (to doctrine) entity property and this is the only job for that property.

Upvotes: 3

Related Questions