isForbidden.php 3.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. <?php
  2. namespace App\Http\Middleware;
  3. use Agent;
  4. use App\Utils\IP;
  5. use Closure;
  6. use Illuminate\Http\Request;
  7. use Log;
  8. use Response;
  9. class isForbidden
  10. {
  11. /**
  12. * 限制机器人、指定IP访问.
  13. *
  14. * @return mixed
  15. */
  16. public function handle(Request $request, Closure $next)
  17. { // 限制机器人、指定IP访问.
  18. // 拒绝机器人访问
  19. if (sysConfig('is_forbid_robot') && Agent::isRobot()) {
  20. Log::warning('识别到机器人('.IP::getClientIp().')访问');
  21. return Response::view('auth.error', ['message' => trans('errors.forbidden.bots')], 403);
  22. }
  23. // 拒绝通过订阅链接域名访问网站,防止网站被探测
  24. if (config('app.env') === 'production' && sysConfig('website_url') && ! str_contains(sysConfig('website_url'), $request->getHost())) {
  25. Log::warning('识别到通过订阅链接访问,强制跳转至百度('.IP::getClientIp().')');
  26. return redirect('https://www.baidu.com');
  27. }
  28. $ip = IP::getClientIP();
  29. $ipLocation = IP::getIPInfo($ip);
  30. if ($ipLocation !== false) {
  31. // 拒绝无IP请求
  32. if (empty($ipLocation) || empty(array_filter($ipLocation))) {
  33. return Response::view('auth.error', ['message' => trans('errors.forbidden.access')], 403);
  34. }
  35. if (! in_array($ipLocation['country'], ['本机地址', '局域网']) && sysConfig('forbid_mode')) {
  36. // 拒绝大陆IP访问
  37. switch (sysConfig('forbid_mode')) {
  38. case 'ban_mainland':
  39. if (in_array($ipLocation['country'], ['China', '中国', 'CN']) && ! in_array($ipLocation['region'], ['香港', '澳门', '台湾', '台湾省'])) {
  40. Log::warning('识别到大陆IP,拒绝访问:'.$ip);
  41. return Response::view('auth.error', ['message' => trans('errors.forbidden.china')], 403);
  42. }
  43. break;
  44. case 'ban_china':
  45. if (in_array($ipLocation['country'], ['China', '中国', 'Taiwan', 'Hong Kong', 'Macao'])) {
  46. Log::warning('识别到中国IP,拒绝访问:'.$ip);
  47. return Response::view('auth.error', ['message' => trans('errors.forbidden.china')], 403);
  48. }
  49. break;
  50. case 'ban_oversea':
  51. if (! in_array($ipLocation['country'], ['China', '中国', 'Taiwan', 'Hong Kong', 'Macao'])) {
  52. Log::warning('识别到海外IP,拒绝访问:'.$ip.' - '.$ipLocation['country']);
  53. return Response::view('auth.error', ['message' => trans('errors.forbidden.oversea')], 403);
  54. }
  55. break;
  56. default:
  57. Log::emergency('未知禁止访问模式!请在系统设置中修改【禁止访问模式】!');
  58. break;
  59. }
  60. }
  61. }
  62. return $next($request);
  63. }
  64. }