如何在cakephp3.x中实现忘记密码



我试图在CakePHP 3.x中实现忘记密码的功能。我已经创建了一个接受用户电子邮件的表单:

<?= $this->Form->create()?>
<div class="form-group">
    <?= $this->Form->input('email', array('class' => 'form-group','autocomplete' => 'off' ,'required' => 'required'))?>
</div>
<div class="form-group">    
    <?= $this->Form->button('Reset Password', array('class' => 'form-group primary'))?>
</div>
<?= $this->Form->end()?>

在我的控制器中,我试图通过电子邮件找到用户,如果电子邮件存在,那么将生成一个随机密码,密码将更新为该电子邮件id:

use CakeORMTableRegistry;
use CakeAuthDefaultPasswordHasher;
    public function forgotPassword($email = null){
    if($this->request->is('post')) {
         $email = $this->request->data['email'];
         $emails = TableRegistry::get('Users'); 
         $user = $emails->find()->where(['email' => $email ])->first();
         if (!$user) {
             $this->Flash->error(__('No user with that email found.'));
             return $this->redirect(['controller' => 'Users','action' => 'forgotPassword']);
        }else{
                $random = 'a';
                $hasher = new DefaultPasswordHasher();
                $val = $hasher->hash($random);
                $data = $this->Users->password =  $val; 
                if ($this->Users->save($data)) {
                    $this->Flash->success(__('Password changed Succesfully.'));
                     return $this->redirect(['controller' => 'Users','action' => 'forgotPassword']);
                }

        }
    }
}

你还没有具体说明问题,但我想我可能知道怎么做能帮上忙。

整个DefaultPasswordHasher位应该在UsersEntity文件中,就像在教程:Blog教程

与哈希适当地放置在实体的例子,它将自动调用,只要你使用PatchEntity或NewEntity(我想,请确认?)。

其次,$this->[model]->save()函数作用于实体,而不仅仅是数据。所以你会找到用户的实体,修补实体,然后保存它:

...} else {
$newpass = 'randomstring';
$user = $this->Users->PatchEntity($user, ['password' => $newpass]);
if ($this->Users->save($user)) ...

最新更新