Procházet zdrojové kódy

feat:去除session逻辑

lizhi před 3 měsíci
rodič
revize
763d9c0b3a

+ 20 - 9
protected/components/Controller.php

@@ -14,6 +14,7 @@ class Controller extends CController
     public array $authIds = [];
     public array $companyIds = [];
     public array $schoolIds = [];
+    private int $_userId = 0;
 
     /**
      * 检查请求方是否合法
@@ -66,13 +67,17 @@ class Controller extends CController
     {
         $this->checkRequest();
 
+        $token = $_SERVER['HTTP_AUTHORIZATION']?? '';
+        $data = RedisInstance::getInstance()->get('user_token:'.$token);
+        $this->_userId = $data['id']?? 0;
+
         Yii::app()->language = 'zh_cn';
 		$controller = Yii::app()->controller->id;
 		$action = $this->getAction()->getId();
         $path = strtolower($controller . '/'. $action);
 		if( !in_array($controller, ['site'])
             &&!in_array($path, LewaimaiAdminPingtaiAuth::$noLoginRouters)
-            && Yii::app()->user->isGuest
+            && !$this->_userId
         ){
             Helper::error('请先登入', 401);
 		}
@@ -81,7 +86,7 @@ class Controller extends CController
         $this->_formatAuth();
 
 		if (!LewaimaiAdminPingtaiAuth::adminAuth($controller, $action)
-            && (!Yii::app()->user->isGuest && Yii::app()->user->_id != 1)
+            && (!$this->_userId && $this->_userId != 1)
         ) {
             Helper::error('您没有相应的权限');
 		}
@@ -91,10 +96,10 @@ class Controller extends CController
 
     private function _formatAuth(): void
     {
-        $key = 'user_auth_' . Yii::app()->user->_id;
+        $key = 'user_auth_' . $this->_userId;
         $data = RedisInstance::getInstance()->get($key);
         if (!$data) {
-            $model = Useradmin::model()->findByPk(Yii::app()->user->_id);
+            $model = Useradmin::model()->findByPk($this->_userId);
             $authIds = DB::getScalerWithCriteria(
                 'role',
                 DbCriteria::simpleCompare(['id' => $model->role_id])->setSelect('auth_ids')
@@ -114,17 +119,23 @@ class Controller extends CController
             $this->companyIds = $data['companyIds'];
             $this->schoolIds = $data['schoolIds'];
         }
+        LewaimaiAdminPingtaiAuth::$authIds = $this->authIds;
     }
 
     public function clearAuth($id = 0)
     {
-        $id = $id ? $id : Yii::app()->user->_id;
+        $id = $id ? : $this->_userId;
         RedisInstance::getInstance()->delete('user_auth_' . $id);
     }
 
+    private function getUserId()
+    {
+        return $this->_userId;
+    }
+
     public function getSchoolFilter($filed = 'school_id'):?array
     {
-        if (Yii::app()->user->_id == 1 || in_array(-1, $this->companyIds)) {
+        if ($this->_userId == 1 || in_array(-1, $this->companyIds)) {
             return null;
         }
         return $this->schoolIds;
@@ -132,7 +143,7 @@ class Controller extends CController
 
     public function checkSchoolId(int $id):bool
     {
-        if (Yii::app()->user->_id == 1 || in_array(-1, $this->schoolIds)) {
+        if ($this->_userId == 1 || in_array(-1, $this->schoolIds)) {
             return true;
         }
         return in_array($id, $this->schoolIds);
@@ -140,7 +151,7 @@ class Controller extends CController
 
     public function getCompanyFilter():?array
     {
-        if (Yii::app()->user->_id == 1 || in_array(-1, $this->companyIds)) {
+        if ($this->_userId == 1 || in_array(-1, $this->companyIds)) {
             return null;
         }
         return $this->companyIds;
@@ -148,7 +159,7 @@ class Controller extends CController
 
     public function checkCompanyId(int $id):bool
     {
-        if (Yii::app()->user->_id == 1 || in_array(-1, $this->companyIds)) {
+        if ($this->_userId == 1 || in_array(-1, $this->companyIds)) {
             return true;
         }
         return in_array($id, $this->companyIds);

+ 0 - 20
protected/components/MySession.php

@@ -1,20 +0,0 @@
-<?php
-
-class MySession extends CHttpSession
-{
-    public $_hasSetId;
-
-    /**
-     * 重写 session open 兼容前端 HTTP_AUTHORIZATION 传递的 token
-     * @return void
-     */
-    public function open()
-    {
-        $token = $_SERVER['HTTP_AUTHORIZATION']?? '';
-        if ($token && !$this->_hasSetId) {
-            $this->_hasSetId = true;
-            $this->setSessionID($token);
-        }
-        return parent::open();
-    }
-}

