麻豆小视频在线观看_中文黄色一级片_久久久成人精品_成片免费观看视频大全_午夜精品久久久久久久99热浪潮_成人一区二区三区四区

首頁 > 開發 > PHP > 正文

詳細解讀PHP的Yii框架中登陸功能的實現

2024-05-04 23:38:52
字體:
來源:轉載
供稿:網友

這篇文章主要介紹了詳細解讀PHP的Yii框架中登陸功能的實現,包括通過cookie實現自動登錄的功能,需要的朋友可以參考下

Yii的登陸機制

Yii 生成應用時已經提供了最基礎的用戶登陸機制。我們用 Yii 生成一個新的應用,進入 protected/components 目錄,我們可以看到 UserIdentity.php 文件,里面的 UserIdentity 類里面只有一個 public 函數如下:

 

 
  1. public function authenticate()  
  2. {  
  3. $users=array(  
  4. // username => password  
  5. 'demo'=>'demo',  
  6. 'admin'=>'admin',  
  7. );  
  8. if(!isset($users[$this->username]))  
  9. $this->errorCode=self::ERROR_USERNAME_INVALID;  
  10. elseif($users[$this->username]!==$this->password)  
  11. $this->errorCode=self::ERROR_PASSWORD_INVALID;  
  12. else 
  13. $this->errorCode=self::ERROR_NONE;  
  14. return !$this->errorCode;  
  15. }  

這個類在 components 里面,會在應用一開始的時候就加載,用于最基礎的用戶驗證,可以看到,該函數一開始只是簡單地定義了兩個用戶 demo 和 admin,而密碼也只是 demo 和 admin,如果所以如果你的用戶很有限的話,可以直接在這里面修改添加用戶就行,多的話我們后面再說。函數下面的 if else 分別是用于檢查用戶名和密碼是否有效,出錯的時候生成 ERROR_USERNAME_INVALID,ERROR_PASSWORD_INVALID 這些錯誤。總的來說,這里進行了真正的用戶名密碼驗證,并進行登陸后的基本邏輯處理。

單看這個類還是看不出登陸控制流程的。遵循 Model/ Control/ View 的原則,我們可以看到登陸流程在這三方面的體現。首先進入 Models 文件夾,你可以看到一個 LoginForm 的類文件,這個類繼承了 CFormModel ,為表單模型的派生類,封裝了關于登陸的數據及業務邏輯。比較核心的函數如下:

 

  1. /**  
  2. * Authenticates the password.  
  3. * This is the 'authenticate' validator as declared in rules().  
  4. */ 
  5. public function authenticate($attribute,$params)  
  6. {  
  7. $this->_identity=new UserIdentity($this->username,$this->password);  
  8. if(!$this->_identity->authenticate())  
  9. $this->addError('password','用戶名或密碼錯誤');  
  10. }  
  11.  
  12. /**  
  13. * Logs in the user using the given username and password in the model.  
  14. * @return boolean whether login is successful  
  15. */ 
  16. public function login()  
  17. {  
  18. if($this->_identity===null)  
  19. {  
  20. $this->_identity=new UserIdentity($this->username,$this->password);  
  21. $this->_identity->authenticate();  
  22. }  
  23. if($this->_identity->errorCode===UserIdentity::ERROR_NONE)  
  24. {  
  25. $duration=$this->rememberMe ? 3600*24*30 : 0; // 30 days  
  26. Yii::app()->user->login($this->_identity,$duration);  
  27. return true;  
  28. }  
  29. else 
  30. return false;  
  31. }  

這里的 authenticate 利用 UserIdentity 類對用戶名密碼進行驗證,而 login 函數通過檢測用戶身份是否已經設置及錯誤碼是否為空,最后進行 Yii 提供的 login 函數進行登陸。$duration 可以設置身份的有效期。

