Yii用户登录系统,带有密码哈希值 [英] Yii user login system with password rehashing
本文介绍了Yii用户登录系统,带有密码哈希值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用Yii框架,我想创建一个具有重新哈希密码的用户登录系统.因此,当用户登录时,系统会生成新的盐,并使用新的盐重新加密密码.我没有收到任何错误,但是当我检查密码和盐时,它们在数据库中没有更改.所以这是我现在所做的:
I am using Yii framework and I want to create a user login system with rehashing passwords. so when user loges in system geerates new salt and rehashes the password with new salt. I am getting no errors but when I am checking password and salt they don't change in database. so here is what I have done for now:
<?php
/**
* UserIdentity represents the data needed to identity a user.
* It contains the authentication method that checks if the provided
* data can identity the user.
*/
class UserIdentity extends CUserIdentity
{
private $_id;
public function authenticate()
{
$record=User::model()->findByAttributes(array('username'=>$this->username));
if($record===null)
$this->errorCode=self::ERROR_USERNAME_INVALID;
else if($record->password !== hash('sha512', $this->password.Security::Decrypt($record->salt)))
$this->errorCode=self::ERROR_PASSWORD_INVALID;
else
{
while ($record2 !== null){
$salt = Security::GenerateSalt(128);
if ($salt === null)
{
die('can\'t generate salt');
}
$record2 = User::model()->findByAttributes(array('salt'=>Security::Encrypt($salt)));
}
$record->salt = Security::Encrypt($salt);
$record->password = hash('sha512', $this->password.$salt);
$record->save();
$this->_id=$record->id;
$this->setState('user_id', $record->id);
$this->setState('user_username', $record->username);
$this->setState('user_privilages', $record->privilages);
$this->errorCode=self::ERROR_NONE;
}
return !$this->errorCode;
}
public function getId()
{
return $this->_id;
}
}
推荐答案
- 仅使用身份验证来进行身份验证并返回成功或失败状态
- 使用CWebUser类中的AfterLogin方法执行重新哈希处理,并确保仅在通过用户名/密码而不是从Cookie授权时才执行此操作.
您的webuser类如下所示:
Your webuser class would look like this:
protected $plain_password;
public function login( $identity, $duration = 0)
{
// ...
$this->id = $identity->id;
$this->plain_password = $identity->password;
return parent::login($identity, $duration);
}
protected function afterLogin($fromCookie)
{
$this->updateUserDataOnLoginSuccess($fromCookie);
return parent::afterLogin($fromCookie);
}
/**
* If the user logged in successfuly, we should update some data about him, like the last login time
* @param bool $fromCookie indicates whether the login takes place using cookie or login form
*/
private function updateUserDataOnLoginSuccess($fromCookie)
{
$attributes = array('last_login' => new CDbExpression('NOW()'));
if(!$fromCookie)
{
$atrributes['hash'] = new hash;
$attributes['password'] = new hashedpassword($this->plain_password, $atrributes['hash']);
}
User::model()->updateByPk($this->id, $attributes);
}
这篇关于Yii用户登录系统,带有密码哈希值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文