We have moved our forum to GitHub Discussions. For questions about Phalcon v3/v4/v5 you can visit here and for Phalcon v6 here.

Behavior only when Column changed?

hi i our project we use an Behavior that automatic uses md5 on the password column before the Model is saved ('beforeSave')

the problem is that if something else is changed beside the password, the Behavior does still trigger and does call md5 on the already hashed Password.

so is there an nice way to get only called when an specific column has changed?



98.9k

You can better use "beforeCreate" to hash the password, this is only triggered when the model is being created also note that md5 is not recommended as hashing algorithm for passwords, it's recommended using blowfish: https://docs.phalcon.io/en/latest/reference/security.html#password-hashing



608

hm okay but what is if i also want that when i use $model->password = "real one" its automatically gets changed after save? Or i use ->save($this->getPost()) ?



98.9k

Check if the password in the model is a legacy password before hash it:

<?php

class Users extends Phalcon\Mvc\Model
{

    public $id;

    public $email;

    public $password;   

    public function beforeSave()
    {
        $security = $this->getDI()->getSecurity();
        if (!$security->isLegacyHash($this->password)) {
            $this->password = $security->hash($this->password);
        }
    }
}

Note that $user ->save($this->request->getPost()) without a white list could lead to mass assignment attacks changing values that aren't allowed to be changed such like profiles or usernames.