2016-07-26 103 views
0

有一種方法(在models/User.php中)用我的自定義表的用戶名和密碼替換默認的Yii用戶(例如admin,demo等)。Yii2動態默認用戶

private static $users = [ 
     '100' => [ 
     'id' => '100', 
     'username' => 'admin', 
     'password' => 'admin', 
     'authKey' => 'test100key', 
     'accessToken' => '100-token', 
     ], 
     '101' => [ 
     'id' => '101', 
     'username' => 'demo', 
     'password' => 'demo', 
     'authKey' => 'test101key', 
     'accessToken' => '101-token', 
     ], 
    ]; 
+1

你的意思是讓用戶?你可以隨意更改這張表,只要你想要... – Bizley

+0

in findByUsername函數我用這個覆蓋默認代碼:$ user = Utente :: find() - > where(['username'=> $ username]) - >酮();但是當我嘗試登錄時,出現此錯誤:調用未知方法:app \ models \ Utente :: validatePassword() – mariobros

+1

如果您正在查找DB用戶實現,則可以從高級模板複製和修改用戶模型。 – Bizley

回答

0

你應該從\yii\web\IdentityInterface實現你的用戶類,並實現這些功能

public static function findIdentity($id) { 

     $model = self::findOne(['users_id' => $id]); 

     return ($model ? new static($model) : NULL); 
    } 

    public static function findIdentityByAccessToken($token, $type = null) { 
     return null; 
    } 

    public function getId() { 
     return $this->users_id; 
    } 

    public function getAuthKey() { 
     return FALSE; 
    } 

    public function validateAuthKey($authKey) { 

    } 
public static function findByid($id) { 

    return self::findOne(['users_id' => $id]); 
} 

public function validatePassword($password) { 
    return Yii::$app->security->validatePassword($password, $this->uusers_password); 
} 

public function setPassword($password) { 
    $this->password_hash = Yii::$app->security->generatePasswordHash($password); 
} 

和更改登錄表單如從數據庫

public function login() 
    { 
     if ($this->validate()) { 
      return Yii::$app->user->login($this->getUser(), $this->rememberMe ? 3600 * 24 * 30 : 0); 
     } else { 
      return false; 
     } 
    } 

    /** 
    * Finds user by [[username]] 
    * 
    * @return User|null 
    */ 
    protected function getUser() 
    { 
     if ($this->_user === null) { 
      $this->_user = Users::findByid($this->username); 
     } 

     return $this->_user; 
    } 
+0

感謝您的建議,似乎工作的部分原因是因爲登錄後我收到此錯誤: 參數1傳遞給yii \ web \ User :: login()必須實現接口yii \ web \ IdentityInterface,應用程序實例\ models \ Utente給出,在第73行調用C:\ Program Files(x86)\ myproject \ models \ LoginForm.php並定義爲 問題似乎在裏面:return Yii :: $ app-> user-> login($ this- > getUser(),$ this-> rememberMe?3600 * 24 * 30:0); – mariobros

+0

你是否以這種方式實現你的類:'class User extends \ yii \ db \ ActiveRecord implements \ yii \ web \ IdentityInterface { ... } '??? – yafater

+0

是的,我已經編輯模型/ User.php並以您建議的方式實現Class。 – mariobros