IpFilter.php 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. <?php
  2. namespace common\libs;
  3. use Yii;
  4. use yii\base\Component;
  5. use yii\web\BadRequestHttpException;
  6. use yii\web\Application;
  7. use MaxMind\Db\Reader;
  8. use MaxMind\Db\InvalidDatabaseException;
  9. use MaxMind\Db\AddressNotFoundException;
  10. use common\helpers\LoggerTool;
  11. class IpFilter
  12. {
  13. /**
  14. * @throws BadRequestHttpException
  15. */
  16. public function frontApiCheck($isLogin = false)
  17. {
  18. $request = Yii::$app->request;
  19. $getParams = Yii::$app->request->get();
  20. $postParams = Yii::$app->request->post();
  21. $remoteAddr = $_SERVER['REMOTE_ADDR']; // 获取用户 IP 地址
  22. // 登录接口不需要验证
  23. if (!self::remoteAddrCall($remoteAddr)) {
  24. $logPreix = $isLogin ? 'nc_ip_filter_login' : 'nc_ip_filter_other';
  25. $getLog = $logPreix . (is_array($getParams) ? json_encode($getParams) : $getParams);
  26. $postLog = $logPreix . (is_array($postParams) ? json_encode($postParams) : $postParams);
  27. LoggerTool::error($getLog);
  28. LoggerTool::error($postLog);
  29. throw new \Exception('用户名或者密码错误');
  30. }
  31. return true;
  32. }
  33. /**
  34. * @throws AddressNotFoundException
  35. * @throws InvalidDatabaseException
  36. */
  37. public static function remoteAddrCall($remoteAddr): bool
  38. {
  39. // 是否有效的IP
  40. if (!filter_var($remoteAddr, FILTER_VALIDATE_IP)) {
  41. return false;
  42. }
  43. // 替换为 GeoLite2 数据库文件的实际路径
  44. $dbPath = \Yii::getAlias('@common/runtime/geoLite//GeoLite2-Country.mmdb');
  45. // 初始化 MaxMind 数据库读取器
  46. $reader = new \GeoIp2\Database\Reader($dbPath);
  47. // 查询 IP 地址的地理位置
  48. $record = $reader->country($remoteAddr);
  49. // 返回国家名称
  50. $countryName = $record->country->name;
  51. if (!in_array($countryName, ['China'])) {
  52. return false;
  53. }
  54. return true;
  55. }
  56. }