Skip to content
This repository has been archived by the owner on Nov 2, 2020. It is now read-only.

Commit

Permalink
perf(IpBan): Move ip ban list to runtime config
Browse files Browse the repository at this point in the history
1. Move ip ban list to runtime config
2. Revert getBanIpsList() to app()->site
3. Add function banIp($ip, $persistence = false, $commit = null), unbanIp($ip, $persistence = false)
  • Loading branch information
Rhilip committed Aug 15, 2019
1 parent 7895158 commit e0fb4f6
Show file tree
Hide file tree
Showing 3 changed files with 51 additions and 21 deletions.
52 changes: 49 additions & 3 deletions apps/components/Site.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,6 @@
use Rid\Base\Component;
use Rid\Utils\ClassValueCacheUtils;

use RuntimeException;

class Site extends Component
{
use ClassValueCacheUtils;
Expand Down Expand Up @@ -156,7 +154,7 @@ public static function ruleCanUsedCategory(): array

public function ruleQuality($quality): array
{
if (!in_array($quality, array_keys($this->getQualityTableList()))) throw new RuntimeException('Unregister quality : ' . $quality);
if (!in_array($quality, array_keys($this->getQualityTableList()))) throw new \RuntimeException('Unregister quality : ' . $quality);
if (false === $data = config('runtime.enabled_quality_' . $quality)) {
/** @noinspection SqlResolve */
$data = app()->pdo->createCommand("SELECT * FROM `quality_$quality` WHERE `id` > 0 AND `enabled` = 1 ORDER BY `sort_index`,`id`")->queryAll();
Expand Down Expand Up @@ -198,6 +196,54 @@ public function rulePinnedTags(): array
return $data;
}

public function getBanIpsList(): array
{
$ban_ips = config('runtime.ban_ips_list');
if ($ban_ips === false) {
$ban_ips = app()->pdo->createCommand('SELECT `ip` FROM `ban_ips`')->queryColumn() ?: [];
app()->config->set('runtime.ban_ips_list', $ban_ips, 'json');
}

return $ban_ips;
}

public function banIp($ip, $persistence = false, $commit = null)
{
// Get old ban_ips_list
$banips = $this->getBanIpsList();

// Add ip if not exist
if (in_array($ip, $banips)) return;

// Rewrite config
$banips[] = $ip;
app()->config->set('runtime.ban_ips_list', $banips, 'json');

if ($persistence === true) { // Save it in table `ban_ips`
$add_by = app()->auth->getCurUser() ? app()->auth->getCurUser()->getId() : 0; // 0 - system
$commit = $commit ?? ($add_by == 0 ? 'Banned By System automatically' : '');
app()->pdo->createCommand('INSERT INTO `ban_ips`(`ip`, `add_by`, `add_at`, `commit`) VALUES (:ip, :add_by, NOW(), :commit)')->bindParams([
'ip' => $ip, 'add_by' => $add_by, 'commit' => $commit
])->execute();
}
}

public function unbanIp($ip, $persistence = false)
{
// Get old ban_ips_list
$banips = $this->getBanIpsList();

// unban ip if exist
if (in_array($ip, $banips)) {
unset($banips[$ip]);
app()->config->set('runtime.ban_ips_list', $banips, 'json');

if ($persistence === true) { // delete it from table `ban_ips`
app()->pdo->createCommand('DELETE FROM `ban_ips` WHERE `ip` = :ip')->bindParams(['ip' => $ip])->execute();
}
}
}

public static function fetchUserCount(): int
{
return app()->pdo->createCommand('SELECT COUNT(`id`) FROM `users`')->queryScalar();
Expand Down
18 changes: 1 addition & 17 deletions apps/middleware/IpBanMiddleware.php
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ class IpBanMiddleware
public function handle($callable, \Closure $next)
{
$ip = app()->request->getClientIp();
$ip_ban_list = $this->getBanIpsList();
$ip_ban_list = app()->site->getBanIpsList();

if (count($ip_ban_list) > 0 && IpUtils::checkIp($ip, $ip_ban_list)) {
return app()->response->setStatusCode(403);
Expand All @@ -25,20 +25,4 @@ public function handle($callable, \Closure $next)
return $next();
}

private function getBanIpsList(): array
{
$timenow = time();
$ban_ips_check = config('runtime.ban_ips_list_check');
if ($ban_ips_check === false // Init to avoid Redis Cache not exist
|| $ban_ips_check > $timenow + 86400 // Keep Redis Cache For 1 days
) {
$ban_ips = app()->pdo->createCommand('SELECT `ip` FROM `ban_ips`')->queryColumn() ?: [];
app()->redis->sAdd('Site:ban_ips_list', ...$ban_ips);
app()->config->set('runtime.ban_ips_list_check', $timenow, 'int');
} else {
$ban_ips = app()->redis->sMembers('Site:ban_ips_list');
}

return $ban_ips;
}
}
2 changes: 1 addition & 1 deletion apps/models/form/Auth/UserLoginForm.php
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,7 @@ public function loginFail()
$user_ip = app()->request->getClientIp();
$test_attempts = app()->redis->hIncrBy('Site:fail_login_ip_count', $user_ip, 1);
if ($test_attempts >= config('security.max_login_attempts')) {
app()->redis->sAdd('Site:ban_ips_list', $user_ip);
app()->site->banIp($user_ip);
}
}

Expand Down

0 comments on commit e0fb4f6

Please sign in to comment.