You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
virt/web/app/Services/UserRestrictionEnforcementS...

301 lines
9.3 KiB
PHTML

<?php
namespace App\Services;
use App\Models\Configurations;
use App\Models\EmailVerify;
use App\Models\User;
class UserRestrictionEnforcementService
{
private const EMAIL_BLACKLIST_KEY = 'email_blacklist';
private const TRUSTED_LOGIN_DEVICE_PREFIX = 'trusted_login_device:';
public static function enforceUsers($users, ?RedisClient $redis = null)
{
$emails = [];
$userIds = [];
foreach ($users as $user) {
if (!$user instanceof User || (bool) $user->is_admin) {
continue;
}
$userId = (int) $user->id;
$email = strtolower(trim((string) $user->email));
if ($userId > 0) {
$userIds[$userId] = $userId;
}
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emails[$email] = $email;
}
}
if (empty($userIds) && empty($emails)) {
return self::emptyResult(false);
}
$result = self::emptyResult(true);
try {
$result['emails_added'] = self::appendEmailsToBlacklist(array_values($emails));
if (!empty($emails)) {
EmailVerify::whereIn('email', array_values($emails))->delete();
}
} catch (\Throwable $exception) {
$result['database_error'] = true;
error_log('User restriction email blacklist update failed: ' . $exception->getMessage());
}
try {
if ($redis === null) {
$redis = new RedisClient();
}
$redis->del(self::EMAIL_BLACKLIST_KEY);
$result['trusted_devices_cleared'] = self::clearTrustedLoginDevices(array_values($userIds), $redis);
} catch (\Throwable $exception) {
$result['redis_error'] = true;
error_log('User restriction trusted device cleanup failed: ' . $exception->getMessage());
}
return $result;
}
public static function releaseUsers($users, ?RedisClient $redis = null)
{
$emails = [];
foreach ($users as $user) {
if (!$user instanceof User || (bool) $user->is_admin) {
continue;
}
$email = strtolower(trim((string) $user->email));
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
$emails[$email] = $email;
}
}
if (empty($emails)) {
return self::emptyResult(false);
}
$result = self::emptyResult(false);
try {
$result['emails_removed'] = self::deleteEmailsFromBlacklist(array_values($emails));
} catch (\Throwable $exception) {
$result['database_error'] = true;
error_log('User restriction email blacklist release failed: ' . $exception->getMessage());
}
try {
if ($redis === null) {
$redis = new RedisClient();
}
$redis->del(self::EMAIL_BLACKLIST_KEY);
} catch (\Throwable $exception) {
$result['redis_error'] = true;
error_log('User restriction email blacklist cache cleanup failed: ' . $exception->getMessage());
}
return $result;
}
public static function mergeEmailBlacklist($raw, array $emails)
{
$existing = [];
foreach (preg_split('/\r\n|\r|\n|,|;/', (string) $raw) as $line) {
$rule = strtolower(trim((string) $line));
if (strpos($rule, '#') !== false) {
$rule = trim(explode('#', $rule, 2)[0]);
}
if (filter_var($rule, FILTER_VALIDATE_EMAIL)) {
$existing[$rule] = true;
}
}
$added = [];
foreach ($emails as $email) {
$email = strtolower(trim((string) $email));
if (!filter_var($email, FILTER_VALIDATE_EMAIL) || isset($existing[$email])) {
continue;
}
$existing[$email] = true;
$added[] = $email;
}
if (empty($added)) {
return ['value' => (string) $raw, 'added' => []];
}
$value = rtrim((string) $raw);
if ($value !== '') {
$value .= "\n";
}
$value .= implode("\n", $added);
return ['value' => $value, 'added' => $added];
}
public static function removeEmailsFromBlacklist($raw, array $emails)
{
$targets = [];
foreach ($emails as $email) {
$email = strtolower(trim((string) $email));
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
$targets[$email] = true;
}
}
if (empty($targets)) {
return ['value' => (string) $raw, 'removed' => []];
}
$kept = [];
$removed = [];
foreach (preg_split('/\r\n|\r|\n|,|;/', (string) $raw) as $entry) {
$entry = trim((string) $entry);
if ($entry === '') {
continue;
}
$rule = strtolower($entry);
if (strpos($rule, '#') !== false) {
$rule = trim(explode('#', $rule, 2)[0]);
}
if (filter_var($rule, FILTER_VALIDATE_EMAIL) && isset($targets[$rule])) {
$removed[$rule] = $rule;
continue;
}
$kept[] = $entry;
}
if (empty($removed)) {
return ['value' => (string) $raw, 'removed' => []];
}
return [
'value' => implode("\n", $kept),
'removed' => array_values($removed),
];
}
private static function appendEmailsToBlacklist(array $emails)
{
if (empty($emails)) {
return 0;
}
$connection = (new Configurations())->getConnection();
return $connection->transaction(function () use ($emails) {
$configuration = Configurations::where('name', self::EMAIL_BLACKLIST_KEY)
->lockForUpdate()
->first();
if ($configuration === null) {
$configuration = new Configurations();
$configuration->name = self::EMAIL_BLACKLIST_KEY;
$configuration->value = '';
}
$merged = self::mergeEmailBlacklist((string) $configuration->value, $emails);
if (empty($merged['added'])) {
return 0;
}
$configuration->value = $merged['value'];
$configuration->save();
return count($merged['added']);
});
}
private static function deleteEmailsFromBlacklist(array $emails)
{
if (empty($emails)) {
return 0;
}
$connection = (new Configurations())->getConnection();
return $connection->transaction(function () use ($emails) {
$configuration = Configurations::where('name', self::EMAIL_BLACKLIST_KEY)
->lockForUpdate()
->first();
if ($configuration === null) {
return 0;
}
$filtered = self::removeEmailsFromBlacklist((string) $configuration->value, $emails);
if (empty($filtered['removed'])) {
return 0;
}
$configuration->value = $filtered['value'];
$configuration->save();
return count($filtered['removed']);
});
}
private static function clearTrustedLoginDevices(array $userIds, RedisClient $redis)
{
if (empty($userIds)) {
return 0;
}
$wanted = array_fill_keys(array_map('intval', $userIds), true);
$client = $redis->getClient();
$keys = [];
try {
$cursor = '0';
do {
$result = $client->executeRaw([
'SCAN',
$cursor,
'MATCH',
self::TRUSTED_LOGIN_DEVICE_PREFIX . '*',
'COUNT',
'500',
]);
if (!is_array($result) || count($result) < 2) {
break;
}
$cursor = (string) $result[0];
$batch = is_array($result[1]) ? $result[1] : [];
foreach ($batch as $key) {
if (preg_match('/^trusted_login_device:(\d+):/', (string) $key, $matches)
&& isset($wanted[(int) $matches[1]])) {
$keys[(string) $key] = (string) $key;
}
}
} while ($cursor !== '0');
} catch (\Throwable $exception) {
foreach ($userIds as $userId) {
try {
foreach ((array) $client->keys(self::TRUSTED_LOGIN_DEVICE_PREFIX . (int) $userId . ':*') as $key) {
$keys[(string) $key] = (string) $key;
}
} catch (\Throwable $innerException) {
continue;
}
}
}
foreach ($keys as $key) {
$redis->del($key);
}
return count($keys);
}
private static function emptyResult($enforced)
{
return [
'enforced' => (bool) $enforced,
'emails_added' => 0,
'emails_removed' => 0,
'trusted_devices_cleared' => 0,
'database_error' => false,
'redis_error' => false,
];
}
}