| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859 |
- <?php
- namespace common\libs;
- use Yii;
- use yii\base\Component;
- use yii\web\BadRequestHttpException;
- use yii\web\Application;
- use MaxMind\Db\Reader;
- use MaxMind\Db\InvalidDatabaseException;
- use MaxMind\Db\AddressNotFoundException;
- class IpFilter
- {
- /**
- * @throws BadRequestHttpException
- */
- public function frontApiCheck()
- {
- $request = Yii::$app->request;
- $getParams = Yii::$app->request->get();
- $postParams = Yii::$app->request->post();
- $remoteAddr = $_SERVER['REMOTE_ADDR']; // 获取用户 IP 地址
- // 登录接口不需要验证
- if (!self::remoteAddrCall($remoteAddr)) {
- Yii::warning('GET 参数: ' . json_encode(is_array($getParams) ? $getParams : [], JSON_PRETTY_PRINT), __METHOD__);
- Yii::warning('POST 参数: ' . json_encode(is_array($postParams) ? $getParams : [], JSON_PRETTY_PRINT), __METHOD__);
- throw new \Exception('用户名或者密码错误');
- }
- return true;
- }
- /**
- * @throws AddressNotFoundException
- * @throws InvalidDatabaseException
- */
- public static function remoteAddrCall($remoteAddr): bool
- {
- // 是否有效的IP
- if (!filter_var($remoteAddr, FILTER_VALIDATE_IP)) {
- return false;
- }
- // 替换为 GeoLite2 数据库文件的实际路径
- $dbPath = \Yii::getAlias('@common/runtime/geoLite//GeoLite2-Country.mmdb');
- // 初始化 MaxMind 数据库读取器
- $reader = new \GeoIp2\Database\Reader($dbPath);
- // 查询 IP 地址的地理位置
- $record = $reader->country($remoteAddr);
- // 返回国家名称
- $countryName = $record->country->name;
- if (!in_array($countryName, ['China'])) {
- return false;
- }
- return true;
- }
- }
|