Model with beforesave and set method

42 views
Skip to first unread message

Anu Tig3r

unread,
Oct 12, 2017, 6:36:12 PM10/12/17
to Fat-Free Framework
Hello friends, I used `beforesave` in my model for some kind of data validation and default `set_` method for automatic formatting data before saving the model.

Let me explain you with the code:

My model:

public function __construct() {
    $saveHandler = function() {
        ....
        if($password === Bcrypt::instance()->hash($confirmation)) {
           $valid = true;
        }
        ....
    };
    $this->beforesave($saveHandler);
}
public function set_password($pswd) {
    return Bcrypt::instance()->hash($pswd);
}


Now, the problem with this code is that, `set_password` method is initializing before the validation, so `password` and `password_confirmation` hash is always different even if the value is same.

xfra35

unread,
Oct 13, 2017, 8:59:53 AM10/13/17
to Fat-Free Framework
Hi Anu,

If I understand you well, you're trying to validate a form where a user fills in a password twice.

Then why not comparing the two raw values?

To answer your question: the hash() method will never return twice the same hash. To compare a password with a hash, use the verify() method.

ved

unread,
Oct 13, 2017, 9:26:00 AM10/13/17
to Fat-Free Framework
What he ^ said.
Also, typing or pasting the the password twice has been (kind of) superseded in favor of using some sort of "show password" functionality client side (a feature that's already also implemented on some browsers for password fields).

Anu Tig3r

unread,
Oct 13, 2017, 11:24:59 AM10/13/17
to Fat-Free Framework
@xfra35: actually i'm comparing the raw values, but `set_password` method replace the value of `password` with `Bcrypt::instance()->hash($pswd)`. So, I can;t compare the raw value.

I want to know that how can I validate client/user provided data through `beforesave` trigger, if, some parameters will replaced by the `set_` method of model?

For example: the code in this post is for `user registration`, where user `post` the form, containing `email, password, password_confirmation`. Than the `route controller` will execute `$model->copyFrom($data, array_keys($model->fields)); $model->save();`

Now, the model validation works like a charm if there is no `confirm` validator. Because before validating these parameters, the `set_` method replace the original value.

By the sorry for my bad english.

Thanks

Anu Tig3r

unread,
Oct 13, 2017, 11:28:31 AM10/13/17
to Fat-Free Framework
Hello @ved: its not only about the `password` parameter/validation. I'm trying to use a package AnandPilania/f3-validator in my project.
Reply all
Reply to author
Forward
0 new messages