YII2对密码加密生成的结果是不同的,即用相同的初始密码在不同时间得到的加密结果不同,所以我们不能用常用的方法去验证密码是否正确(将密码加密后与数据库中的密码相比较)。YII2有自己的加密以及密码验证流程。
加密 $hash = Yii::$app->getSecurity()->generatePasswordHash('123456']);
验证 Yii::$app->getSecurity()->validatePassword('123456', $hash),返回true或false
2、返回信息处理
Yii::$app->session->setFlash('contact','旧密码错误');//设置 flash
return $this->goBack(); //页面转跳
Yii::$app->session->getFlash('contact'); //获取 flash
public function actionPassword(){
$model=new PasswordForm;
$request = YII::$app->request;
if($request->isPost){
$p = $request->post('PasswordForm');
$id = YII::$app->user->id;
$admin= Admin::findIdentity($id);
$password = $admin->password;
if(Yii::$app->getSecurity()->validatePassword($p['password'], $password)){
if($p['pass1'] == $p['pass2']){
$newPass = Yii::$app->getSecurity()->generatePasswordHash($p['pass1']);
$connection = \Yii::$app->db;
$r = $connection->createCommand()->update('admin', ['password' => $newPass], 'id='.$id)->execute();
if($r){
Yii::$app->user->logout();
return $this->goHome();
}else{
return $this->goBack();
}
}
}else{
Yii::$app->session->setFlash('contact','旧密码错误');
return $this->redirect(array('site/password'));
}
}else{
return $this->render('password',['model'=>$model]);
}
}
代码优化:主要优化细节如下
1、将控制器中的主要逻辑代码移入模型中
2、优化数据库操作
控制器中:
public function actionPassword(){
$model=new PasswordForm;
$request = YII::$app->request;
if($request->isPost && $model->load(Yii::$app->request->post()) && $model->changePassword()){
Yii::$app->user->logout();
return $this->goHome();
}else{
return $this->render('password',['model'=>$model]);
}
}
模型中:
public function changePassword(){
$id = YII::$app->user->id;
$admin= Admin::findIdentity($id);
$password = $admin->password;
if(Yii::$app->getSecurity()->validatePassword($this->password, $password)){
if($this->pass1 == $this->pass2){
$newPass = Yii::$app->getSecurity()->generatePasswordHash($this->pass1);
$admin->password = $newPass;
if($admin->save()){
return true;
}else{
return false;
}
}else{
Yii::$app->session->setFlash('contact','两次新密码不相等');
return false;
}
}else{
Yii::$app->session->setFlash('contact','旧密码错误');
return false;
}
}