Forbidden.php 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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. $ip = getClientIP();
  31. $qqwry = new QQWry();
  32. $ipInfo = $qqwry->ip($ip);
  33. if (isset($ipInfo['error'])) {
  34. Log::info('无法识别IP,可能是IPv6,尝试解析:' . $ip);
  35. $ipInfo = getIPv6($ip);
  36. }
  37. if (empty($ipInfo) || empty($ipInfo['country'])) {
  38. return $next($request);
  39. }
  40. if ($ipInfo['country'] != '本机地址' && $ipInfo['country'] != '局域网') {
  41. $forbidChina = Config::query()->where('name', 'is_forbid_china')->first();
  42. if ($forbidChina && $forbidChina->value && ($ipInfo['country'] == '中国' || $ipInfo['country'] == 'China')) {
  43. Log::info('识别到大陆IP,拒绝访问:' . $ip);
  44. return Response::view('403', [], 403);
  45. }
  46. $forbidOversea = Config::query()->where('name', 'is_forbid_oversea')->first();
  47. if ($forbidOversea && $forbidOversea->value && ($ipInfo['country'] != '中国' || $ipInfo['country'] != 'China')) {
  48. Log::info('识别到海外IP,拒绝访问:' . $ip . ' - ' . $ipInfo['country']);
  49. return Response::view('403', [], 403);
  50. }
  51. }
  52. return $next($request);
  53. }
  54. }