/
v.bolshakov
/
AIEcosystem-Testing
Обзор
Документация
Войти
/
v.bolshakov
/
AIEcosystem-Testing
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
dev
api/components/ApiKeyFilter.php
60 строк
2 KB
Developer
Initial commit
03 авг 2026, 17:43
03 авг 2026, 17:43
7433917
Код
Авторство
О чём код?
<?php namespace api\components; use common\kdf\KApiKey; use common\models\ApiWhiteListIp; use Yii; use yii\base\ActionFilter; use yii\web\BadRequestHttpException; use yii\web\NotFoundHttpException; /** * Проверка доступа по IP к разным api-key * * @author Dmitry E. Semenov <sde.tomsk@gmail.com> * @copyright Self (c) 2019 */ class ApiKeyFilter extends ActionFilter { /** * {@inheritdoc} */ public function beforeAction($action) { $apiKey = Yii::$app->request->getHeaders()->get('apiKey'); if (!$apiKey) { $apiKey = Yii::$app->request->get('apiKey'); } if (!$apiKey) { throw new BadRequestHttpException(Yii::t('app', 'Your request was made without valid «apiKey»')); } /** @var KApiKey $api */ $api = KApiKey::find() ->andWhere(['api_key' => $apiKey]) ->one(); if (!$api) { throw new NotFoundHttpException(Yii::t('app', 'Your apiKey «{0}» not found', [$apiKey])); } $ip = Yii::$app->request->userIP; $is_allow = ApiWhiteListIp::find() ->andWhere([ 'api_key_id' => $api->id, 'ip2long' => ip2long($ip) ]) ->count() > 0; if (!$is_allow) { // throw new ForbiddenHttpException(Yii::t('app', 'Access from remote ip «{0}» forbidden', [$ip])); } Yii::$app->set('api', $api); return true; } }