《PHP教程:詳細(xì)解讀PHP的Yii框架中登陸功能的實(shí)現(xiàn)》要點(diǎn):
本文介紹了PHP教程:詳細(xì)解讀PHP的Yii框架中登陸功能的實(shí)現(xiàn),希望對(duì)您有用。如果有疑問(wèn),可以聯(lián)系我們。
相關(guān)主題:YII框架
PHP學(xué)習(xí)Yii的登岸機(jī)制
PHP學(xué)習(xí)Yii 生成應(yīng)用時(shí)已經(jīng)提供了最基礎(chǔ)的用戶(hù)登岸機(jī)制.我們用 Yii 生成一個(gè)新的應(yīng)用,進(jìn)入 protected/components 目錄,我們可以看到 UserIdentity.php 文件,里面的 UserIdentity 類(lèi)里面只有一個(gè) public 函數(shù)如下:
PHP學(xué)習(xí)
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;
}
PHP學(xué)習(xí)???? 這個(gè)類(lèi)在 components 里面,會(huì)在應(yīng)用一開(kāi)始的時(shí)候就加載,用于最基礎(chǔ)的用戶(hù)驗(yàn)證,可以看到,該函數(shù)一開(kāi)始只是簡(jiǎn)單地定義了兩個(gè)用戶(hù) demo 和 admin,而暗碼也只是 demo 和 admin,如果所以如果你的用戶(hù)很有限的話(huà),可以直接在這里面修改添加用戶(hù)就行,多的話(huà)我們后面再說(shuō).函數(shù)下面的 if else 分別是用于檢查用戶(hù)名和暗碼是否有效,出錯(cuò)的時(shí)候生成 ERROR_USERNAME_INVALID,ERROR_PASSWORD_INVALID 這些錯(cuò)誤.總的來(lái)說(shuō),這里進(jìn)行了真正的用戶(hù)名暗碼驗(yàn)證,并進(jìn)行登陸后的基本邏輯處理.
???? 單看這個(gè)類(lèi)還是看不出登陸控制流程的.遵循 Model/ Control/ View 的原則,我們可以看到登陸流程在這三方面的體現(xiàn).首先進(jìn)入 Models 文件夾,你可以看到一個(gè) LoginForm 的類(lèi)文件,這個(gè)類(lèi)繼承了 CFormModel ,為表單模型的派生類(lèi),封裝了關(guān)于登陸的數(shù)據(jù)及業(yè)務(wù)邏輯.比較核心的函數(shù)如下:
PHP學(xué)習(xí)
/**
* 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','用戶(hù)名或暗碼錯(cuò)誤');
}
/**
* 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;
}
PHP學(xué)習(xí)??? 這里的 authenticate 利用 UserIdentity 類(lèi)對(duì)用戶(hù)名暗碼進(jìn)行驗(yàn)證,而 login 函數(shù)通過(guò)檢測(cè)用戶(hù)身份是否已經(jīng)設(shè)置及錯(cuò)誤碼是否為空,最后進(jìn)行 Yii 提供的 login 函數(shù)進(jìn)行登陸.$duration 可以設(shè)置身份的有效期.
??? 再看 Control,在 siteControler 里面有一個(gè) action 是關(guān)于登錄的,就是 actionLogin, 函數(shù)如下:
PHP學(xué)習(xí)
/**
* 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));
}
PHP學(xué)習(xí)??? 該 login 的 action 是基于 LoginForm 將 POST 的表單進(jìn)行驗(yàn)證登岸或者渲染一個(gè)新的登錄頁(yè)面.
PHP學(xué)習(xí)???? 最后, view 的文件是 site 文件夾的 login.php ,這便是你所看到的登陸界面了.
PHP學(xué)習(xí)??? 梳理一下,我們可以清楚地看到 Yii 的用戶(hù)登陸邏輯處理,當(dāng)你在 login 界面輸入用戶(hù)名暗碼之后,表單將數(shù)據(jù) POST 到 site/login 的動(dòng)作,loign 實(shí)例化了一個(gè) LoginForm 表單模型,并根據(jù) model 里面的 validate 函數(shù) 和 login 函數(shù) 進(jìn)行登陸檢測(cè),validate 會(huì)根據(jù) rule 的規(guī)則驗(yàn)證表單數(shù)據(jù),其中 password 的驗(yàn)證需要 authenticate 函數(shù),而 authenticate 和 login 函數(shù)的驗(yàn)證都是基于 UserIdentity 的 authenticate 函數(shù).所以,如果我們更改登錄的邏輯,LgoinForm 和 loginaction 都可以不用修改,直接改 UserIdentity 的 authenticate 函數(shù)就基本可以了.
PHP學(xué)習(xí)???? 以上的分析是 Yii 自動(dòng)生成的關(guān)于用戶(hù)登陸的邏輯處理代碼,看起來(lái)已經(jīng)很像樣了不是嗎?但我們的系統(tǒng)一般要支持很多用戶(hù)訪(fǎng)問(wèn),在代碼里簡(jiǎn)單地羅列用戶(hù)名和暗碼明顯是不理智的,更為成熟的當(dāng)然是請(qǐng)數(shù)據(jù)庫(kù)來(lái)幫我們管理.假設(shè)我們?cè)谧约旱臄?shù)據(jù)庫(kù)里面按下面的 Mysql 語(yǔ)句創(chuàng)建一個(gè) admin 的表:
PHP學(xué)習(xí)
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 '昵稱(chēng)',
`add_time` datetime not null comment '創(chuàng)建時(shí)間',
`login_time` datetime null comment '最近登錄時(shí)間',
unique key(`username`),
primary key (`admin_id`)
) engine=innodb default charset=utf8 comment='管理員表';
PHP學(xué)習(xí)??? Mysql 建表完成后我們就用 gii 生成 admin 的 Model,然后我們可以回到我們最初 Component 里面的 UserIdentity.php 重寫(xiě) authenticate 函數(shù)來(lái)實(shí)現(xiàn)我們自己的用戶(hù)名密碼驗(yàn)證.為了平安起見(jiàn),密碼采用兩次 sha1 加密,所以將采集到的密碼兩次 sha1 加密,然后在我們創(chuàng)建的 Admin 里面查找是否存在與表單輸入的 username 對(duì)應(yīng)的用戶(hù),然后比對(duì)加密過(guò)的密碼,如果都通過(guò)后就可以把這個(gè)用戶(hù)的常用信息由 setState 函數(shù)設(shè)置為 Yii 的 user 的用戶(hù)字段,比如 $this->setState('nick', $user->nick); 這一句之后,以后可以直接通過(guò) Yii:app()->user->nick 來(lái)訪(fǎng)問(wèn)當(dāng)前登陸用戶(hù)的昵稱(chēng),而不用去查詢(xún)數(shù)據(jù)庫(kù).而 $user->login_time = date('Y-m-d H:i:s'); 是進(jìn)行更新用戶(hù)登陸時(shí)間,并通過(guò)下一句的 save 保存到數(shù)據(jù)庫(kù)中.
PHP學(xué)習(xí)
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;
}
PHP學(xué)習(xí)??? 而如果你想要修改登陸的界面,那就進(jìn)入 view 里面 site 文件夾中的 login.php ,盡情地折騰讓它變成你想要的樣子,這樣我們本身的登陸流程也完成了.有了 Yii 是不是方便極了~
PHP學(xué)習(xí)
設(shè)置自動(dòng)登陸
自動(dòng)登錄的原理很簡(jiǎn)單.主要就是利用cookie來(lái)實(shí)現(xiàn)的
在第一次登錄的時(shí)候,如果登錄成功并且選中了下次自動(dòng)登錄,那么就會(huì)把用戶(hù)的認(rèn)證信息保留到cookie中,cookie的有效期為1年或者幾個(gè)月.
PHP學(xué)習(xí)在下次登錄的時(shí)候先斷定cookie中是否存儲(chǔ)了用戶(hù)的信息,如果有則用cookie中存儲(chǔ)的用戶(hù)信息來(lái)登錄,
PHP學(xué)習(xí)配置User組件
PHP學(xué)習(xí)首先在配置文件的components中設(shè)置user組件
PHP學(xué)習(xí)
'user' => [
'identityClass' => 'app\models\User',
'enableAutoLogin' => true,
],
PHP學(xué)習(xí)我們看到enableAutoLogin便是用來(lái)判斷是否要啟用自動(dòng)登錄功能,這個(gè)和界面上的下次自動(dòng)登錄無(wú)關(guān).
只有在enableAutoLogin為true的情況下,如果選擇了下次自動(dòng)登錄,那么就會(huì)把用戶(hù)信息存儲(chǔ)起來(lái)放到cookie中并設(shè)置cookie的有效期為3600*24*30秒,以用于下次登錄
PHP學(xué)習(xí)現(xiàn)在我們來(lái)看看Yii中是怎樣實(shí)現(xiàn)的.
PHP學(xué)習(xí)一、第一次登錄存cookie
PHP學(xué)習(xí)1、login 登錄功能
PHP學(xué)習(xí)
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();
}
PHP學(xué)習(xí)在這里,就是簡(jiǎn)單的登錄,然后執(zhí)行switchIdentity辦法,設(shè)置認(rèn)證信息.
PHP學(xué)習(xí)2、switchIdentity設(shè)置認(rèn)證信息
PHP學(xué)習(xí)
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));
}
}
PHP學(xué)習(xí)這個(gè)辦法比較重要,在退出的時(shí)候也需要調(diào)用這個(gè)辦法.
PHP學(xué)習(xí)這個(gè)辦法主要有三個(gè)功能
設(shè)置session的有效期
如果cookie的有效期大于0并且允許自動(dòng)登錄,那么就把用戶(hù)的認(rèn)證信息保存到cookie中
如果允許自動(dòng)登錄,刪除cookie信息.這個(gè)是用于退出的時(shí)候調(diào)用的.退出的時(shí)候傳遞進(jìn)來(lái)的$identity為null
PHP學(xué)習(xí)
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);
}
PHP學(xué)習(xí)存儲(chǔ)在cookie中的用戶(hù)信息包括有三個(gè)值:
PHP學(xué)習(xí)getId()和getAuthKey()是在IdentityInterface接口中的.我們也知道在設(shè)置User組件的時(shí)候,這個(gè)User Model是必需要實(shí)現(xiàn)IdentityInterface接口的.所以,可以在User Model中得到前兩個(gè)值,第三值就是cookie的有效期.
PHP學(xué)習(xí)二、自動(dòng)從cookie登錄
PHP學(xué)習(xí)從上面我們知道用戶(hù)的認(rèn)證信息已經(jīng)存儲(chǔ)到cookie中了,那么下次的時(shí)候直接從cookie里面取信息然后設(shè)置就可以了.
PHP學(xué)習(xí)1、AccessControl用戶(hù)拜訪(fǎng)控制
PHP學(xué)習(xí)Yii提供了AccessControl來(lái)判斷用戶(hù)是否登錄,有了這個(gè)就不必要在每一個(gè)action里面再判斷了
PHP學(xué)習(xí)??
PHP學(xué)習(xí)
public function behaviors()
{
return [
'access' => [
'class' => AccessControl::className(),
'only' => ['logout'],
'rules' => [
[
'actions' => ['logout'],
'allow' => true,
'roles' => ['@'],
],
],
],
];
}
PHP學(xué)習(xí)2、getIsGuest、getIdentity斷定是否認(rèn)證用戶(hù)
PHP學(xué)習(xí)isGuest是自動(dòng)登錄過(guò)程中最重要的屬性.
在上面的AccessControl拜訪(fǎng)控制里面通過(guò)IsGuest屬性來(lái)判斷是否是認(rèn)證用戶(hù),然后在getIsGuest方法里面是調(diào)用getIdentity來(lái)獲取用戶(hù)信息,如果不為空就說(shuō)明是認(rèn)證用戶(hù),否則就是游客(未登錄).
PHP學(xué)習(xí)??
PHP學(xué)習(xí)
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;
}
PHP學(xué)習(xí)3、renewAuthStatus 重新生成用戶(hù)認(rèn)證信息
PHP學(xué)習(xí)???
PHP學(xué)習(xí)
protected function renewAuthStatus()
{
$session = Yii::$app->getSession();
$id = $session->getHasSessionId() || $session->getIsActive() ? $session->get($this->idParam) : null;
if ($id === null) {
$identity = null;
} else {
/** @var IdentityInterface $class */
$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();
}
}
}
PHP學(xué)習(xí)這一部門(mén)先通過(guò)session來(lái)判斷用戶(hù),因?yàn)橛脩?hù)登錄后就已經(jīng)存在于session中了.然后再判斷如果是自動(dòng)登錄,那么就通過(guò)cookie信息來(lái)登錄.
PHP學(xué)習(xí)4、通過(guò)保留的Cookie信息來(lái)登錄 loginByCookie
PHP學(xué)習(xí)???
PHP學(xué)習(xí)
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;
/** @var IdentityInterface $class */
$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__);
}
}
}
}
PHP學(xué)習(xí)先讀取cookie值,然后$data = json_decode($value, true);反序列化為數(shù)組.
PHP學(xué)習(xí)這個(gè)從上面的代碼可以知道要想實(shí)現(xiàn)自動(dòng)登錄,這三個(gè)值都必須有值.另外,在User Model中還必須要實(shí)現(xiàn)findIdentity、validateAuthKey這兩個(gè)辦法.
PHP學(xué)習(xí)登錄完成后,還可以再重新設(shè)置cookie的有效期,這樣便能一起有效下去了.
PHP學(xué)習(xí)
$this->switchIdentity($identity, $this->autoRenewCookie ? $duration : 0);
PHP學(xué)習(xí)三、退出 logout
PHP學(xué)習(xí)???
PHP學(xué)習(xí)
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));
}
}
PHP學(xué)習(xí)退出的時(shí)候先把當(dāng)前的認(rèn)證設(shè)置為null,然后再斷定如果是自動(dòng)登錄功能則再刪除相關(guān)的cookie信息.
《PHP教程:詳細(xì)解讀PHP的Yii框架中登陸功能的實(shí)現(xiàn)》是否對(duì)您有啟發(fā),歡迎查看更多與《PHP教程:詳細(xì)解讀PHP的Yii框架中登陸功能的實(shí)現(xiàn)》相關(guān)教程,學(xué)精學(xué)透。維易PHP學(xué)院為您提供精彩教程。
轉(zhuǎn)載請(qǐng)注明本頁(yè)網(wǎng)址:
http://www.snjht.com/jiaocheng/8779.html