I've just learnt CakePHP and I want a user to input their old password when the edit their own information.
In my model User.php
'password_old' => array(
'match_old_password' => array(
'rule' => 'matchOldPassword',
'message' => 'Wrong password'
),
'minlength' => array(
'rule' => array('minLength', '8'),
'message' => 'Minimum 8 characters long'
)
)
I create a function matchOldPassword
public function matchOldPassword(){
if($this->data['User']['password_old']==$current_password){
return true;
}
return false;
}
My question is, how can I get value of current user's password in the Model? I use CakePHP 2.1.
You can perform database queries from a model just like you would in your controllers.
So in your User model you could call:
$this->find('first', array('conditions' => array('User.id' => $userId)));
or
$this->read(null, $userId);
Of course you'll have to pass the current user id from the controller to the model method.
If you're using the Auth component provided by Cake you can call $this->Auth->user('id')
to retrieve the id of the user that's currently logged in (if that's what you mean by "current user"). $this->Auth->user()
is a controller method so it can't be used in models. Your setup would look roughly like this:
UserModel method:
public function getCurrentUserPassword($userId) {
$password = '';
$this->recursive = -1;
$password = $this->read('password', $userId);
return $password;
}
UsersController call:
$userId = $this->Auth->user('id');
$this->User->getCurrentUserPassword($userId);