再看 Control,在 siteControler 里面有一個 action 是關于登錄的,就是 actionLogin, 函數如下:

 

 
  1. /**  
  2. * Displays the login page  
  3. */ 
  4. public function actionLogin()  
  5. {  
  6. if (!defined('CRYPT_BLOWFISH')||!CRYPT_BLOWFISH)  
  7. throw new CHttpException(500,"This application requires that PHP was compiled with Blowfish support for crypt().");  
  8.  
  9. $model=new LoginForm;  
  10.  
  11. // if it is ajax validation request  
  12. if(isset($_POST['ajax']) && $_POST['ajax']==='login-form')  
  13. {  
  14. echo CActiveForm::validate($model);  
  15. Yii::app()->end();  
  16. }  
  17.  
  18. // collect user input data  
  19. if(isset($_POST['LoginForm']))  
  20. {  
  21. $model->attributes=$_POST['LoginForm'];  
  22. // validate user input and redirect to the previous page if valid  
  23. if($model->validate() && $model->login())  
  24. $this->redirect(Yii::app()->user->returnUrl);  
  25. }  
  26. // display the login form  
  27. $this->render('login',array('model'=>$model));  
  28. }  

該 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 的表:

 

  1. drop table if exists `admin`;  
  2. create table `admin` (  
  3. `admin_id` int unsigned not null auto_increment comment '主鍵',  
  4. `username` varchar(32) not null comment '登錄名',  
  5. `psw` char(40) not null comment '登錄密碼(兩次sha1)',  
  6. `nick` varchar(64) not null comment '昵稱',  
  7. `add_time` datetime not null comment '創建時間',  
  8. `login_time` datetime null comment '最近登錄時間',  
  9. unique key(`username`),  
  10. primary key (`admin_id`)  
  11. ) 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 保存到數據庫中。

 

 
  1. public function authenticate()  
  2. {  
  3. if(strlen($this->password) > 0)  
  4. $this->password = sha1(sha1($this->password));  
  5. $user = Admin::model()->findByAttributes(array('username' => $this->username));  
  6. if($user == null)  
  7. $this->errorCode=self::ERROR_USERNAME_INVALID;  
  8. elseif( !($user instanceof Admin) || ($user->psw != $this->password) )  
  9. $this->errorCode=self::ERROR_PASSWORD_INVALID;  
  10. else 
  11. {  
  12. $this->setState('admin_id', $user->admin_id);  
  13. $this->setState('nick', $user->nick);  
  14. $this->setState('username', $user->username);  
  15. $user->login_time = date('Y-m-d H:i:s');  
  16. $user->save();  
  17. $this->errorCode=self::ERROR_NONE;  
  18. }  
  19. return !$this->errorCode;  
  20. }  

而如果你想要修改登陸的界面,那就進入 view 里面 site 文件夾中的 login.php ,盡情地折騰讓它變成你想要的樣子,這樣我們自己的登陸流程也完成了。有了 Yii 是不是方便極了~

設置自動登陸

自動登錄的原理很簡單。主要就是利用cookie來實現的

在第一次登錄的時候,如果登錄成功并且選中了下次自動登錄,那么就會把用戶的認證信息保存到cookie中,cookie的有效期為1年或者幾個月。

在下次登錄的時候先判斷cookie中是否存儲了用戶的信息,如果有則用cookie中存儲的用戶信息來登錄,

配置User組件

首先在配置文件的components中設置user組件

 

 
  1. 'user' => [ 
  2. 'identityClass' => 'app/models/User'
  3. 'enableAutoLogin' => true
  4. ], 

我們看到enableAutoLogin就是用來判斷是否要啟用自動登錄功能,這個和界面上的下次自動登錄無關。

只有在enableAutoLogin為true的情況下,如果選擇了下次自動登錄,那么就會把用戶信息存儲起來放到cookie中并設置cookie的有效期為3600*24*30秒,以用于下次登錄

現在我們來看看Yii中是怎樣實現的。

一、第一次登錄存cookie

