Переглянути джерело

Merge branch 'bad_03_26_liu'

rkljw 3 тижнів тому
батько
коміт
88afaec873

+ 46 - 0
app/Command/ImportBadWordsCommand.php

@@ -0,0 +1,46 @@
+<?php
+
+namespace App\Command;
+
+use App\Model\BlackWord;
+use Hyperf\Command\Annotation\Command;
+use Hyperf\Command\Command as HyperfCommand;
+use Hyperf\Di\Annotation\Inject;
+use Hyperf\Redis\Redis;
+
+// 假设这是一个命令类,用于执行导入违禁词的操作
+// 可以通过命令行运行该命令:php bin/hyperf.php import:badwords
+#[Command]
+class ImportBadWordsCommand extends HyperfCommand
+{
+    public function __construct()
+    {
+        parent::__construct('import:badwords');
+    }
+
+    #[Inject]
+    protected Redis $redis;
+
+    public function handle()
+    {
+        // 假设这是从数据库或文件中获取的 30 万条违禁词数组
+        // 这里只是示例,实际应用中需要从相应数据源读取
+        $badWords = BlackWord::pluck('name')->toArray();
+        // 使用集合(Set)类型存储违禁词,键名为 'bad_words_set'
+        $redisKey = 'black_word';
+        $result = $this->redis->del($redisKey);
+        if ($result === 1) {
+            $this->info('已成功清空 black_word 集合。');
+        } else {
+            $this->error('清空 black_word 集合失败。');
+        }
+        // 开始事务,确保一次性导入所有违禁词
+        $this->redis->multi();
+        foreach ($badWords as $badWord) {
+            $this->redis->sAdd($redisKey, $badWord);
+        }
+        $this->redis->exec();
+
+        $this->info('违禁词已成功导入到 Redis 中!');
+    }
+}

+ 47 - 0
app/Command/ImportWhiteWordsCommand.php

@@ -0,0 +1,47 @@
+<?php
+
+namespace App\Command;
+
+use App\Model\BlackWord;
+use App\Model\WhiteWord;
+use Hyperf\Command\Annotation\Command;
+use Hyperf\Command\Command as HyperfCommand;
+use Hyperf\Di\Annotation\Inject;
+use Hyperf\Redis\Redis;
+
+// 假设这是一个命令类,用于执行导入违禁词的操作
+// 可以通过命令行运行该命令:php bin/hyperf.php import:whitewords
+#[Command]
+class ImportWhiteWordsCommand extends HyperfCommand
+{
+    public function __construct()
+    {
+        parent::__construct('import:whitewords');
+    }
+
+    #[Inject]
+    protected Redis $redis;
+
+    public function handle()
+    {
+        // 假设这是从数据库或文件中获取的 30 万条违禁词数组
+        // 这里只是示例,实际应用中需要从相应数据源读取
+        $badWords = WhiteWord::pluck('name')->toArray();
+        // 使用集合(Set)类型存储违禁词,键名为 'bad_words_set'
+        $redisKey = 'white_word';
+        $result = $this->redis->del($redisKey);
+        if ($result === 1) {
+            $this->info('已成功清空 white_word 集合。');
+        } else {
+            $this->error('清空 white_word 集合失败。');
+        }
+        // 开始事务,确保一次性导入所有违禁词
+        $this->redis->multi();
+        foreach ($badWords as $badWord) {
+            $this->redis->sAdd($redisKey, $badWord);
+        }
+        $this->redis->exec();
+
+        $this->info('白名单已成功导入到 Redis 中!');
+    }
+}

+ 29 - 44
app/Middleware/Auth/SensitiveMiddleware.php

@@ -12,8 +12,9 @@ use Psr\Http\Message\ResponseInterface;
 use Psr\Http\Message\ServerRequestInterface;
 use Psr\Http\Server\MiddlewareInterface;
 use Psr\Http\Server\RequestHandlerInterface;
