传递给yii \ web \ User :: login()的参数1必须实现接口yii \ web \ IdentityInterface

时间:2018-02-10 13:18:53

标签: yii2 identity

这些是我的文件:

config/web.php

'user' => [
            'identityClass' => '\app\models\User',
            'enableAutoLogin' => false,
        ],

SiteController.php

public function actionSignin()
{
    $model = new SigninForm();
    if(!Yii::$app->user->isGuest)
    {
        return $this->goHome();
    }
    if($model->load(Yii::$app->request->post()) and $model->validate())
    {
        $identity = User::findOne(['email' => $model->email])
        Yii::$app->user->login($identity);
    }
    return $this->render('signin',compact('model'));
}

User.php

namespace app\models;
use yii\db\ActiveRecord;
use yii\web\IdentityInterface;

class User extends ActiveRecord implements IdentityInterface
{
    /* and all methods Identityinterface is here!*/
}

我收到的错误是我在 User.php 模型中没有使用IdentityInterface。我的错误在哪里?

1 个答案:

答案 0 :(得分:0)

您需要定义实施IdentityInterface所需的所有方法 如给定here,登录方法将使用的另外两种方法首先将它们添加到您的类中。

class User extends ActiveRecord implements IdentityInterface
{
    public static function findIdentity($id)
    {
        return static::findOne($id);
    }

    public static function findIdentityByAccessToken($token, $type = null)
    {
        return static::findOne(['access_token' => $token]);
    }

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

    public function getAuthKey()
    {
        return $this->authKey;
    }

    public function validateAuthKey($authKey)
    {
        return $this->authKey === $authKey;
    }

    /**
    * Finds user by username
    *
    * @param string $username
    * @return static|null
    */
        public static function findByUsername($username)
        {
            foreach (self::$users as $user) {
                if (strcasecmp($user['username'], $username) === 0) {
                    return new static($user);
                }
            }

            return null;
        }

         /**
         * Validates password
         *
         * @param string $password password to validate
         * @return bool if password provided is valid for current user
         */

        public function validatePassword($password)
        {
            return $this->password === $password;
        }

}

然后你SigninForm应该如下所示

<?php

namespace app\models;

use Yii;
use yii\base\Model;

/**
 * SigninForm is the model behind the login form.
 *
 * @property User|null $user This property is read-only.
 *
 */
class SigninForm extends Model {

    public $username;
    public $password;
    public $rememberMe = true;
    private $_user = false;

    /**
     * @return array the validation rules.
     */
    public function rules() {
        return [
            // username and password are both required
            [['username', 'password'], 'required'],
            // rememberMe must be a boolean value
            ['rememberMe', 'boolean'],
            // password is validated by validatePassword()
            ['password', 'validatePassword'],
        ];
    }

    /**
     * Validates the password.
     * This method serves as the inline validation for password.
     *
     * @param string $attribute the attribute currently being validated
     * @param array $params the additional name-value pairs given in the rule
     */
    public function validatePassword($attribute, $params) {
        if (!$this->hasErrors()) {
            $user = $this->getUser();

            if (!$user || !$user->validatePassword($this->password)) {
                $this->addError($attribute, 'Incorrect username or password.');
            }
        }
    }

    /**
     * Logs in a user using the provided username and password.
     * @return bool whether the user is logged in successfully
     */
    public function login() {
        if ($this->validate()) {
            return Yii::$app->user->login($this->getUser(), $this->rememberMe ? 3600 * 24 * 30 : 0));
        }
        return false;
    }

    /**
     * Finds user by [[username]]
     *
     * @return User|null
     */
    public function getUser() {

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

        return $this->_user;
    }

}

将注册操作更新为以下

 public function actionSignin()
{
    $model = new SigninForm();
    if(!Yii::$app->user->isGuest)
    {
        return $this->goHome();
    }
    if($model->load(Yii::$app->request->post()) && $model->login())
    {
         return $this->goBack();
    }
    return $this->render('signin',compact('model'));
}

然后在config/web.php下的components内添加以下内容,如下例所示:

'components'=>[
      'user' => [
        'identityClass' => 'app\models\User', // User must implement the IdentityInterface
        'enableAutoLogin' => true,
        // 'loginUrl' => ['user/login'],
        // ...
    ]
]

您应该更全面地查看文档here是一个很好的视频教程,可以指导您逐步实现您的登录界面。

希望有所帮助