Utopia framework abuse library is simple and lite library for managing application usage limits. This library is aiming to be as simple and easy to learn and use. This library is maintained by the Appwrite team.
Although this library is part of the Utopia Framework project it is dependency free, and can be used as standalone with any other PHP project or framework.
Install using composer:
composer require utopia-php/abuse
Time Limit Abuse
The time limit abuse allow each key (action) to be performed [X] times in given time frame. This adapter uses a MySQL / MariaDB to store usage attempts. Before using it create the table schema as documented in this repository (./data/schema.sql)
<?php
require_once __DIR__ . '/../../vendor/autoload.php';
use Utopia\Abuse\Abuse;
use Utopia\Abuse\Adapters\TimeLimit;
use Utopia\Cache\Adapter\None as NoCache;
use Utopia\Cache\Cache;
use Utopia\Database\Adapter\MySQL;
use Utopia\Database\Database;
$dbHost = '127.0.0.1';
$dbUser = 'travis';
$dbPass = '';
$pdo = new PDO("mysql:host={$dbHost};", $dbUser, $dbPass, array(
PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES utf8',
PDO::ATTR_TIMEOUT => 5, // Seconds
));
// Connection settings
$pdo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC); // Return arrays
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db = new Database(new MySQL($pdo), new Cache(new NoCache()));
$db->setNamespace('namespace');
// Limit login attempts to 10 time in 5 minutes time frame
$adapter = new TimeLimit('login-attempt-from-{{ip}}', 10, (60 * 5), $db);
$adapter->setup(); //setup database as required
$adapter->setParam('{{ip}}', '127.0.0.1')
;
$abuse = new Abuse($adapter);
// Use vars to resolve adapter key
if(!$abuse->check()) {
throw new Exception('Service was abused!'); // throw error and return X-Rate limit headers here
}
ReCaptcha Abuse
The ReCaptcha abuse controller is using Google ReCaptcha service to detect when service is being abused by bots. To use this adapter you need to create an API key from the Google ReCaptcha service admin console.
<?php
require_once __DIR__ . '/../../vendor/autoload.php';
use Utopia\Abuse\Abuse;
use Utopia\Abuse\Adapters\ReCaptcha;
// Limit login attempts to 10 time in 5 minutes time frame
$adapter = new ReCaptcha('secret-api-key', $_POST['g-recaptcha-response'], $_SERVER['REMOTE_ADDR']);
$abuse = new Abuse($adapter);
if(!$abuse->check()) {
throw new Exception('Service was abused!'); // throw error and return X-Rate limit headers here
}
Notice: The code above is for example purpose only. It is always recommended to validate user input before using it in your code. If you are using a load balancer or any proxy server you might need to get user IP from the HTTP_X_FORWARDED_FOR header.
Utopia Framework requires PHP 7.4 or later. We recommend using the latest PHP version whenever possible.
Eldad Fux
The MIT License (MIT) http://www.opensource.org/licenses/mit-license.php