Yii2验证登录得User类

Yii2中的  Class yiiwebUser 是如果进行验证登录,如果我们使用User类验证登录会给我们减少很多麻烦。在此就拿Yii2中自带的登录功能进行说明。

配置。在应用配置文件components中添加user组件,默认是配置好了,不过可以自己配置的后台登录功能。

'user' => [
    'identityClass' => 'appmodelsUser', // User这个模型必须要实现identity接口
    'enableAutoLogin' => true,
    // 'loginUrl' => ['user/login'],
    // ...
]

在SiteController中可以查看登录动作,如果是过直接pass掉,如果不是过客,再进行下一步,就new一个LoginForm对象

public function actionLogin()
    {
        if (!Yii::$app->user->isGuest) {
            return $this->goHome();
        }

        $model = new LoginForm();
//数据的导入, 调用模型登录功能
        if ($model->load(Yii::$app->request->post()) && $model->login()) {
            return $this->goBack();
        } else {
            return $this->render('login', [
                'model' => $model,
            ]);
        }
    }

在公共模型文件中找到LoginForm模型

public function login()
    {
        //验证规则  rules
        if ($this->validate()) {
        // 传入第一User信息参数验证登录 这时配置文件User组件起作用了  通过yiiwebUser验证
            return Yii::$app->user->login($this->getUser(), $this->rememberMe ? 3600 * 24 * 30 : 0);
        } else {
            return false;
        }
    }

这时可以进入到yiiwebUser类中查看login动作是如何处理,不管如何处理,反正做了乱七八糟的一些事,最后返回一个布尔值。通过触发事件来设置登录信息。

//注意第一个参数是要IdentityInterface 得实例
public function login(IdentityInterface $identity, $duration = 0)
    {
        if ($this->beforeLogin($identity, false, $duration)) {
            $this->switchIdentity($identity, $duration);
            $id = $identity->getId();
            $ip = Yii::$app->getRequest()->getUserIP();
            if ($this->enableSession) {
                $log = "User '$id' logged in from $ip with duration $duration.";
            } else {
                $log = "User '$id' logged in from $ip. Session not enabled.";
            }
           //写入日志
            Yii::info($log, __METHOD__);
            $this->afterLogin($identity, false, $duration);
        }

        return !$this->getIsGuest();
    }
原文地址:https://www.cnblogs.com/webph/p/6591081.html