我正在爲登錄用戶構建一個表單來更改他們的帳戶設置(電子郵件和密碼)。要做到這一點,他們需要能夠確認他們當前的密碼。這就是我如何建立我的形式settings.ctp
:更改帳戶設置時檢查用戶當前的密碼
<div id="content-complex-image">
<div id="sidebar">
<ul>
<li><a href="/account/images">Your images</a></li>
<li><a href="/account/settings">Account settings</a></li>
</ul>
</div>
<div id="content-inner">
<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('password', array('type' => 'password'));
echo $this->Form->end('Update');
?>
</div>
<div class="clear"></div>
</div>
,這是我的控制器操作:
public function settings() {
$this->set('title_for_layout', 'Account Settings');
$this->User->id = $this->Auth->user('id');
if ($this->request->is('post')) {
if($this->Auth->user('password') == $this->request->data['User']['currentPassword']) {
if ($this->User->save($this->request->data)) {
$this->Session->setFlash('Your details have been saved');
$this->redirect(array('action' => 'settings'));
} else {
$this->Session->setFlash('Your details could not be updated. Try again.');
}
} else {
$this->Session->setFlash('Invalid password. Try again.');
}
}
}
然而,if()
密碼檢查結果始終爲假,總是顯示「無效密碼「消息。我猜測我沒有正確地檢查密碼,但我不知道這樣做的正確方法。
此外,我不希望用戶能夠更改他們的用戶名。我知道我已將表單字段設置爲禁用,但如果用戶向我的設置操作發送了發佈請求,他們可以更改其用戶名。如何阻止用戶名更新爲$this->User->save()
?
編輯:看起來像兩個問題,其中一個,我沒有在比較和兩個之前哈希密碼,$this->Auth->user('password')
實際上是NULL。這引發了另一個問題,我如何從數據庫中獲取用戶哈希密碼以便比較它?
密碼是否使用明文存儲在數據庫中?如果沒有,那會導致您的驗證檢查失敗。 – nick 2012-07-25 22:17:40
它使用Cake的默認哈希算法,我相信它是sha1? – 2012-07-25 22:25:12
您還需要對'currentPassword'進行散列,以便它匹配任何'Auth :: user('password')' – Ross 2012-07-25 22:25:59