isForbidden.php 3.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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('auth.error', ['message' => trans('error.forbidden.bots')], 403);
  25. }
  26. // 拒绝通过订阅链接域名访问网站,防止网站被探测
  27. if (false !== strpos(sysConfig('subscribe_domain'), $request->getHost())
  28. && ! str_contains(sysConfig('subscribe_domain'), sysConfig('website_url'))) {
  29. Log::info('识别到通过订阅链接访问,强制跳转至百度('.IP::getClientIp().')');
  30. return redirect('https://www.baidu.com');
  31. }
  32. $ip = IP::getClientIP();
  33. $ipLocation = IP::getIPInfo($ip);
  34. // 拒绝无IP请求
  35. if (! $ipLocation || empty(array_filter($ipLocation))) {
  36. return Response::view('auth.error', ['message' => trans('error.forbidden.access')], 403);
  37. }
  38. if (! in_array($ipLocation['country'], ['本机地址', '局域网']) && sysConfig('forbid_mode')) {
  39. // 拒绝大陆IP访问
  40. switch (sysConfig('forbid_mode')) {
  41. case 'ban_mainland':
  42. if (in_array($ipLocation['country'], ['China', '中国']) && ! in_array($ipLocation['province'], ['香港', '澳门', '台湾', '台湾省'])) {
  43. Log::info('识别到大陆IP,拒绝访问:'.$ip);
  44. return Response::view('auth.error', ['message' => trans('error.forbidden.china')], 403);
  45. }
  46. break;
  47. case 'ban_china':
  48. if (in_array($ipLocation['country'], ['China', '中国', 'Taiwan', 'Hong Kong', 'Macao'])) {
  49. Log::info('识别到中国IP,拒绝访问:'.$ip);
  50. return Response::view('auth.error', ['message' => trans('error.forbidden.china')], 403);
  51. }
  52. break;
  53. case 'ban_oversea':
  54. if (! in_array($ipLocation['country'], ['China', '中国', 'Taiwan', 'Hong Kong', 'Macao'])) {
  55. Log::info('识别到海外IP,拒绝访问:'.$ip.' - '.$ipLocation['country']);
  56. return Response::view('auth.error', ['message' => trans('error.forbidden.oversea')], 403);
  57. }
  58. break;
  59. default:
  60. Log::warning('未知禁止访问模式!请在系统设置中修改【禁止访问模式】!');
  61. break;
  62. }
  63. }
  64. return $next($request);
  65. }
  66. }