I was working on user login in yii2, but instead of using active record there's another server handle the validation of user's username and password. So the following is what I did to work around:
in LoginForm.php
, I made some changes in validatePassword()
which apiRest()
is a method I used to send request to the remote server in charge of the validation.
if (!$this->hasErrors()) {
$json = '{
"username": "' . $this->username . '",
"password": "' . $this->password . '"
}';
$response = $this->apiRest("POST", "104.130.126.68:3000/api/users/login", $json);
$user = $this->getUser();
if(!$user || isset($response['error'])) {
$this->addError($attribute, $response['error']['message']);
}
if(isset($response['data'])) {
$user->id = $response['data']['userId'];
$user->username = $this->username;
$user->ttl = $response['data']['ttl'];
$user->created = $response['data']['created'];
$user->accessToken = $response['data']['id'];
}
}
And in the LoginForm.php/getUser()
, I also made some modification:
if ($this->_user === false) {
$this->_user = User::createNewUser();
}
return $this->_user;
where in User.php
I have:
public static function createNewUser()
{
$user = [
'id' => '',
'username' => '',
'ttl' => '',
'created' => '',
'accessToken' => '',
];
return new static($user);
}
Everything seems fine and I can also print out the user identity in SiteController.php/actionLogin()
:
if ($model->load(Yii::$app->request->post()) && $model->login()) {
print('<pre>');
print_r(Yii::$app->user->identity->username);
die();
return $this->redirect(['set/index']);
} else {
$this->layout = "plain";
return $this->render('login', [
'model' => $model,
]);
}
However, the problem is after the page redirection, the user identity is gone; there's nothing in Yii::$app->user->identity
. Did I miss anything? Please help me.