isForbidden.php 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. <?php
  2. namespace App\Http\Middleware;
  3. use Agent;
  4. use App\Components\IP;
  5. use Closure;
  6. use Illuminate\Http\Request;
  7. use Log;
  8. use Response;
  9. class isForbidden
  10. {
  11. /**
  12. * 限制机器人、指定IP访问
  13. *
  14. * @param Request $request
  15. * @param Closure $next
  16. *
  17. * @return mixed
  18. */
  19. public function handle(Request $request, Closure $next)
  20. {
  21. // 拒绝机器人访问
  22. if (sysConfig('is_forbid_robot') && Agent::isRobot()) {
  23. Log::info("识别到机器人访问(" . IP::getClientIp() . ")");
  24. return Response::view(
  25. 'auth.error',
  26. ['message' => trans('error.ForbiddenRobot')],
  27. 403
  28. );
  29. }
  30. // 拒绝通过订阅链接域名访问网站,防止网站被探测
  31. if (false !== strpos(sysConfig('subscribe_domain'), $request->getHost())
  32. && ! str_contains(
  33. sysConfig('subscribe_domain'),
  34. sysConfig('website_url')
  35. )) {
  36. Log::info("识别到通过订阅链接访问,强制跳转至百度(" . IP::getClientIp() . ")");
  37. return redirect('https://www.baidu.com');
  38. }
  39. $ip = IP::getClientIP();
  40. $ipLocation = IP::getIPInfo($ip);
  41. // 拒绝无IP请求
  42. if ( ! $ipLocation || empty(array_filter($ipLocation))) {
  43. return Response::view(
  44. 'auth.error',
  45. ['message' => trans('error.ForbiddenAccess')],
  46. 403
  47. );
  48. }
  49. if ( ! in_array($ipLocation['country'], ['本机地址', '局域网'])) {
  50. // 拒绝大陆IP访问
  51. if (sysConfig('is_forbid_china') &&
  52. in_array($ipLocation['country'], ['China', '中国']) &&
  53. ! in_array(
  54. $ipLocation['province'],
  55. ['香港', '澳门', '台湾', '台湾省']
  56. )) {
  57. Log::info('识别到大陆IP,拒绝访问:' . $ip);
  58. return Response::view(
  59. 'auth.error',
  60. [
  61. 'message' => trans(
  62. 'error.ForbiddenChina'
  63. ),
  64. ],
  65. 403
  66. );
  67. }
  68. // 拒绝非大陆IP访问
  69. if (sysConfig('is_forbid_oversea')
  70. && ! in_array(
  71. $ipLocation['country'],
  72. ['China', '中国', 'Taiwan', 'Hong Kong', 'Macao']
  73. )) {
  74. Log::info(
  75. '识别到海外IP,拒绝访问:' . $ip . ' - ' . $ipLocation['country']
  76. );
  77. return Response::view(
  78. 'auth.error',
  79. [
  80. 'message' => trans(
  81. 'error.ForbiddenOversea'
  82. ),
  83. ],
  84. 403
  85. );
  86. }
  87. }
  88. return $next($request);
  89. }
  90. }