- 注册
//-会员注册
public function actionRegister(){
if (\Yii::$app->request->isPost){
$model= new Member();
$model->username=\Yii::$app->request->post('username');
$password=\Yii::$app->request->post('password_hash');
$model->password_hash=\Yii::$app->security->generatePasswordHash($password);
// \Yii::$app->security->generatePasswordHash($this->password);
$model->tel=\Yii::$app->request->post('tel');
$model->email=\Yii::$app->request->post('email');
if ($model->validate()){
$model->save();
//注册成功
$result = [
'errorCode'=>0,
'errorMsg'=>'注册成功',
'data'=>[
'id'=>$model->id,
'usernam'=>$model->username,
'tel'=>$model->tel,
'email'=>$model->email,
]
];
}else{
//验证不通过
$result = [
'errorCode'=>10,
'errorMsg'=>'注册失败,请检测错误信息',
'data'=>$model->getErrors()
];
}
}else{
$result = [
'errorCode'=>99,
'errorMsg'=>'请求方式错误,请使用POST提交数据',
'data'=>[]
];
}
return json_encode($result);
}
- 登录
public function actionLogin(){
$model=new LoginForm();
$request=new Request();
if ($request->isPost){
$model->load($request->post());
if ( $model->validate()){
//通过验证
$username=Member::findOne(['username'=>$model->username]);
// var_dump($username);exit;
if ($username){
// var_dump($username->password_hash,$model->password_hash);exit;
// \Yii::$app->security->validatePassword(明文,密文)
if (\Yii::$app->security->validatePassword($model->password_hash,$username->password_hash)){
$username->last_login_time=time();
$username->last_login_ip=\Yii::$app->request->userIP;
//保存登录信息;
\Yii::$app->user->login($username,$model->rememberMe?7*24*3600:0);
///由于有验证码,所以保存的时候要false
$username->save(false);
return $this->redirect(['member/index']);
}else{
$model->addError('password_hash','密码错误');
}
}else{
$model->addError('username','没有该帐号');
}
}
}
return $this->render('login',['model'=>$model]);
}
登录注意
模型登录必须实现接口(implements) IdentityInterface
public static function findIdentity($id)
{
return self::findOne($id);
// TODO: Implement findIdentity() method.
}
public function getId()
{
return $this->id;
// TODO: Implement getId() method.
}
public function getAuthKey()
{
return $this->auth_key;
// TODO: Implement getAuthKey() method.
}
public function validateAuthKey($authKey)
{
return $this->auth_key==$authKey;
// TODO: Implement validateAuthKey() method.
}
网友评论