Yii2 user identity loss after page redirection

2019-08-19 03:09发布

问题:

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.

回答1:

Well, the validation looks fine, however you do this

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'];
    }

but you never set the user back to the model. I believe you should have at the end a

$this->_user = $user;

Your login probably looks like this

/**
 * Logs in a user using the provided username and password.
 *
 * @return boolean whether the user is logged in successfully
 */
public function login()
{
    if ($this->validate()) {
        return $this->getUser()->login($this->rememberMe ? 2592000 : 0);
    } else {
        return false;
    }
}

getUser will again return nothing (it will return the empty user you create) as you never actually set it.

Also what deacs says I hope it goes without saying :).



回答2:

Check that you have implemented yii\web\IdentityInterface in User.php

namespace app\models;

use yii\web\IdentityInterface;

class User implements IdentityInterface
{

}

If that's the case, be sure to check that Yii::$app->user->enableSession is TRUE (which it should be by default).