IpFilter.php 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  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()
  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. LoggerTool::warning(is_array($getParams) ? $getParams : []);
  25. LoggerTool::warning(is_array($postParams) ? $getParams : []);
  26. throw new \Exception('用户名或者密码错误');
  27. }
  28. return true;
  29. }
  30. /**
  31. * @throws AddressNotFoundException
  32. * @throws InvalidDatabaseException
  33. */
  34. public static function remoteAddrCall($remoteAddr): bool
  35. {
  36. // 是否有效的IP
  37. if (!filter_var($remoteAddr, FILTER_VALIDATE_IP)) {
  38. return false;
  39. }
  40. // 替换为 GeoLite2 数据库文件的实际路径
  41. $dbPath = \Yii::getAlias('@common/runtime/geoLite//GeoLite2-Country.mmdb');
  42. // 初始化 MaxMind 数据库读取器
  43. $reader = new \GeoIp2\Database\Reader($dbPath);
  44. // 查询 IP 地址的地理位置
  45. $record = $reader->country($remoteAddr);
  46. // 返回国家名称
  47. $countryName = $record->country->name;
  48. if (!in_array($countryName, ['China'])) {
  49. return false;
  50. }
  51. return true;
  52. }
  53. }