I bing with Yii2, some weeks ago.
After some troubles i make login work.
But after login my problem is tha identity set in login form is loose after redirect to index.
Here is my code
"FormLogin model Login "
public function login()
{
if($this->_identity===null)
{
$this->_identity=new User([ 'username' => $this->username, 'password' => $this->password ] );
$this->_identity->authenticate();
}
if($this->_identity->errorCode===User::ERROR_NONE)
{
$duration=$this->rememberMe ? 3600*24*30 : 0; // 30 days
return Yii::$app->user->login($this->_identity,$duration);
// exit( "|" . \Yii::$app->user->getId() . "| no app" ); this test if identey was added ( OK )
} else
return false;
}
Evrething is ok, y test with comment code if id of loged user is ok
After return i am in the actionLogin o site controller the code below :
"Site Controller Action Login "
public function actionLogin()
{
$this->layout = 'login'; // Layout especifico para o login
$request = Yii::$app->request;
$model = new LoginForm();
if( !is_null( $request->post('LoginForm') ) && $model->load($request->post(), 'LoginForm' ))
{
// validate user input and redirect to the previous page if valid
if( $model->validate($request->post('LoginForm')) && $model->login() )
{
return $this->redirect( ['site/index'] ); // here redirect back to index
} else {
$model->password = '';
$model->username = '';
}
}
echo $this->render('login',compact('model'));
}
When i cam to index from login, the identity is null and the action index go back to login again…
"Site Controller Action Index "
public function actionIndex()
{
// I try the both sentences
if( Yii::$app->user->getIsGuest() )
//if( \Yii::$app->user->getId() === null )
return $this->redirect(array('site/login'));
return $this->render('index');
}
Why i am loosing the identity in the redirect?
Can someone geave my some ligth ?
Thanks in advance