4
votes

I have Users in DB, their passwords are encrypted with:

security:
    encoders:
        AppBundle\Entity\User:
            algorithm: bcrypt

After a User's registration, the password used to encoded by:

        $encoder = $this->container->get('security.password_encoder');
        $encoded = $encoder->encodePassword($user, $password);

Where $user came from

$form->handleRequest ( $request );

After it's form was validated. $password is a plain text in this case. When it's completed, i see the hashed string in my object:

$2y$13$DF.Es7XjAQKrRklZXRyLX.YYzRG7gC3XOLA72eul6BEVigMbvir4C

In my controller, when i try to modify an User's password, i've added a new field, like this:

$form->add ( 'oldpassword', 'password', array('label'=>'old password', 'required'=>true, 'error_bubbling'=>true, 'mapped' => false)  );

So I can reach it's value from

$form->get('oldpassword')->getData()

My goal is to check the "oldpassword" field against the saved one ($user->getPassword()) right before flushing the object to the database.

Now, it's seems like:

        $form->handleRequest ( $request );
        if ($form->isSubmitted ()) {

        if ( !$functions->passwordVerify($user, $form->get('oldpassword')->getData()) ) {
            $form->get ( 'oldpassword' ) ->addError ( new FormError ( "Your current password is invalid" ) );               
        }

Where $functions is an injected service's function:

    public function passwordVerify($user=null, $oldpassword=null) {
        $encoder = $this->container->get('security.password_encoder');
        $valid = $encoder->isPasswordValid($user, $oldpassword);
        return $valid;
    }

Somehow, the $valid variable is always returns with false. The password i wrote for "oldpassword" is exactly the same i used to in registration (with encoder see the code above).

Looks like never generates the same hash/token...

Thank you in advance.

1
Be sure you're not changing the salt.. - xurshid29
Not sure about symfony, but to me it seems that you pass the wrong parameters, a password encoder will hardly fetch the password from the user. Shouldn't it be $encoder->encodePassword($password); and $encoder->isPasswordValid($password, $oldpassword);? Have a look at the documentation. - martinstoeckli

1 Answers

0
votes

You should try using the inbuilt UserPassword validator constraint, it's designed just for this task.