Yii的登陸機制
Yii 生成應用時已經提供了最基礎的使用者登陸機制。我們用 Yii 生成一個新的應用,進入 protected/components 目錄,我們可以看到 UserIdentity.php 檔案,裡面的 UserIdentity 類裡面隻有一個 public 函數如下:
public function authenticate()
{
$users=array(
// username => password
'demo'=>'demo',
'admin'=>'admin',
);
if(!isset($users[$this->username]))
$this->errorCode=self::ERROR_USERNAME_INVALID;
elseif($users[$this->username]!==$this->password)
$this->errorCode=self::ERROR_PASSWORD_INVALID;
else
$this->errorCode=self::ERROR_NONE;
return !$this->errorCode;
}
這個類在 components 裡面,會在應用一開始的時候就加載,用于最基礎的使用者驗證,可以看到,該函數一開始隻是簡單地定義了兩個使用者 demo 和 admin,而密碼也隻是 demo 和 admin,如果是以如果你的使用者很有限的話,可以直接在這裡面修改添加使用者就行,多的話我們後面再說。函數下面的 if else 分别是用于檢查使用者名和密碼是否有效,出錯的時候生成 ERROR_USERNAME_INVALID,ERROR_PASSWORD_INVALID 這些錯誤。總的來說,這裡進行了真正的使用者名密碼驗證,并進行登陸後的基本邏輯處理。
單看這個類還是看不出登陸控制流程的。遵循 Model/ Control/ View 的原則,我們可以看到登陸流程在這三方面的展現。首先進入 Models 檔案夾,你可以看到一個 LoginForm 的類檔案,這個類繼承了 CFormModel ,為表單模型的派生類,封裝了關于登陸的資料及業務邏輯。比較核心的函數如下:
public function authenticate($attribute,$params)
{
$this->_identity=new UserIdentity($this->username,$this->password);
if(!$this->_identity->authenticate())
$this->addError('password','使用者名或密碼錯誤');
}
public function login()
{
if($this->_identity===null)
{
$this->_identity=new UserIdentity($this->username,$this->password);
$this->_identity->authenticate();
}
if($this->_identity->errorCode===UserIdentity::ERROR_NONE)
{
$duration=$this->rememberMe ? 3600*24*30 : 0; // 30 days
Yii::app()->user->login($this->_identity,$duration);
return true;
}
else
return false;
}
這裡的 authenticate 利用 UserIdentity 類對使用者名密碼進行驗證,而 login 函數通過檢測使用者身份是否已經設定及錯誤碼是否為空,最後進行 Yii 提供的 login 函數進行登陸。$duration 可以設定身份的有效期。
再看 Control,在 siteControler 裡面有一個 action 是關于登入的,就是 actionLogin, 函數如下:
public function actionLogin()
{
if (!defined('CRYPT_BLOWFISH')||!CRYPT_BLOWFISH)
throw new CHttpException(500,"This application requires that PHP was compiled with Blowfish support for crypt().");
$model=new LoginForm;
// if it is ajax validation request
if(isset($_POST['ajax']) && $_POST['ajax']==='login-form')
{
echo CActiveForm::validate($model);
Yii::app()->end();
}
// collect user input data
if(isset($_POST['LoginForm']))
{
$model->attributes=$_POST['LoginForm'];
// validate user input and redirect to the previous page if valid
if($model->validate() && $model->login())
$this->redirect(Yii::app()->user->returnUrl);
}
// display the login form
$this->render('login',array('model'=>$model));
}
該 login 的 action 是基于 LoginForm 将 POST 的表單進行驗證登陸或者渲染一個新的登入頁面。
最後, view 的檔案是 site 檔案夾的 login.php ,這就是你所看到的登陸界面了。
梳理一下,我們可以清楚地看到 Yii 的使用者登陸邏輯處理,當你在 login 界面輸入使用者名密碼之後,表單将資料 POST 到 site/login 的動作,loign 執行個體化了一個 LoginForm 表單模型,并根據 model 裡面的 validate 函數 和 login 函數 進行登陸檢測,validate 會根據 rule 的規則驗證表單資料,其中 password 的驗證需要 authenticate 函數,而 authenticate 和 login 函數的驗證都是基于 UserIdentity 的 authenticate 函數。是以,如果我們更改登入的邏輯,LgoinForm 和 loginaction 都可以不用修改,直接改 UserIdentity 的 authenticate 函數就基本可以了。
以上的分析是 Yii 自動生成的關于使用者登陸的邏輯處理代碼,看起來已經很像樣了不是嗎?但我們的系統一般要支援很多使用者通路,在代碼裡簡單地羅列使用者名和密碼明顯是不理智的,更為成熟的當然是請資料庫來幫我們管理。假設我們在自己的資料庫裡面按下面的 Mysql 語句建立一個 admin 的表:
drop table if exists `admin`;
create table `admin` (
`admin_id` int unsigned not null auto_increment comment '主鍵',
`username` varchar(32) not null comment '登入名',
`psw` char(40) not null comment '登入密碼(兩次sha1)',
`nick` varchar(64) not null comment '昵稱',
`add_time` datetime not null comment '建立時間',
`login_time` datetime null comment '最近登入時間',
unique key(`username`),
primary key (`admin_id`)
) engine=innodb default charset=utf8 comment='管理者表';
Mysql 建表完成後我們就用 gii 生成 admin 的 Model,然後我們可以回到我們最初 Component 裡面的 UserIdentity.php 重寫 authenticate 函數來實作我們自己的使用者名密碼驗證。為了安全起見,密碼采用兩次 sha1 加密,是以将采集到的密碼兩次 sha1 加密,然後在我們建立的 Admin 裡面查找是否存在與表單輸入的 username 對應的使用者,然後比對加密過的密碼,如果都通過後就可以把這個使用者的常用資訊由 setState 函數設定為 Yii 的 user 的使用者字段,比如 $this->setState('nick', $user->nick); 這一句之後,以後可以直接通過 Yii:app()->user->nick 來通路目前登陸使用者的昵稱,而不用去查詢資料庫。而 $user->login_time = date('Y-m-d H:i:s'); 是進行更新使用者登陸時間,并通過下一句的 save 儲存到資料庫中。
public function authenticate()
{
if(strlen($this->password) > 0)
$this->password = sha1(sha1($this->password));
$user = Admin::model()->findByAttributes(array('username' => $this->username));
if($user == null)
$this->errorCode=self::ERROR_USERNAME_INVALID;
elseif( !($user instanceof Admin) || ($user->psw != $this->password) )
$this->errorCode=self::ERROR_PASSWORD_INVALID;
else
{
$this->setState('admin_id', $user->admin_id);
$this->setState('nick', $user->nick);
$this->setState('username', $user->username);
$user->login_time = date('Y-m-d H:i:s');
$user->save();
$this->errorCode=self::ERROR_NONE;
}
return !$this->errorCode;
}
而如果你想要修改登陸的界面,那就進入 view 裡面 site 檔案夾中的 login.php ,盡情地折騰讓它變成你想要的樣子,這樣我們自己的登陸流程也完成了。有了 Yii 是不是友善極了~
設定自動登陸自動登入的原理很簡單。主要就是利用cookie來實作的
在第一次登入的時候,如果登入成功并且選中了下次自動登入,那麼就會把使用者的認證資訊儲存到cookie中,cookie的有效期為1年或者幾個月。
在下次登入的時候先判斷cookie中是否存儲了使用者的資訊,如果有則用cookie中存儲的使用者資訊來登入,
配置User元件
首先在配置檔案的components中設定user元件
'user' => [
'identityClass' => 'app\models\User',
'enableAutoLogin' => true,
],
我們看到enableAutoLogin就是用來判斷是否要啟用自動登入功能,這個和界面上的下次自動登入無關。
隻有在enableAutoLogin為true的情況下,如果選擇了下次自動登入,那麼就會把使用者資訊存儲起來放到cookie中并設定cookie的有效期為3600*24*30秒,以用于下次登入
現在我們來看看Yii中是怎樣實作的。
一、第一次登入存cookie
1、login 登入功能
public function login($identity, $duration = 0)
{
if ($this->beforeLogin($identity, false, $duration)) {
$this->switchIdentity($identity, $duration);
$id = $identity->getId();
$ip = Yii::$app->getRequest()->getUserIP();
Yii::info("User '$id' logged in from $ip with duration $duration.", __METHOD__);
$this->afterLogin($identity, false, $duration);
}
return !$this->getIsGuest();
}
在這裡,就是簡單的登入,然後執行switchIdentity方法,設定認證資訊。
2、switchIdentity設定認證資訊
public function switchIdentity($identity, $duration = 0)
{
$session = Yii::$app->getSession();
if (!YII_ENV_TEST) {
$session->regenerateID(true);
}
$this->setIdentity($identity);
$session->remove($this->idParam);
$session->remove($this->authTimeoutParam);
if ($identity instanceof IdentityInterface) {
$session->set($this->idParam, $identity->getId());
if ($this->authTimeout !== null) {
$session->set($this->authTimeoutParam, time() + $this->authTimeout);
}
if ($duration > 0 && $this->enableAutoLogin) {
$this->sendIdentityCookie($identity, $duration);
}
} elseif ($this->enableAutoLogin) {
Yii::$app->getResponse()->getCookies()->remove(new Cookie($this->identityCookie));
}
}
這個方法比較重要,在退出的時候也需要調用這個方法。
這個方法主要有三個功能
設定session的有效期
如果cookie的有效期大于0并且允許自動登入,那麼就把使用者的認證資訊儲存到cookie中
如果允許自動登入,删除cookie資訊。這個是用于退出的時候調用的。退出的時候傳遞進來的$identity為null
protected function sendIdentityCookie($identity, $duration)
{
$cookie = new Cookie($this->identityCookie);
$cookie->value = json_encode([
$identity->getId(),
$identity->getAuthKey(),
$duration,
]);
$cookie->expire = time() + $duration;
Yii::$app->getResponse()->getCookies()->add($cookie);
}
存儲在cookie中的使用者資訊包含有三個值:
$identity->getId()
$identity->getAuthKey()
$duration
getId()和getAuthKey()是在IdentityInterface接口中的。我們也知道在設定User元件的時候,這個User Model是必須要實作IdentityInterface接口的。是以,可以在User Model中得到前兩個值,第三值就是cookie的有效期。
二、自動從cookie登入
從上面我們知道使用者的認證資訊已經存儲到cookie中了,那麼下次的時候直接從cookie裡面取資訊然後設定就可以了。
1、AccessControl使用者通路控制
Yii提供了AccessControl來判斷使用者是否登入,有了這個就不需要在每一個action裡面再判斷了
public function behaviors()
{
return [
'access' => [
'class' => AccessControl::className(),
'only' => ['logout'],
'rules' => [
[
'actions' => ['logout'],
'allow' => true,
'roles' => ['@'],
],
],
],
];
}
2、getIsGuest、getIdentity判斷是否認證使用者
isGuest是自動登入過程中最重要的屬性。
在上面的AccessControl通路控制裡面通過IsGuest屬性來判斷是否是認證使用者,然後在getIsGuest方法裡面是調用getIdentity來擷取使用者資訊,如果不為空就說明是認證使用者,否則就是遊客(未登入)。
public function getIsGuest($checkSession = true)
{
return $this->getIdentity($checkSession) === null;
}
public function getIdentity($checkSession = true)
{
if ($this->_identity === false) {
if ($checkSession) {
$this->renewAuthStatus();
} else {
return null;
}
}
return $this->_identity;
}
3、renewAuthStatus 重新生成使用者認證資訊
protected function renewAuthStatus()
{
$session = Yii::$app->getSession();
$id = $session->getHasSessionId() || $session->getIsActive() ? $session->get($this->idParam) : null;
if ($id === null) {
$identity = null;
} else {
$class = $this->identityClass;
$identity = $class::findIdentity($id);
}
$this->setIdentity($identity);
if ($this->authTimeout !== null && $identity !== null) {
$expire = $session->get($this->authTimeoutParam);
if ($expire !== null && $expire < time()) {
$this->logout(false);
} else {
$session->set($this->authTimeoutParam, time() + $this->authTimeout);
}
}
if ($this->enableAutoLogin) {
if ($this->getIsGuest()) {
$this->loginByCookie();
} elseif ($this->autoRenewCookie) {
$this->renewIdentityCookie();
}
}
}
這一部分先通過session來判斷使用者,因為使用者登入後就已經存在于session中了。然後再判斷如果是自動登入,那麼就通過cookie資訊來登入。
4、通過儲存的Cookie資訊來登入 loginByCookie
protected function loginByCookie()
{
$name = $this->identityCookie['name'];
$value = Yii::$app->getRequest()->getCookies()->getValue($name);
if ($value !== null) {
$data = json_decode($value, true);
if (count($data) === 3 && isset($data[0], $data[1], $data[2])) {
list ($id, $authKey, $duration) = $data;
$class = $this->identityClass;
$identity = $class::findIdentity($id);
if ($identity !== null && $identity->validateAuthKey($authKey)) {
if ($this->beforeLogin($identity, true, $duration)) {
$this->switchIdentity($identity, $this->autoRenewCookie ? $duration : 0);
$ip = Yii::$app->getRequest()->getUserIP();
Yii::info("User '$id' logged in from $ip via cookie.", __METHOD__);
$this->afterLogin($identity, true, $duration);
}
} elseif ($identity !== null) {
Yii::warning("Invalid auth key attempted for user '$id': $authKey", __METHOD__);
}
}
}
}
先讀取cookie值,然後$data = json_decode($value, true);反序列化為數組。
這個從上面的代碼可以知道要想實作自動登入,這三個值都必須有值。另外,在User Model中還必須要實作findIdentity、validateAuthKey這兩個方法。
登入完成後,還可以再重新設定cookie的有效期,這樣便能一起有效下去了。
$this->switchIdentity($identity, $this->autoRenewCookie ? $duration : 0);
三、退出 logout
public function logout($destroySession = true)
{
$identity = $this->getIdentity();
if ($identity !== null && $this->beforeLogout($identity)) {
$this->switchIdentity(null);
$id = $identity->getId();
$ip = Yii::$app->getRequest()->getUserIP();
Yii::info("User '$id' logged out from $ip.", __METHOD__);
if ($destroySession) {
Yii::$app->getSession()->destroy();
}
$this->afterLogout($identity);
}
return $this->getIsGuest();
}
public function switchIdentity($identity, $duration = 0)
{
$session = Yii::$app->getSession();
if (!YII_ENV_TEST) {
$session->regenerateID(true);
}
$this->setIdentity($identity);
$session->remove($this->idParam);
$session->remove($this->authTimeoutParam);
if ($identity instanceof IdentityInterface) {
$session->set($this->idParam, $identity->getId());
if ($this->authTimeout !== null) {
$session->set($this->authTimeoutParam, time() + $this->authTimeout);
}
if ($duration > 0 && $this->enableAutoLogin) {
$this->sendIdentityCookie($identity, $duration);
}
} elseif ($this->enableAutoLogin) {
Yii::$app->getResponse()->getCookies()->remove(new Cookie($this->identityCookie));
}
}
退出的時候先把目前的認證設定為null,然後再判斷如果是自動登入功能則再删除相關的cookie資訊。