使用CakePHP更新用户电子邮件和密码

时间:2012-07-24 20:07:03

标签: php cakephp

我有一个用户注册的CakePHP应用程序。在用户页面上,我希望他们能够更新他们的电子邮件和密码。这是我的User模型:

<?php

class User extends AppModel {
    public $name = 'User';
    public $validate = array(
        'username' => array(
            'required' => array(
                'rule' => array('notEmpty'),
                'message' => 'A username is required'
            ),
            'range' => array(
                'rule' => array('between', 4, 20),
                'message' => 'Between 4 and 20 characters'
            ),
            'characters' => array(
                'rule' => array('alphaNumeric'),
                'message' => 'Alphanumeric characters only'
            ),
            'unique' => array(
                'rule' => array('isUnique'),
                'message' => 'This username is taken'
            )
        ),
        'email' => array(
            'required' => array(
                'rule' => array('notEmpty'),
                'message' => 'An email is required'
            ),
            'validEmail' => array(
                'rule' => array('email'),
                'message' => 'Please provide a valid email'
            ),
            'range' => array(
                'rule' => array('between', 5, 64),
                'message' => 'Between 5 and 64 characters'
            ),
            'unique' => array(
                'rule' => array('isUnique'),
                'message' => 'This email has already been used'
            )
        ),
        'password' => array(
            'required' => array(
                'rule' => array('notEmpty'),
                'message' => 'A password is required'
            ),
            'range' => array(
                'rule' => array('between', 5, 64),
                'message' => 'Between 5 and 64 characters'
            ),
        )
    );

    public function beforeSave() {
        if (isset($this->data[$this->alias]['password'])) {
            $this->data[$this->alias]['password'] = AuthComponent::password($this->data[$this->alias]['password']);
        }
        return true;
    }

}

我正在使用表单助手来创建表单:

<p>Modify your account settings</p>
<?php echo $this->Session->flash(); ?>
<?php
    echo $this->Form->create('User');
    echo $this->Form->input('currentPassword', array('type' => 'password'));
    echo $this->Form->input('username', array('disabled' => 'disabled', 'value' => $username));
    echo $this->Form->input('email');
    echo $this->Form->input('newPassword', array('type' => 'password'));
    echo $this->Form->end('Update');
?>

我如何检查当前密码是否有效,检查新电子邮件和密码是否通过验证规则,然后从我的控制器中更新用户表中的用户记录?

5 个答案:

答案 0 :(得分:1)

添加新用户 - UsersController.php:

public function add() {
        if ($this->request->is('post')) {
            $this->User->create();
                    if ($this->User->save($this->request->data)) {
                $this->Session->setFlash(__('Registration complete. :)'));
                $this->redirect(array('action' => 'index'));
            } else {
                $this->Session->setFlash(__('Error... Please try again.'));
            }
        }
    }

编辑用户 - UsersController.php:

public function edit($id = null) {
    $this->User->id = $id;
    if (!$this->User->exists()) {
        throw new NotFoundException(__('Invalid user'));
    }
    if ($this->request->is('post') || $this->request->is('put')) {
        if($this->Auth->user('password') == AuthComponent::password($this->request->data['User']['password']){
        if ($this->User->save($this->request->data)) {
            $this->Session->setFlash(__('The user has been saved'));
            $this->redirect(array('action' => 'index'));
        } else {
            $this->Session->setFlash(__('The user could not be saved. Please, try again.'));
        }
    }}else{
         $this->Session->setFlash(__('Incorrect password.'));
        }
         else {
        $this->request->data = $this->User->read(null, $id);
    }
}

注意{}。 :d

如果不起作用,请尝试

if($this->Auth->user('password') == $this->request->data['User']['password'])...

答案 1 :(得分:1)

对于那些在不更改模型且不显示散列密码的情况下需要某些内容的人:Updating user with or without password - CakePHP

TL; DR:

// add in your view `app/View/Users/edit.ctp`
// a 'fake' field you'll only use on the controller
echo $this->Form->input('new_password');
// add in your controller `app/Model/User.php`
// if we have a new password, create key `password` in data
if(!empty($new_password = $this->request->data['User']['new_password']))
  $this->request->data['User']['password'] = $new_password;
else // else, we remove the rules on password
  $this->User->validator()->remove('password');

答案 2 :(得分:0)

您还应该提供第二个密码字段以进行确认。这通常用于密码更新。 对于此以及如果要检查当前密码,请参阅此行为以了解如何完成此操作: http://www.dereuromark.de/2011/08/25/working-with-passwords-in-cakephp/

答案 3 :(得分:0)

答:

如何检查用户输入的密码是否与存储在数据库中的密码相同? - 詹姆斯道森

您可以在模型中添加以下功能。

function check_user($check) {
  if(!empty($check["EMail"]) && !empty( $_POST['data']['User']['password'])) 
    {
        $user = $this->find('first',array('conditions'=>array('User.EMail'=>$check["EMail"],'User.IsVerified'=>1)));
      if(empty($user)) {
        return FALSE;
       }
        $Encrypted = md5($_POST['data']['User']['password']);
        if($user['User']['password'] != ($Encrypted)) {
        return FALSE;
        }
    }
        return TRUE;
    }

并验证规则

'EMail' => array(
            'email' => array(
                'rule' => array('email'),
                'message' => 'Please enter valid email address..!',
                //'allowEmpty' => false,
                //'required' => false,
                //'last' => false, // Stop validation after this rule
                'on' => 'login', // Limit validation to 'create' or 'update' operations
            ),

            'check_user'=>array(
                'rule'=>'check_user',
                'message'=>'Either your Username or Password is invalid',
                'on' => 'login', // Limit validation to 'create' or 'update' operations
                'last'=>TRUE,

            ),

        ),

答案 4 :(得分:0)

protected function _update_password() {

        $password_error = false;

        /**
         * Handle post
         */
        if (($this->request->is('post') || $this->request->is('put')) && isset($this->request->data['User'])) {

            $old_pass_in_db = $this->User->read('password', $this->Session->read('Auth.User.id'));

            $old_pass_in_post = $this->Auth->password($this->request->data['User']['old_password']);

            //assign post data
            $this->User->set($this->request->data);


            //validate
            if (trim($old_pass_in_post) != trim($old_pass_in_db['User']['password'])) {
                $this->User->validationErrors['old_password'] = __("Old password do not match.");
            } else {
                unset($this->User->validationErrors['old_password']);
            }

            if ($this->User->validates(array('fieldList' => array('password', 'password_confirm'))) && ($old_pass_in_post == $old_pass_in_db['User']['password'])) {
                $this->User->id = $this->Session->read('Auth.User.id');
                if ($this->User->save(array('password', $this->Auth->password($this->request->data['User']['password'])), false)) {
                    $this->Session->setFlash(__('Password updated successfully.', true), 'default', array('class' => 'alert alert-success'));
                } //end save
            } else {
                $password_error = true;
            }
        }

        $this->set('password_error', $password_error);
    }