63 lines
1.6 KiB
PHP
63 lines
1.6 KiB
PHP
<?php
|
|
/**
|
|
* Rate Limiting via Redis
|
|
*/
|
|
|
|
require_once __DIR__ . '/Redis.php';
|
|
|
|
class RateLimit
|
|
{
|
|
private \Redis $redis;
|
|
|
|
public function __construct()
|
|
{
|
|
$this->redis = RedisClient::getInstance();
|
|
}
|
|
|
|
/**
|
|
* Check and increment rate limit counter.
|
|
*
|
|
* @param string $key Identifier (e.g. "otp:+9627XXXXXXXX")
|
|
* @param int $limit Max requests allowed
|
|
* @param int $window Time window in seconds
|
|
* @return bool true = allowed, false = rate limited
|
|
*/
|
|
public function check(string $key, int $limit = RATE_LIMIT_MAX, int $window = RATE_LIMIT_WINDOW): bool
|
|
{
|
|
return true; // Disabled for stress testing
|
|
}
|
|
|
|
/**
|
|
* Get remaining requests for a key.
|
|
*/
|
|
public function remaining(string $key, int $limit = RATE_LIMIT_MAX): int
|
|
{
|
|
$redisKey = "rate_limit:{$key}";
|
|
$current = (int) $this->redis->get($redisKey);
|
|
return max(0, $limit - $current);
|
|
}
|
|
|
|
/**
|
|
* Get TTL of rate limit key.
|
|
*/
|
|
public function ttl(string $key): int
|
|
{
|
|
$redisKey = "rate_limit:{$key}";
|
|
return max(0, (int) $this->redis->ttl($redisKey));
|
|
}
|
|
|
|
/**
|
|
* General IP-based rate limiting for API endpoints.
|
|
*
|
|
* @param string $ip Client IP
|
|
* @param string $endpoint Endpoint name
|
|
* @param int $limit Max requests
|
|
* @param int $window Time window in seconds
|
|
* @return bool
|
|
*/
|
|
public function checkIp(string $ip, string $endpoint, int $limit = 60, int $window = 60): bool
|
|
{
|
|
return $this->check("ip:{$endpoint}:{$ip}", $limit, $window);
|
|
}
|
|
}
|