瀏覽代碼

Allow dynamic redirect when access is rejected

BrettonYe 1 年之前
父節點
當前提交
5d6e7412d4

+ 64 - 49
app/Http/Middleware/isForbidden.php

@@ -13,69 +13,84 @@ class isForbidden
 {
     /**
      * 限制机器人、指定IP访问.
-     *
-     * @return mixed
      */
-    public function handle(Request $request, Closure $next)
-    { // 限制机器人、指定IP访问.
+    public function handle(Request $request, Closure $next): mixed
+    {
         // 拒绝机器人访问
         if (sysConfig('is_forbid_robot') && Agent::isRobot()) {
-            Log::warning('识别到机器人('.IP::getClientIp().')访问');
+            Log::warning(trans('errors.forbidden.bots').': '.IP::getClientIp());
 
             return Response::view('auth.error', ['message' => trans('errors.forbidden.bots')], 403);
         }
 
-        // 拒绝通过订阅链接域名访问网站,防止网站被探测
-        if (config('app.env') === 'production' && sysConfig('website_url') && ! str_contains(sysConfig('website_url'), $request->getHost())) {
-            Log::warning('识别到通过订阅链接访问,强制跳转至百度('.IP::getClientIp().') '.$request->fullUrl());
+        // 拒绝通过非网站链接访问网站,防止网站被探测
+        if ($this->isForbiddenSubscription($request)) {
+            Log::warning(trans('errors.forbidden.redirect', ['ip' => IP::getClientIp(), 'url' => $request->fullUrl()]));
 
             return redirect(sysConfig('redirect_url', 'https://www.baidu.com').'?url='.$request->url());
         }
 
-        if (sysConfig('forbid_mode')) {
-            $ip = IP::getClientIP();
-            $ipLocation = IP::getIPInfo($ip);
-
-            if ($ipLocation !== false) {
-                // 拒绝无IP请求
-                if (empty($ipLocation) || empty(array_filter($ipLocation))) {
-                    Log::warning(trans('errors.forbidden.access').": $ip");
-
-                    return Response::view('auth.error', ['message' => trans('errors.forbidden.access')], 403);
-                }
-
-                if (! in_array($ipLocation['country'], ['本机地址', '局域网'])) {
-                    // 拒绝大陆IP访问
-                    switch (sysConfig('forbid_mode')) {
-                        case 'ban_mainland':
-                            if (in_array($ipLocation['country'], ['China', '中国', 'CN']) && ! in_array($ipLocation['region'], ['Taiwan', 'Hong Kong', 'Macao', '香港', '澳门', '台湾', '台湾省'])) {
-                                Log::warning(trans('errors.forbidden.china').": $ip");
-
-                                return Response::view('auth.error', ['message' => trans('errors.forbidden.china')], 403);
-                            }
-                            break;
-                        case 'ban_china':
-                            if (in_array($ipLocation['country'], ['China', '中国', 'Taiwan', 'Hong Kong', 'Macao', '香港', '台湾', '澳门'])) {
-                                Log::warning(trans('errors.forbidden.china').": $ip");
-
-                                return Response::view('auth.error', ['message' => trans('errors.forbidden.china')], 403);
-                            }
-                            break;
-                        case 'ban_oversea':
-                            if (! in_array($ipLocation['country'], ['China', '中国', 'Taiwan', 'Hong Kong', 'Macao', '香港', '台湾', '澳门'])) {
-                                Log::warning(trans('errors.forbidden.oversea').": $ip - ".$ipLocation['country']);
-
-                                return Response::view('auth.error', ['message' => trans('errors.forbidden.oversea')], 403);
-                            }
-                            break;
-                        default:
-                            Log::emergency(trans('errors.forbidden.unknown'));
-                            break;
+        // 拒绝特定IP访问
+        if (sysConfig('forbid_mode') && $this->isForbiddenIP()) {
+            return Response::view('auth.error', ['message' => trans('errors.forbidden.access')], 403);
+        }
+
+        return $next($request);
+    }
+
+    /**
+     * 检查是否通过非网站链接访问.
+     */
+    private function isForbiddenSubscription(Request $request): bool
+    {
+        return config('app.env') === 'production' && sysConfig('website_url') && ! str_contains(sysConfig('website_url'), $request->getHost());
+    }
+
+    /**
+     * 检查是否为禁止访问的IP.
+     */
+    private function isForbiddenIP(): bool
+    {
+        $ip = IP::getClientIP();
+        $ipLocation = IP::getIPInfo($ip);
+
+        if (! $ipLocation || empty(array_filter($ipLocation))) {
+            Log::warning(trans('errors.forbidden.access').": $ip");
+
+            return true;
+        }
+
+        if (! in_array($ipLocation['country'], ['本机地址', '局域网'])) {
+            switch (sysConfig('forbid_mode')) {
+                case 'ban_mainland':
+                    if (in_array($ipLocation['country'], ['China', '中国', 'CN']) &&
+                        ! in_array($ipLocation['region'], ['Taiwan', 'Hong Kong', 'Macao', '香港', '澳门', '台湾', '台湾省'])) {
+                        Log::warning(trans('errors.forbidden.china').": $ip");
+
+                        return true;
                     }
-                }
+                    break;
+                case 'ban_china':
+                    if (in_array($ipLocation['country'], ['China', '中国', 'Taiwan', 'Hong Kong', 'Macao', '香港', '台湾', '澳门'])) {
+                        Log::warning(trans('errors.forbidden.china').": $ip");
+
+                        return true;
+                    }
+                    break;
+                case 'ban_oversea':
+                    if (! in_array($ipLocation['country'], ['China', '中国', 'Taiwan', 'Hong Kong', 'Macao', '香港', '台湾', '澳门'])) {
+                        Log::warning(trans('errors.forbidden.oversea').": $ip - ".$ipLocation['country']);
+
+                        return true;
+                    }
+                    break;
+                default:
+                    Log::emergency(trans('errors.forbidden.unknown'));
+
+                    return true;
             }
         }
 
-        return $next($request);
+        return false;
     }
 }

+ 1 - 0
resources/lang/de/errors.php

@@ -9,6 +9,7 @@ return [
         'china' => 'China-IP oder Proxy-Zugriff erkannt, Zugriff verweigert',
         'oversea' => 'Übersee-IP oder Proxy-Zugriff erkannt, Zugriff verweigert',
         'unknown' => 'Unbekannter verbotener Zugriffsmodus! Bitte ändern Sie den [Zugriffsbeschränkung] in den Systemeinstellungen!',
+        'redirect' => '(:ip :url) wurde beim Zugriff über einen Abonnement-Link erkannt, erzwungene Weiterleitung.',
     ],
     'log' => 'Protokoll',
     'refresh' => 'Aktualisieren',

+ 1 - 0
resources/lang/en/errors.php

@@ -9,6 +9,7 @@ return [
         'china' => 'Detected China IP or proxy access, access denied',
         'oversea' => 'Detected overseas IP or proxy access, access denied',
         'unknown' => 'Unknown forbidden access mode! Please modify the [Access Restriction] in the system settings!',
+        'redirect' => 'Detected (:ip :url) accessing through a subscription link, forcing a redirect.',
     ],
     'log' => 'Log',
     'refresh' => 'Refresh',

+ 1 - 0
resources/lang/fa/errors.php

@@ -9,6 +9,7 @@ return [
         'china' => 'دسترسی IP یا پروکسی چین شناسایی شد، دسترسی ممنوع',
         'oversea' => 'دسترسی IP یا پروکسی خارج از کشور شناسایی شد، دسترسی ممنوع',
         'unknown' => 'حالت دسترسی ممنوع ناشناخته! لطفاً [حالت مسدودسازی] را در تنظیمات سیستم تغییر دهید!',
+        'redirect' => '(:ip :url) از طریق پیوند اشتراک دسترسی شناسایی شد، تغییر مسیر اجباری.',
     ],
     'log' => 'لاگ',
     'refresh' => 'تازه‌سازی',

+ 1 - 0
resources/lang/ja/errors.php

@@ -9,6 +9,7 @@ return [
         'china' => '中国のIPまたはプロキシアクセスが検出されました。アクセス禁止',
         'oversea' => '海外のIPまたはプロキシアクセスが検出されました。アクセス禁止',
         'unknown' => '不明な禁止アクセスモード!システム設定で[アクセス禁止モード]を変更してください!',
+        'redirect' => '(:ip :url)がサブスクリプションリンクを通じてアクセスしていることを検出しました。強制リダイレクトを実行します。',
     ],
     'log' => 'ログ',
     'refresh' => 'リフレッシュ',

+ 1 - 0
resources/lang/ko/errors.php

@@ -9,6 +9,7 @@ return [
         'china' => '중국 IP 또는 프록시 접근이 감지되었습니다. 접근이 거부되었습니다.',
         'oversea' => '해외 IP 또는 프록시 접근이 감지되었습니다. 접근이 거부되었습니다.',
         'unknown' => '알 수 없는 금지 액세스 모드입니다! 시스템 설정에서 [접근 제한 모드]를 수정하십시오!',
+        'redirect' => '(:ip :url) 구독 링크를 통해 접근이 감지되어 강제 리디렉션 중입니다.',
     ],
     'log' => '로그',
     'refresh' => '새로 고침',

+ 1 - 0
resources/lang/vi/errors.php

@@ -9,6 +9,7 @@ return [
         'china' => 'Phát hiện truy cập từ IP hoặc proxy Trung Quốc, từ chối truy cập',
         'oversea' => 'Phát hiện truy cập từ IP hoặc proxy nước ngoài, từ chối truy cập',
         'unknown' => 'Chế độ truy cập bị cấm không xác định! Vui lòng sửa đổi [Chế độ cấm truy cập] trong cài đặt hệ thống!',
+        'redirect' => 'Phát hiện (:ip :url) truy cập thông qua liên kết đăng ký, buộc chuyển hướng.',
     ],
     'log' => 'Nhật ký',
     'refresh' => 'Làm mới',

+ 1 - 0
resources/lang/zh_CN/errors.php

@@ -9,6 +9,7 @@ return [
         'china' => '检测到中国IP或代理访问,禁止访问',
         'oversea' => '检测到海外IP或代理访问,禁止访问',
         'unknown' => '未知禁止访问模式!请在系统设置中修改【禁止访问模式】!',
+        'redirect' => '识别到(:ip :url)通过订阅链接访问,强制重定向',
     ],
     'log' => '日志',
     'refresh' => '刷新',