Forbidden.php 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. <?php
  2. namespace App\Http\Middleware;
  3. use App\Components\QQWry;
  4. use App\Http\Models\Config;
  5. use Response;
  6. use Agent;
  7. use Log;
  8. use Closure;
  9. class Forbidden
  10. {
  11. /**
  12. * Handle an incoming request.
  13. *
  14. * @param \Illuminate\Http\Request $request
  15. * @param \Closure $next
  16. *
  17. * @return mixed
  18. */
  19. public function handle($request, Closure $next)
  20. {
  21. // 拒绝机器人访问
  22. $config = Config::query()->where('name', 'is_forbid_robot')->first();
  23. if ($config && $config->value) {
  24. if (Agent::isRobot()) {
  25. Log::info("识别到机器人访问(" . getClientIp() . ")");
  26. return Response::view('403', [], 403);
  27. }
  28. }
  29. // 拒绝受限IP访问
  30. $isIPv6 = false;
  31. $ip = getClientIP();
  32. $qqwry = new QQWry();
  33. $ipInfo = $qqwry->ip($ip);
  34. if (isset($ipInfo['error'])) {
  35. $isIPv6 = true;
  36. Log::info('无法识别IP,可能是IPv6,尝试解析:' . $ip);
  37. $ipInfo = getIPv6($ip);
  38. }
  39. if (empty($ipInfo) || empty($ipInfo['country'])) {
  40. return $next($request);
  41. }
  42. if ($ipInfo['country'] != '本机地址' && $ipInfo['country'] != '局域网') {
  43. $forbidChina = Config::query()->where('name', 'is_forbid_china')->first();
  44. if ($forbidChina && $forbidChina->value && ($ipInfo['country'] == '中国' || ($isIPv6 && $ipInfo['country'] == 'China'))) {
  45. Log::info('识别到大陆IP,拒绝访问:' . $ip);
  46. return Response::view('403', [], 403);
  47. }
  48. $forbidOversea = Config::query()->where('name', 'is_forbid_oversea')->first();
  49. if ($forbidOversea && $forbidOversea->value && ($ipInfo['country'] != '中国' || ($isIPv6 && $ipInfo['country'] != 'China'))) {
  50. Log::info('识别到海外IP,拒绝访问:' . $ip . ' - ' . $ipInfo['country']);
  51. return Response::view('403', [], 403);
  52. }
  53. }
  54. return $next($request);
  55. }
  56. }