IpFilter.php 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  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. class IpFilter
  11. {
  12. /**
  13. * @throws BadRequestHttpException
  14. */
  15. public function frontApiCheck()
  16. {
  17. $request = Yii::$app->request;
  18. $getParams = Yii::$app->request->get();
  19. $postParams = Yii::$app->request->post();
  20. $remoteAddr = $_SERVER['REMOTE_ADDR']; // 获取用户 IP 地址
  21. // 登录接口不需要验证
  22. if (!self::remoteAddrCall($remoteAddr)) {
  23. Yii::warning('GET 参数: ' . json_encode(is_array($getParams) ? $getParams : [], JSON_PRETTY_PRINT), __METHOD__);
  24. Yii::warning('POST 参数: ' . json_encode(is_array($postParams) ? $getParams : [], JSON_PRETTY_PRINT), __METHOD__);
  25. throw new \Exception('用户名或者密码错误');
  26. }
  27. return true;
  28. }
  29. /**
  30. * @throws AddressNotFoundException
  31. * @throws InvalidDatabaseException
  32. */
  33. public static function remoteAddrCall($remoteAddr): bool
  34. {
  35. // 是否有效的IP
  36. if (!filter_var($remoteAddr, FILTER_VALIDATE_IP)) {
  37. return false;
  38. }
  39. // 替换为 GeoLite2 数据库文件的实际路径
  40. $dbPath = \Yii::getAlias('@common/runtime/geoLite//GeoLite2-Country.mmdb');
  41. // 初始化 MaxMind 数据库读取器
  42. $reader = new \GeoIp2\Database\Reader($dbPath);
  43. // 查询 IP 地址的地理位置
  44. $record = $reader->country($remoteAddr);
  45. // 返回国家名称
  46. $countryName = $record->country->name;
  47. if (!in_array($countryName, ['China'])) {
  48. return false;
  49. }
  50. return true;
  51. }
  52. }