yii2系统自带的登录流程

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验证,注意,这步会把user这个类传入到web/user中,web/user会调用其已实现的接口,从而注册Yii::$app->user
            return Yii::$app->user->login($this->getUser(), $this->rememberMe ? 3600 * 24 * 30 : 0);
        } else {
            return false;
        }
    }

这时可以进入到yiiwebUser类中查看login动作, 通过一系列的验证,并且返回true表示登录成功

//注意第一个参数是要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/rickyctbu/p/12970201.html