2015-01-02 24 views
0

我正在yii2中進行用戶登錄,但不是使用活動記錄,而是另一個服務器處理驗證用戶的用戶名和密碼。所以下面是我做過什麼來解決:Yii2頁面重定向後用戶身份丟失

LoginForm.php,我在validatePassword()其中apiRest()是我用來發送請求,負責驗證的遠程服務器的方法做了一些改動。

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

而在LoginForm.php/getUser(),我也做了一些修改:

if ($this->_user === false) { 
    $this->_user = User::createNewUser(); 
} 

return $this->_user; 

其中User.php我:

public static function createNewUser() 
{ 
    $user = [ 
     'id' => '', 
     'username' => '', 
     'ttl' => '', 
     'created' => '', 
     'accessToken' => '', 
    ]; 
    return new static($user); 
} 

似乎一切都很好,我也可以打印出用戶身份在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, 
    ]); 
} 

但是,問題出在頁面重定向後,用戶身份不見了; Yii::$app->user->identity中沒有任何內容。我錯過了什麼嗎?請幫幫我。

回答

0

檢查是否已在User.php

namespace app\models; 

use yii\web\IdentityInterface; 

class User implements IdentityInterface 
{ 

} 

實現yii\web\IdentityInterface如果是這樣的話,一定要檢查Yii::$app->user->enableSessionTRUE(這應該是by default)。

0

好,驗證看起來不錯,但你這樣做

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

但你永遠不設置用戶回模型。我相信你應該在最後一個

$this->_user = $user; 

您的登錄或許看起來像這樣

/** 
* 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將再次沒有返回(它會回報你創建空的用戶),因爲你從來沒有真正把它。

還什麼取消說我希望它不用說:)。