質問

I need help with applyFilter() for password. The filter works fine when I create a new record (i.e. save).

But how should I modify the filter to also encrypt password when I update password.

Here is my save filter.

Users::applyFilter('save', function($self, $params, $chain) {
    if ($params['data']) {
        $params['entity']->set($params['data']);
        $params['data'] = array();
    }
    if (!$params['entity']->exists()) {
        $params['entity']->password = Password::hash($params['entity']->password);
    }
    return $chain->next($self, $params, $chain);
});

Thanks

役に立ちましたか?

解決

You need to hash the password only when it's changed. In the entity object we can get at the original data for the entity and see if it has been updated. Likewise, we don't want to hash the password if the password field is empty.

Assuming you're doing something like this:

$user = Users::first($id);
if (!empty($this->request->data) && !empty($user)) {
    if ($user->save($this->request->data)) {
        // woohoo
    } else {
        // bummer
    }
}

Then the following code should work.

Users::applyFilter('save', function($self, $params, $chain) {
    if ($params['data']) {
        $params['entity']->set($params['data']);
        $params['data'] = array();
    }
    $entity = $params['entity'];
    if ($entity->password) {
        $export = $entity->export();
        if (empty($export['data']['password']) || $export['data']['password'] != $entity->password) {
            $entity->password = Password::hash($entity->password);
        }
    }
    return $chain->next($self, $params, $chain);
});
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top