Pārlūkot izejas kodu

fix:优化代码

aiden 4 mēneši atpakaļ
vecāks
revīzija
b89d56177f

+ 13 - 1
app/common.php

@@ -35,6 +35,18 @@ if(!function_exists('json_error')){
     }
 }
 
+/**
+ * 获取用户真实请求IP
+ * 使用ThinkPHP内置的Request::ip()方法
+ *
+ * @return string 返回客户端真实IP地址
+ */
+if(!function_exists('getClientIp')){
+    function getClientIp() {
+        return \think\facade\Request::ip();
+    }
+}
+
 /**
  * 生成JWT Token
  *
@@ -185,7 +197,7 @@ if(!function_exists('checkUserIpWhiteList')){
         }
         
         // 获取客户端IP
-        $clientIp = \app\service\IpWhiteListService::getRealIp();
+        $clientIp = getClientIp();
         
         // 检查IP白名单
         return \app\service\IpWhiteListService::checkIpWhiteList($clientIp, $userModel->white_list_ip);

+ 1 - 100
app/controller/User.php

@@ -49,12 +49,9 @@ class User extends BaseController
         // 查询用户
         $user = UserModel::where('user_name', $userName)->find();
         if ($user && password_verify($password, $user->password)) {
-            
             // 检查IP白名单
-            $clientIp = IpWhiteListService::getRealIp();
+            $clientIp = getClientIp();
             if (!IpWhiteListService::checkIpWhiteList($clientIp, $user->white_list_ip)) {
-                // 记录IP限制登录日志
-                trace("用户 {$userName} 尝试从IP {$clientIp} 登录,但不在白名单 {$user->white_list_ip} 中", 'info');
                 return json_error([
                     'client_ip' => $clientIp,
                     'white_list_ip' => $user->white_list_ip
@@ -71,9 +68,6 @@ class User extends BaseController
             $user->login_time = time();
             $user->save();
 
-            // 记录成功登录日志
-            trace("用户 {$userName} 从IP {$clientIp} 登录成功", 'info');
-
             return json_success([
                 'user_name' => $user->user_name,
                 'nick_name' => $user->nick_name,
@@ -358,99 +352,6 @@ class User extends BaseController
         }
     }
     
-    /**
-     * 验证IP白名单格式
-     */
-    public function validateIpWhiteList()
-    {
-        $loginInfo = checkUserLogin();
-        if (!$loginInfo) {
-            return json_error([], '请先登录');
-        }
-        
-        $whiteListIp = Request::post('white_list_ip', '', 'trim');
-        
-        try {
-            list($isValid, $message, $parsedList) = IpWhiteListService::validateWhiteListFormat($whiteListIp);
-            
-            return json_success([
-                'valid' => $isValid,
-                'message' => $message,
-                'parsed_list' => $parsedList,
-                'current_ip' => IpWhiteListService::getRealIp()
-            ], '验证完成');
-        } catch (\Exception $e) {
-            return json_error([], '验证失败:' . $e->getMessage());
-        }
-    }
-    
-    /**
-     * 获取当前访问IP信息
-     */
-    public function getCurrentIp()
-    {
-        $loginInfo = checkUserLogin();
-        if (!$loginInfo) {
-            return json_error([], '请先登录');
-        }
-        
-        try {
-            $currentIp = IpWhiteListService::getRealIp();
-            $ipInfo = IpWhiteListService::getIpInfo($currentIp);
-            
-            return json_success([
-                'current_ip' => $currentIp,
-                'ip_info' => $ipInfo,
-                'timestamp' => time(),
-                'datetime' => date('Y-m-d H:i:s')
-            ], '获取当前IP成功');
-        } catch (\Exception $e) {
-            return json_error([], '获取IP信息失败:' . $e->getMessage());
-        }
-    }
-    
-    /**
-     * 检查IP是否在用户白名单中
-     */
-    public function checkIpWhiteList()
-    {
-        $loginInfo = checkUserLogin();
-        if (!$loginInfo) {
-            return json_error([], '请先登录');
-        }
-        
-        $userId = Request::get('user_id', $loginInfo['user_id'], 'intval');
-        $testIp = Request::get('test_ip', '', 'trim');
-        
-        // 获取用户信息
-        $user = UserModel::where('user_id', $userId)
-            ->where('merchant_id', $loginInfo['merchant_id'])
-            ->find();
-            
-        if (!$user) {
-            return json_error([], '用户不存在');
-        }
-        
-        $currentIp = IpWhiteListService::getRealIp();
-        $checkIp = !empty($testIp) ? $testIp : $currentIp;
-        
-        try {
-            $isAllowed = IpWhiteListService::checkIpWhiteList($checkIp, $user->white_list_ip);
-            
-            return json_success([
-                'user_id' => $userId,
-                'user_name' => $user->user_name,
-                'check_ip' => $checkIp,
-                'white_list_ip' => $user->white_list_ip,
-                'is_allowed' => $isAllowed,
-                'current_ip' => $currentIp,
-                'is_current_ip' => $checkIp === $currentIp
-            ], $isAllowed ? 'IP在白名单中' : 'IP不在白名单中');
-        } catch (\Exception $e) {
-            return json_error([], '检查IP白名单失败:' . $e->getMessage());
-        }
-    }
-
     /**
      * 验证输入数据
      */