-use function Hyperf\Support\env;
-
+use Hyperf\HttpMessage\Stream\SwooleStream;
+use Hyperf\Di\Annotation\Inject;
+use Hyperf\Redis\Redis;
 class SensitiveMiddleware implements MiddlewareInterface
 {
     protected ContainerInterface $container;
@@ -21,7 +22,8 @@ class SensitiveMiddleware implements MiddlewareInterface
     protected RequestInterface $request;
 
     protected HttpResponse $response;
-
+    #[Inject]
+    protected Redis $redis;
     public function __construct( RequestInterface $request, HttpResponse $response)
     {
         $this->request = $request;
@@ -31,53 +33,36 @@ class SensitiveMiddleware implements MiddlewareInterface
     public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
     {
         try {
-          $req = $this->request->all();
-          $concatenated = "";
-          if($req){
-              foreach ($req as $value) {
-                  if (is_array($value)) {
-                      // 如果值是数组,将数组元素用逗号连接
-                      $concatenated.= implode(',', $value);
-                  } else {
-                      // 如果不是数组,直接拼接
-                      $concatenated.= $value;
+            $badWords = $this->redis->sMembers('black_word'); //黑名单
+            $whiteWords = $this->redis->sMembers('white_word');//白名单
+            // 获取所有请求参数并拼接成文本
+            $params = $this->request->all();
+            $concatenated = "";
+             if($params){
+                  foreach ($params as $value) {
+                      if (is_array($value)) {
+                          // 如果值是数组,将数组元素用逗号连接
+                          $concatenated.= implode(',', $value);
+                      } else {
+                          // 如果不是数组,直接拼接
+                          $concatenated.= $value;
+                      }
                   }
               }
-          }
-          if(empty($concatenated)){
-              return $handler->handle($request);
-          }else{
-              $concatenated = preg_replace('/[0-9]/', '', $concatenated);
-              //白名单
-              $filterArray = array("http", "https",".","cn");
-              $concatenated = str_replace($filterArray, '', $concatenated);
-          }
-          $url = env("SENSITIVE_WORD")."?msg=".urlencode($concatenated);
-          $rep = PublicData::http_get($url);
-            if (preg_match('/\{[^{}]*"code":[^}]*\}/', $rep, $matches)) {
-                $jsonString = $matches[0];
-                // 解析 JSON 字符串为 PHP 数组
-                $jsonData = json_decode($jsonString, true);
-                if ($jsonData!== null) {
-                    // 输出解析后的 JSON 数据
-                    print_r($jsonData);
-                    if($jsonData['code']==200){
-                        if(isset($jsonData['num']) && $jsonData['num']>0){
-                            return $this->response->json(
-                                [
-                                    'code' => 0,
-                                    'data' => [],
-                                    'message' => "存在敏感词:".$jsonData['ci'],
-                                ]
-                            );
-                        }
-                    }
-                } else {
+            // 遍历违禁词,检查是否在文本中存在
+            foreach ($badWords as $badWord) {
+                // 判断该违禁词是否在白名单中,如果在则跳过
+                if (in_array($badWord, $whiteWords)) {
+                    continue;
+                }
+                if (str_contains($concatenated, $badWord)) {
+                    // 处理找到违禁词的情况,例如返回错误信息
+                    $message = '发现违禁词: '. $badWord;
                     return $this->response->json(
                         [
                             'code' => 0,
                             'data' => [],
-                            'message' => '解析敏感词接口失败',
+                            'message' => $message
                         ]
                     );
                 }

+ 22 - 0
app/Model/BlackWord.php

@@ -0,0 +1,22 @@
+<?php
+
+declare(strict_types=1);
+
+namespace App\Model;
+
+use Hyperf\DbConnection\Model\Model;
+
+/**
+ */
+class BlackWord extends Model
+{
+    /**
+     * The table associated with the model.
+     */
+    protected ?string $table = 'black_word';
+
+    /**
+     * The attributes that should be cast to native types.
+     */
+    protected array $casts = [];
+}

+ 22 - 0
app/Model/WhiteWord.php

@@ -0,0 +1,22 @@
+<?php
+
+declare(strict_types=1);
+
+namespace App\Model;
+
+use Hyperf\DbConnection\Model\Model;
+
+/**
+ */
+class WhiteWord extends Model
+{
+    /**
+     * The table associated with the model.
+     */
+    protected ?string $table = 'white_word';
+
+    /**
+     * The attributes that should be cast to native types.
+     */
+    protected array $casts = [];
+}

+ 1 - 1
config/autoload/middlewares.php

@@ -2,7 +2,7 @@
 return [
     'http' => [
         \App\Middleware\CorsMiddleware::class,
-//        \App\Middleware\Auth\SensitiveMiddleware::class,
+        \App\Middleware\Auth\SensitiveMiddleware::class,
         \Hyperf\Validation\Middleware\ValidationMiddleware::class,
     ],
     'ws' => [