1、login 登錄功能

 

  1. public function login($identity, $duration = 0) 
  2. if ($this->beforeLogin($identity, false, $duration)) { 
  3. $this->switchIdentity($identity, $duration); 
  4. $id = $identity->getId(); 
  5. $ip = Yii::$app->getRequest()->getUserIP(); 
  6. Yii::info("User '$id' logged in from $ip with duration $duration.", __METHOD__); 
  7. $this->afterLogin($identity, false, $duration); 
  8.  
  9. return !$this->getIsGuest(); 

在這里,就是簡單的登錄,然后執行switchIdentity方法,設置認證信息。

2、switchIdentity設置認證信息

 

 
  1. public function switchIdentity($identity, $duration = 0) 
  2. $session = Yii::$app->getSession(); 
  3. if (!YII_ENV_TEST) { 
  4. $session->regenerateID(true); 
  5. $this->setIdentity($identity); 
  6. $session->remove($this->idParam); 
  7. $session->remove($this->authTimeoutParam); 
  8. if ($identity instanceof IdentityInterface) { 
  9. $session->set($this->idParam, $identity->getId()); 
  10. if ($this->authTimeout !== null) { 
  11. $session->set($this->authTimeoutParam, time() + $this->authTimeout); 
  12. if ($duration > 0 && $this->enableAutoLogin) { 
  13. $this->sendIdentityCookie($identity, $duration); 
  14. } elseif ($this->enableAutoLogin) { 
  15. Yii::$app->getResponse()->getCookies()->remove(new Cookie($this->identityCookie)); 

這個方法比較重要,在退出的時候也需要調用這個方法。

這個方法主要有三個功能

設置session的有效期

如果cookie的有效期大于0并且允許自動登錄,那么就把用戶的認證信息保存到cookie中

如果允許自動登錄,刪除cookie信息。這個是用于退出的時候調用的。退出的時候傳遞進來的$identity為null

 

 
  1. protected function sendIdentityCookie($identity, $duration) 
  2. $cookie = new Cookie($this->identityCookie); 
  3. $cookie->value = json_encode([ 
  4. $identity->getId(), 
  5. $identity->getAuthKey(), 
  6. $duration, 
  7. ]); 
  8. $cookie->expire = time() + $duration; 
  9. 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里面再判斷了

 

 
  1. public function behaviors() 
  2. return [ 
  3. 'access' => [ 
  4. 'class' => AccessControl::className(), 
  5. 'only' => ['logout'], 
  6. 'rules' => [ 
  7. 'actions' => ['logout'], 
  8. 'allow' => true
  9. 'roles' => ['@'], 
  10. ], 
  11. ], 
  12. ], 
  13. ]; 

2、getIsGuest、getIdentity判斷是否認證用戶

isGuest是自動登錄過程中最重要的屬性。

在上面的AccessControl訪問控制里面通過IsGuest屬性來判斷是否是認證用戶,然后在getIsGuest方法里面是調用getIdentity來獲取用戶信息,如果不為空就說明是認證用戶,否則就是游客(未登錄)。

 

 
  1. public function getIsGuest($checkSession = true
  2. return $this->getIdentity($checkSession) === null
  3. public function getIdentity($checkSession = true
  4. if ($this->_identity === false) { 
  5. if ($checkSession) { 
  6. $this->renewAuthStatus(); 
  7. else { 
  8. return null
  9.  
  10. return $this->_identity; 

3、renewAuthStatus 重新生成用戶認證信息

 

 
  1. protected function renewAuthStatus() 
  2. $session = Yii::$app->getSession(); 
  3. $id = $session->getHasSessionId() || $session->getIsActive() ? $session->get($this->idParam) : null
  4.  
  5. if ($id === null) { 
  6. $identity = null
  7. else { 
  8. /** @var IdentityInterface $class */ 
  9. $class = $this->identityClass; 
  10. $identity = $class::findIdentity($id); 
  11.  
  12. $this->setIdentity($identity); 
  13.  
  14. if ($this->authTimeout !== null && $identity !== null) { 
  15. $expire = $session->get($this->authTimeoutParam); 
  16. if ($expire !== null && $expire < time()) { 
  17. $this->logout(false); 
  18. else { 
  19. $session->set($this->authTimeoutParam, time() + $this->authTimeout); 
  20.  
  21. if ($this->enableAutoLogin) { 
  22. if ($this->getIsGuest()) { 
  23. $this->loginByCookie(); 
  24. } elseif ($this->autoRenewCookie) { 
  25. $this->renewIdentityCookie(); 

這一部分先通過session來判斷用戶,因為用戶登錄后就已經存在于session中了。然后再判斷如果是自動登錄,那么就通過cookie信息來登錄。

4、通過保存的Cookie信息來登錄 loginByCookie

 

 
  1. protected function loginByCookie() 
  2. $name = $this->identityCookie['name']; 
  3. $value = Yii::$app->getRequest()->getCookies()->getValue($name); 
  4. if ($value !== null) { 
  5. $data = json_decode($value, true); 
  6. if (count($data) === 3 && isset($data[0], $data[1], $data[2])) { 
  7. list ($id, $authKey, $duration) = $data; 
  8. /** @var IdentityInterface $class */ 
  9. $class = $this->identityClass; 
  10. $identity = $class::findIdentity($id); 
  11. if ($identity !== null && $identity->validateAuthKey($authKey)) { 
  12. if ($this->beforeLogin($identity, true, $duration)) { 
  13. $this->switchIdentity($identity, $this->autoRenewCookie ? $duration : 0); 
  14. $ip = Yii::$app->getRequest()->getUserIP(); 
  15. Yii::info("User '$id' logged in from $ip via cookie.", __METHOD__); 
  16. $this->afterLogin($identity, true, $duration); 
  17. } elseif ($identity !== null) { 
  18. Yii::warning("Invalid auth key attempted for user '$id': $authKey", __METHOD__); 

先讀取cookie值,然后$data = json_decode($value, true);反序列化為數組。

這個從上面的代碼可以知道要想實現自動登錄,這三個值都必須有值。另外,在User Model中還必須要實現findIdentity、validateAuthKey這兩個方法。

登錄完成后,還可以再重新設置cookie的有效期,這樣便能一起有效下去了。

 

 
  1. $this->switchIdentity($identity, $this->autoRenewCookie ? $duration : 0); 

三、退出 logout

 

 
  1. public function logout($destroySession = true
  2. $identity = $this->getIdentity(); 
  3. if ($identity !== null && $this->beforeLogout($identity)) { 
  4. $this->switchIdentity(null); 
  5. $id = $identity->getId(); 
  6. $ip = Yii::$app->getRequest()->getUserIP(); 
  7. Yii::info("User '$id' logged out from $ip.", __METHOD__); 
  8. if ($destroySession) { 
  9. Yii::$app->getSession()->destroy(); 
  10. $this->afterLogout($identity); 
  11.  
  12. return $this->getIsGuest(); 
  13.  
  14.  
  15. public function switchIdentity($identity, $duration = 0) 
  16. $session = Yii::$app->getSession(); 
  17. if (!YII_ENV_TEST) { 
  18. $session->regenerateID(true); 
  19. $this->setIdentity($identity); 
  20. $session->remove($this->idParam); 
  21. $session->remove($this->authTimeoutParam); 
  22. if ($identity instanceof IdentityInterface) { 
  23. $session->set($this->idParam, $identity->getId()); 
  24. if ($this->authTimeout !== null) { 
  25. $session->set($this->authTimeoutParam, time() + $this->authTimeout); 
  26. if ($duration > 0 && $this->enableAutoLogin) { 
  27. $this->sendIdentityCookie($identity, $duration); 
  28. } elseif ($this->enableAutoLogin) { 
  29. Yii::$app->getResponse()->getCookies()->remove(new Cookie($this->identityCookie)); 

退出的時候先把當前的認證設置為null,然后再判斷如果是自動登錄功能則再刪除相關的cookie信息。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: av电影在线观看网站 | 鲁久久 | 国产91一区二区三区 | 亚洲成人免费电影 | 亚洲国产成人一区二区 | 亚洲一区在线免费视频 | 成年免费大片黄在线观看岛国 | 免费黄色在线电影 | 又黄又爽免费无遮挡在线观看 | 亚洲一区二区在线视频 | 在线 日本 制服 中文 欧美 | 一级黄色欧美 | 精品免费国产一区二区三区 | 国产免费一区二区三区最新不卡 | 国产91对白叫床清晰播放 | av色先锋| 国产在线看一区 | 午夜精品久久久久久久99热浪潮 | 久色网站| 免费观看一级黄色片 | 日本免费aaa观看 | 成人在线免费观看视频 | 99热久草 | 精国产品一区二区三区四季综 | 欧美另类综合 | 羞羞的视频在线 | 成人在线视频精品 | 国内精品久久久久久久星辰影视 | 禁漫天堂久久久久久久久久 | 欧美色视频免费 | 欧美日韩一区,二区,三区,久久精品 | 激情久久一区二区 | 黄网站免费入口 | 农村少妇吞精夜夜爽视频 | 婷婷久久网 | 线观看免费完整aaa 欧美在线一级 | 久久网一区二区 | 国产美女视频一区二区三区 | 午夜视频久久 | 刘亦菲一区二区三区免费看 | 99影视在线视频免费观看 |