yii2框架中自帶了一個登錄的功能,下面介紹一下這個登錄的運行流程
配置。在應用配置文件components中添加user組件,默認是配置好了,不過可以自己配置的后台登錄功能。
'user' => [ 'identityClass' => 'app\models\User', // 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組件起作用了 通過yii\web\User驗證,注意,這步會把user這個類傳入到web/user中,web/user會調用其已實現的接口,從而注冊Yii::$app->user return Yii::$app->user->login($this->getUser(), $this->rememberMe ? 3600 * 24 * 30 : 0); } else { return false; } }
這時可以進入到yii\web\User類中查看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(); }