如何编辑用户 CakePHP 3

How to Edit User CakePHP 3

所以我一直在尝试让编辑用户功能在我的应用程序中运行,但我对如何使用 CakePHP 3 执行此操作感到有点困惑。这就是我的应用程序在我的 UsersController.php:

中编辑操作
public function edit() {
    $this->layout = 'dashboard';

    $user = $this->Users->get($this->Auth->user('id'));
    if ($this->request->is(['post', 'put'])) {
      $this->Users->patchEntity($user, $this->request->data);
      if ($this->Users->save($user)) {
        $this->Flash->success(__('Your account has been edited'));
        return $this->redirect(['controller' => 'Users', 'action' => 'edit']);
      }
      $this->Flash->error(__('Your account could not be edited. Please fix errors below.'));
    }
    $this->set(compact('user'));
}

在我的 edit.ctp 文件中:

<?php
    $this->Form->templates($form_templates['defaultBootstrap']);
    echo $this->Form->create($user);
?>
<fieldset>
    <legend><?php echo __('Edit Profile'); ?></legend>
    <?php
      echo $this->Form->input('email', [
        'label' => __('Email'),
            'placeholder' => __('Email'),
            'autofocus'
        ]);
        echo $this->Form->input('currency', [
          'label' => __('Default Currency'),
          'options' => [
             'CAD' => 'CAD',
             'USD' => 'USD'
           ]
        ]);
        echo $this->Form->input('password', array(
          'label' => __('Password'),
          'placeholder' => __('Password'),
          'value' => ''
        ));
        echo $this->Form->input('confirm_password', array(
          'label' => __('Confirm Password'),
          'placeholder' => __('Confirm Password'),
          'type' => 'password'
        ));
    ?>
</fieldset>
<?php
    echo $this->Form->submit(__('Edit'));
    echo $this->Form->end();
?>

这个问题是附加到表单的密码被散列了,所以当我使用 patchEntity 时,它再次被散列,因为实体 User.php:

protected function _setPassword($password) {
  return (new DefaultPasswordHasher)->hash($password);
}

我也尝试过在我的控制器中设置 $user 时不获取密码。但是当我使用 patchEntity 时,它只是散列空白值。

也许我正在以完全错误的方式解决这个问题,我只是在寻找一些关于如何解决这个问题的方向,如果有人能帮忙的话。

如果您需要能够更改 edit 表单中的密码,那么您必须确保在编组之前删除它,以防未提供任何数据.

这可以通过 Users table class.

中的 Model.beforeMarshal 事件来实现

http://book.cakephp.org/3.0/en/orm/saving-data.html#before-marshal

public function beforeMarshal(Event $event, \ArrayObject $data, \ArrayObject $options)
{
    if(isset($data['password']) && empty($data['password'])) {
        unset($data['password']);
    }
}

这是一个非常基本的示例,您可能想要添加一些更严格的检查,也许在测试值是否为空之前删除空格等

您还可以将编辑配置文件数据和编辑凭据分开到不同的 actions/views/forms,然后使用 fieldList 选项来限制可以编组的字段。

http://book.cakephp.org/3.0/en/orm/saving-data.html#avoiding-property-mass-assignment-attacks

编辑个人资料:

$this->Users->patchEntity($user, $this->request->data, [
    'fieldList' => ['currency']
]);

编辑凭据:

$this->Users->patchEntity($user, $this->request->data, [
    'fieldList' => ['email', 'password']
]);