+ 1 - 1
app/controller/UserRole.php

@@ -66,7 +66,7 @@ class UserRole extends BaseController
             return json_error([], '没有查看角色详情的权限');
         }
         
-        $id = $this->request->param('id', 0, 'intval');
+        $id = Request::param('id', 0, 'intval');
         if (!$id) {
             return json_error([], '角色ID不能为空');
         }

+ 2 - 5
app/middleware/IpWhiteListMiddleware.php

@@ -45,13 +45,10 @@ class IpWhiteListMiddleware
         }
         
         // 获取客户端IP
-        $clientIp = IpWhiteListService::getRealIp();
+        $clientIp = getClientIp();
         
         // 检查IP白名单
-        if (!IpWhiteListService::checkIpWhiteList($clientIp, $user->white_list_ip)) {
-            // 记录IP限制访问日志
-            trace("用户 {$user->user_name} 尝试从IP {$clientIp} 访问 {$request->pathinfo()},但不在白名单 {$user->white_list_ip} 中", 'warning');
-            
+        if (!IpWhiteListService::checkIpWhiteList($clientIp, $user->white_list_ip)) {            
             return json([
                 'state' => 0,
                 'code' => 403,

+ 1 - 5
app/model/UserRoleModel.php

@@ -18,11 +18,7 @@ class UserRoleModel extends Model
     
     // 开启自动时间戳
     protected $autoWriteTimestamp = 'int';
-    
-    // 定义时间戳字段名
-    protected $createTime = 'create_time';
-    protected $updateTime = 'update_time';
-    
+        
     // 设置json类型字段
     protected $json = ['privileges'];
     

+ 0 - 58
app/service/IpWhiteListService.php

@@ -157,37 +157,7 @@ class IpWhiteListService
         
         return preg_match($pattern, $clientIp) === 1;
     }
-    
-    /**
-     * 获取客户端真实IP
-     * 
-     * @return string
-     */
-    public static function getRealIp(): string
-    {
-        $headers = [
-            'HTTP_X_FORWARDED_FOR',
-            'HTTP_X_REAL_IP',
-            'HTTP_CLIENT_IP',
-            'HTTP_CF_CONNECTING_IP',
-            'HTTP_X_CLUSTER_CLIENT_IP',
-            'REMOTE_ADDR'
-        ];
         
-        foreach ($headers as $header) {
-            if (!empty($_SERVER[$header])) {
-                $ips = explode(',', $_SERVER[$header]);
-                $ip = trim($ips[0]);
-                
-                if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)) {
-                    return $ip;
-                }
-            }
-        }
-        
-        return $_SERVER['REMOTE_ADDR'] ?? '0.0.0.0';
-    }
-    
     /**
      * 验证IP白名单格式
      * 
@@ -295,32 +265,4 @@ class IpWhiteListService
             'message' => '不支持的IP格式'
         ];
     }
-    
-    /**
-     * 获取IP地理位置信息(简单实现)
-     * 
-     * @param string $ip
-     * @return array
-     */
-    public static function getIpInfo(string $ip): array
-    {
-        // 内网IP检测
-        if (filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE) === false) {
-            return [
-                'ip' => $ip,
-                'type' => 'private',
-                'location' => '内网IP',
-                'isp' => '内网'
-            ];
-        }
-        
-        // 这里可以集成第三方IP地理位置服务
-        // 如:百度、腾讯、阿里云等IP查询API
-        return [
-            'ip' => $ip,
-            'type' => 'public',
-            'location' => '未知',
-            'isp' => '未知'
-        ];
-    }
 }