+ 9 - 6
protected/controllers/CommonController.php

@@ -189,9 +189,9 @@ class CommonController extends Controller
             Helper::error($res['msg'] ?? '上传出错');
         }
         if ($upType == 'avatar') {
-            $info = DB::getInfoById('useradmin', \Yii::app()->user->_id);
+            $info = DB::getInfoById('useradmin', $this->getUserId());
             Helper::imageDelete($info['avatar']);
-            DB::updateById('useradmin', ['avatar' => $upPath], \Yii::app()->user->_id);
+            DB::updateById('useradmin', ['avatar' => $upPath], $this->getUserId());
         }
         if ($upType == 'editor') {
             exit(json_encode([
@@ -225,14 +225,14 @@ class CommonController extends Controller
         if ( $new != $new1){
             Helper::error('新密码不一致');
         }
-        $info = DB::getInfoById('useradmin', \Yii::app()->user->_id);
+        $info = DB::getInfoById('useradmin', $this->getUserId());
         if (!$info) {
             Helper::error('用户未找到');
         }
         if (md5($old) != $info['password']) {
             Helper::error('旧密码错误');
         }
-        DB::updateById('useradmin', ['password' => md5($new)], \Yii::app()->user->_id);
+        DB::updateById('useradmin', ['password' => md5($new)], $this->getUserId());
         Helper::ok();
     }
 
@@ -248,7 +248,7 @@ class CommonController extends Controller
         if (!Helper::checkEmptyKey($info, ['username', 'phone', 'email'])) {
             Helper::error('参数错误');
         }
-        DB::updateById('useradmin', $info, \Yii::app()->user->_id);
+        DB::updateById('useradmin', $info, $this->getUserId());
         Helper::ok();
     }
 
@@ -257,7 +257,10 @@ class CommonController extends Controller
      */
     public function actionLogout()
     {
-        Yii::app()->user->logout();
+        $token = $_SERVER['HTTP_AUTHORIZATION']?? '';
+        if ($token) {
+            RedisInstance::getInstance()->delete('user_token:'.$token);
+        }
         Helper::ok();
     }
 }

+ 2 - 2
protected/controllers/CompanyController.php

@@ -175,12 +175,12 @@ class CompanyController extends Controller
                     throw new \Exception('添加失败');
                 }
                 // 给用户操作权限
-                $user = DB::getInfoById('useradmin', \Yii::app()->user->_id);
+                $user = DB::getInfoById('useradmin', $this->getUserId());
                 if (!str_contains($user['company_ids'], '-1')) {
                     DB::updateById(
                         'useradmin',
                         ['company_ids' => trim($user['company_ids'] . ',' . $id, ',')],
-                        \Yii::app()->user->_id
+                        $this->getUserId()
                     );
                 }
                 $this->clearAuth();

+ 1 - 1
protected/controllers/FollowController.php

