2019-05-09 18:54:39 +12:00
|
|
|
<?php
|
2019-10-01 17:57:41 +13:00
|
|
|
|
2020-06-29 05:31:21 +12:00
|
|
|
use Utopia\App;
|
2019-11-30 07:23:29 +13:00
|
|
|
use Utopia\Exception;
|
|
|
|
use Utopia\Abuse\Abuse;
|
|
|
|
use Utopia\Abuse\Adapters\TimeLimit;
|
|
|
|
|
2020-07-03 05:37:24 +12:00
|
|
|
App::init(function ($utopia, $request, $response, $project, $user, $register) {
|
|
|
|
/** @var Utopia\App $utopia */
|
|
|
|
/** @var Utopia\Request $request */
|
2020-08-06 18:51:49 +12:00
|
|
|
/** @var Appwrite\Utopia\Response $response */
|
2020-07-03 05:37:24 +12:00
|
|
|
/** @var Appwrite\Database\Document $project */
|
|
|
|
/** @var Appwrite\Database\Document $user */
|
|
|
|
/** @var Utopia\Registry\Registry $register */
|
|
|
|
|
2019-11-30 07:23:29 +13:00
|
|
|
$route = $utopia->match($request);
|
|
|
|
|
2020-06-25 08:59:04 +12:00
|
|
|
if (empty($project->getId()) && $route->getLabel('abuse-limit', 0) > 0) { // Abuse limit requires an active project scope
|
2020-06-18 08:08:55 +12:00
|
|
|
throw new Exception('Missing or unknown project ID', 400);
|
|
|
|
}
|
|
|
|
|
2019-11-30 07:23:29 +13:00
|
|
|
/*
|
|
|
|
* Abuse Check
|
|
|
|
*/
|
|
|
|
$timeLimit = new TimeLimit($route->getLabel('abuse-key', 'url:{url},ip:{ip}'), $route->getLabel('abuse-limit', 0), $route->getLabel('abuse-time', 3600), function () use ($register) {
|
|
|
|
return $register->get('db');
|
|
|
|
});
|
2020-02-17 20:16:11 +13:00
|
|
|
$timeLimit->setNamespace('app_'.$project->getId());
|
2019-11-30 07:23:29 +13:00
|
|
|
$timeLimit
|
2020-02-17 20:16:11 +13:00
|
|
|
->setParam('{userId}', $user->getId())
|
2020-07-04 03:14:51 +12:00
|
|
|
->setParam('{userAgent}', $request->getUserAgent(''))
|
2019-11-30 07:23:29 +13:00
|
|
|
->setParam('{ip}', $request->getIP())
|
2020-07-03 05:37:24 +12:00
|
|
|
->setParam('{url}', $request->getHostname().$route->getURL())
|
2019-11-30 07:23:29 +13:00
|
|
|
;
|
|
|
|
|
|
|
|
//TODO make sure we get array here
|
|
|
|
|
|
|
|
foreach ($request->getParams() as $key => $value) { // Set request params as potential abuse keys
|
2020-06-20 23:20:49 +12:00
|
|
|
$timeLimit->setParam('{param-'.$key.'}', (\is_array($value)) ? \json_encode($value) : $value);
|
2019-11-30 07:23:29 +13:00
|
|
|
}
|
|
|
|
|
|
|
|
$abuse = new Abuse($timeLimit);
|
|
|
|
|
|
|
|
if ($timeLimit->limit()) {
|
|
|
|
$response
|
|
|
|
->addHeader('X-RateLimit-Limit', $timeLimit->limit())
|
|
|
|
->addHeader('X-RateLimit-Remaining', $timeLimit->remaining())
|
|
|
|
->addHeader('X-RateLimit-Reset', $timeLimit->time() + $route->getLabel('abuse-time', 3600))
|
|
|
|
;
|
|
|
|
}
|
|
|
|
|
2020-06-29 07:28:18 +12:00
|
|
|
if ($abuse->check() && App::getEnv('_APP_OPTIONS_ABUSE', 'enabled') !== 'disabled') {
|
2019-11-30 07:23:29 +13:00
|
|
|
throw new Exception('Too many requests', 429);
|
|
|
|
}
|
2020-07-03 05:37:24 +12:00
|
|
|
}, ['utopia', 'request', 'response', 'project', 'user', 'register'], 'api');
|