[英]Yii2 Auto login after registration
How can I achieve auto login after registration in yii2? 在yii2中注册后如何实现自动登录? In yii1, we achieved this through user Identity, but now I couldn't find it. 在yii1中,我们是通过用户身份实现的,但现在找不到了。
MY controller 我的控制器
public function actionCreate()
{
$model = new User();
if ($model->load(Yii::$app->request->post()) && $model->save()) {
Yii::$app->session->setFlash('success', 'Please Login with Email/Password!');
return $this->redirect('../site/login');
} else {
return $this->render('create', [
'model' => $model,
]);
}
}
If registration is successful, I want to auto login instead of going site login. 如果注册成功,我想自动登录而不是网站登录。
if ($model->load(Yii::$app->request->post()) && $model->save()) {
\Yii::$app->user->login($model);
return $this->redirect(['/site/index']);
}
You can accomplish that with switchIdentity() method. 您可以使用switchIdentity()方法完成此操作 。
Example: 例:
if ($userModel->load(Yii::$app->request->post()) && $userModel->save()) {
Yii::$app->user->switchIdentity($userModel); // log in
// do your stuff
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.