@@ -47,7 +47,7 @@ class FollowController extends Controller
 
     private function _add($type)
     {
-        $userID = Yii::app()->user->_id;
+        $userID = $this->getUserId();
         $this->type = $type;
         $this->tableArr = self::TYPE_TABLE_MAP[$this->type];
         $firstId = Helper::getPostInt('first_id');

+ 2 - 2
protected/controllers/SchoolController.php

@@ -160,12 +160,12 @@ class SchoolController extends Controller
             } else {
                 $id = DB::addData(self::$table, $data);
                 // 给用户操作权限
-                $user = DB::getInfoById('useradmin', \Yii::app()->user->_id);
+                $user = DB::getInfoById('useradmin', $this->getUserId());
                 if (!str_contains($user['school_ids'], '-1')) {
                     DB::updateById(
                         'useradmin',
                         ['school_ids' => trim($user['school_ids'].','.$id, ',')],
-                        \Yii::app()->user->_id
+                        $this->getUserId()
                     );
                     $this->clearAuth();
                 }

+ 13 - 11
protected/controllers/SiteController.php

@@ -24,17 +24,19 @@ class SiteController extends Controller
 	 */
 	public function actionLogin()
 	{
-        $model=new LoginForm;
-		if (isset($_POST['username'])) {
-			$model->attributes=$_POST;
-			if($model->validate() && $model->login()){
-                $this->clearAuth();
-                Helper::ok(['token' => \Yii::app()->session->getSessionID(), 'refreshToken' => '']);
-            } else {
-                Helper::error('登入失败');
-            }
-		}
-        Helper::error('参数错误');
+        $userName = Helper::getPostString('username', '');
+        $password = Helper::getPostString('password', '');
+		if (!($userName && $password)) {
+            Helper::error('参数错误');
+        }
+        $user = DB::getInfoWithCriteria('useradmin', DbCriteria::simpleCompare(['username' => $userName])->setSelect('id, password'));
+        if (!$user || $user['password'] != md5($password)) {
+            Helper::error('登入失败');
+        }
+        $token = Helper::getRandomString(32);
+        RedisInstance::getInstance()->set('user_token:'.$token, ['id' => $user['id']], 86400);
+        $this->clearAuth();
+        Helper::ok(['token' => $token, 'refreshToken' => '']);
 	}
 
     /**

+ 1 - 1
protected/controllers/UseradminController.php

@@ -11,7 +11,7 @@ class UseradminController extends Controller
 
     public function actionInfo()
     {
-        $model = Useradmin::model()->findByPk(Yii::app()->user->_id);
+        $model = Useradmin::model()->findByPk($this->getUserId());
         if (!$model) {
             Helper::error('信息未找到');
         }

+ 0 - 32
protected/include/Helper.php

@@ -408,38 +408,6 @@ class Helper
         return $str;
     }
 
-    //php防注入和XSS攻击通用过滤
-    public static function safeFilter (&$arr)
-    {
-        $ra=Array('/([\x00-\x08,\x0b-\x0c,\x0e-\x19])/','/script/','/javascript/','/vbscript/','/expression/','/applet/'
-        ,'/meta/','/xml/','/blink/','/link/','/style/','/embed/','/object/','/frame/','/layer/','/title/','/bgsound/'
-        ,'/base/','/onload/','/onunload/','/onchange/','/onsubmit/','/onreset/','/onselect/','/onblur/','/onfocus/',
-            '/onabort/','/onkeydown/','/onkeypress/','/onkeyup/','/onclick/','/ondblclick/','/onmousedown/','/onmousemove/'
-        ,'/onmouseout/','/onmouseover/','/onmouseup/','/onunload/');
-
-        if (is_array($arr))
-        {
-            foreach ($arr as $key => $value)
-            {
-                if (!is_array($value))
-                {
-                    if (!get_magic_quotes_gpc())  //不对magic_quotes_gpc转义过的字符使用addslashes(),避免双重转义。
-                    {
-                        $value  = addslashes($value); //给单引号(')、双引号(")、反斜线(\)与 NUL(NULL 字符)
-                        #加上反斜线转义
-                    }
-                    $value       = preg_replace($ra,'',$value);     //删除非打印字符,粗暴式过滤xss可疑字符串
-                    // $arr[$key]     = htmlentities(strip_tags($value)); //去除 HTML 和 PHP 标记并转换为 HTML 实体
-                }
-                else
-                {
-                    self::SafeFilter($arr[$key]);
-                }
-            }
-        }
-        return $arr;
-    }
-
     public static function getSign($data)
     {
         return md5($data . "145709480B89EE59E3F4D43A56C355F2");

+ 2 - 11
protected/include/LewaimaiAdminPingtaiAuth.php

@@ -10,7 +10,7 @@ use Yii;
 class LewaimaiAdminPingtaiAuth
 {
 
-    public static $_authIds;
+    public static $authIds = [];
 
     /**
      * @var array 不需要登入的 routers
@@ -39,16 +39,7 @@ class LewaimaiAdminPingtaiAuth
         if (empty($num)) {
             return false;
         }
-
-        if (is_null(self::$_authIds)) {
-            $model = Useradmin::model()->findByPk(Yii::app()->user->_id);
-            $authIds = DB::getScalerWithCriteria(
-                'role',
-                DbCriteria::simpleCompare(['id' => $model->role_id])->setSelect('auth_ids')
-            );
-            self::$_authIds = $authIds ? explode(',', $authIds) : [];
-        }
-        if (in_array($num, self::$_authIds)) {
+        if (in_array($num, self::$authIds)) {
             return true;
         }
 

+ 1 - 2
protected/include/LewaimaiExport.php

@@ -57,8 +57,7 @@ class LewaimaiExport
     public static function produceCsv($data, $filename, $file_path = '')
     {
         if (empty($file_path)) {
-            $admin_id = Yii::app()->user->_id;
-            $dir_name = $admin_id.date('YmdHis', time());
+            $dir_name = date('YmdHis', time());
             $file_path = Yii::app()->getBasePath().'/data/csv/'.$dir_name;
         }
         $filename = $file_path.'/'.$filename.'.csv';