歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Yii 用戶登陸機制

Yii 用戶登陸機制

日期:2017/3/1 9:35:00   编辑:Linux編程

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 ,為表單模型的派生類,封裝了關於登陸的數據及業務邏輯。比較核心的函數如下:

/**
* Authenticates the password.
* This is the 'authenticate' validator as declared in rules().
*/
public function authenticate($attribute,$params)
{
$this->_identity=new UserIdentity($this->username,$this->password);
if(!$this->_identity->authenticate())
$this->addError('password','用戶名或密碼錯誤');
}

/**
* Logs in the user using the given username and password in the model.
* @return boolean whether login is successful
*/
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, 函數如下:

/**
* Displays the login page
*/
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 是不是方便極了~

Yii 的詳細介紹:請點這裡
Yii 的下載地址:請點這裡

Copyright © Linux教程網 All Rights Reserved