gview gview - 1 year ago 64
PHP Question

How should you validate input to a password setter?

I've been looking at my options for Symfony2 validation. The problem is this:

I have a Member class that hashes a password in the setPassword method:

public function setPassword($password)
$this->password = Encrypt::cryptPassword($password);

The hash is a long string that exists regardless of the original input.

For this reason validation like this is useless:

* @Assert\NotBlank()
* @Assert\Length(
* min = "8",
* max = "15",
* minMessage = "Your password must be at least {{ limit }} characters",
* maxMessage = "Your password cannot be longer than {{ limit }} characters"
* )

The validation is triggered because the hash string is created regardless of the validity of the input.

I looked at trying a getter validation, but this also seems to be a dead end, because again, what I really want to validate is the original input to setPassword() and getting the hash value after setPassword has created a hash value isn't helpful.

What's the recommended approach to this that works with the existing Validation component that will let me validate the original user input?


Although I accepted the answer, it is not really viable. It did cause
me to focus in on the lifecycle callback system which will probably be
part of the solution.

Given the current suggestion, once the password is encoded the first
time, validation is exceeded anytime you try and edit the entity
because the hashed password is of course not the input and cannot be
decrypted into the original input.

I'm experimenting now with a separate attribute in the entity, purely
for the entry of the password, along with the use of validation groups
to trigger the use of validation in certain circumstances (new user
creation/ password change) while omitting it in other cases. I do
plan to make use of the prePersist and preUpdate callbacks to do the
encoding of the password.

Just for the record, this is being employed in an application that
provides a REST api, as well as administration tools and a web front
end for selected functionality.

Answer Source

Use doctrine lifecycles and never modify the behavior of a setter !


// ...

 * @ORM\Entity()
 * @ORM\HasLifecycleCallbacks()
class Member
    public function setPassword($password)
        $this->password = $password;

     * @ORM\PrePersist
     * First time you save the entity
    public function prePersist()
        $this->password = Encrypt::cryptPassword($this->password);

In this example, password is not encoded until you save your member object, so it can be validate by an assert !

However Symfony2 security comes with a firewall that can encrypt the password of members and simply do the job for you:


Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download