CakePHP在用户升级后自动更改密码

时间:2016-02-16 16:11:54

标签: php cakephp

我有以下星座:

Table `users`
Table `profiles`

profiles表格在User - 模型中与hasOne匹配,Profile - 模型与users匹配belongsTo。< / p>

注册,登录,一切正常。首次登录后,用户必须创建包含其他数据的profiles条目。还上传用户图像。图像路径存储在users表中。

ProfilesController.php

public function add() {
    $profile = $this->Profile->find('count', array('recusrive'=>-1, 'conditions'=>array('Profile.user_id'=>$this->Auth->user('id'))));
    if($profile > 0) {
        debug("error 1"); exit;
    }

    if ($this->request->is('post')) {

        // move tmp image to uploads folder
        // ... code with uploading image

        // create profile
        $this->Profile->create();

        // unset uploaded picture
        $profile_image = $this->request->data['User']['image']['name'];
        unset($this->request->data['User']);

        // prepare data to save
        $profileSafeData = array();
        $profileSafeData['Profile'] = $this->request->data['Profile'];

        if(!$this->Profile->save($profileSafeData)) {
            debug("error 2"); exit;
        }
        // works correctly, profile created.

        // save image to user
        $this->loadModel('User');
        $user = $this->User->find('first', array('conditions'=>array('User.id'=>$this->Auth->user('id')), 'recursive'=>-1));
        $user['User']['image'] = $profile_image;

        if($this->User->save($user)) { // *** here *** comes the problem. the users password changes after this save.
            $this->Session->setFlash(__('Congratulations! Your profile has been created.'), 'flash/success');

            // update new session data
            $this->Session->write('Auth', $this->User->read(null, $this->Auth->User('id')));

            $this->redirect(array('action' => 'view'));
        } else {
            return $this->Session->setFlash(__('Profile image could not be added to your user'), 'flash/error');
        }
    }

1 个答案:

答案 0 :(得分:1)

在最后一个用户查找(&#39;第一个&#39;)中,您将包含所有字段。

正在从数据库中读取密码,因此它将包含在save()中并再次加密。

解决方案:

只需在查找中添加字段选项(&#39;首先&#39;)或从 $ user 数组中取消设置密码索引。

$user = $this->User->find('first', array(
    'conditions'=>array('User.id'=>$this->Auth->user('id')), 
    'recursive'=>-1
    'fields' => array('id','image')
));