Remove user feature restrictions

go
codex 4 weeks ago
parent bc5d7ce263
commit 2e66371a1d

@ -7,7 +7,6 @@ use App\Services\AccountSecurityService;
use App\Services\AdminCsrf;
use App\Services\Auth;
use App\Services\Payment\RechargeMethodsService;
use App\Services\UserFeatureRestrictionService;
use App\Services\UserProfileService;
use App\Utils\Hash;
@ -186,14 +185,6 @@ class AccountSecurityController extends BaseController
public function rechargeOptions($request, $response, $args)
{
$user = Auth::getUser();
if (UserFeatureRestrictionService::isRechargeRestricted($user)) {
return $this->json($response, [
'ret' => 0,
'msg' => UserFeatureRestrictionService::RECHARGE_MESSAGE,
'methods' => [],
], 503);
}
return $this->json($response, [
'ret' => 1,
'methods' => RechargeMethodsService::forUser($user),

@ -75,10 +75,9 @@ final class CloudApiController
private function userIsoImportAllowed(array $actor, bool $throw = false): bool
{
$user = User::where('id', $actor['user_id'])->first();
$allowed = $user !== null && (int) $user->enable === 1
&& (int) $user->restrict_balance_purchase !== 1;
$allowed = $user !== null && (int) $user->enable === 1;
if (!$allowed && $throw) {
throw new CloudError('账户套餐购买及 ISO 上传服务已被管理员停用', 403);
throw new CloudError('账户不可用,无法导入 ISO', 403);
}
return $allowed;
}
@ -1331,15 +1330,12 @@ final class CloudApiController
CloudMoney::cents((string) $user->money)
);
$balanceSufficient = CloudMoney::cents($balance) >= $priceCents;
$purchaseAllowed = (int) $user->restrict_balance_purchase !== 1;
$enabled = $priceCents > 0;
$canChange = ($options['can_change'] ?? false) === true
&& $enabled && $purchaseAllowed && $balanceSufficient;
&& $enabled && $balanceSufficient;
$message = (string) ($options['message'] ?? '');
if (!$enabled) {
$message = '管理员尚未启用付费更换 IP。';
} elseif (!$purchaseAllowed) {
$message = '账户付费操作已被管理员停用。';
} elseif (!$balanceSufficient) {
$message = '账户余额不足,请先充值。';
}

@ -8,16 +8,12 @@ use App\Models\PaytaroOrder;
use App\Services\Auth;
use App\Services\Config;
use App\Services\Payment\PaytaroPaymentService;
use App\Services\UserFeatureRestrictionService;
class PaytaroController extends BaseController
{
public function create($request, $response, $args)
{
$user = Auth::getUser();
if (UserFeatureRestrictionService::isRechargeRestricted($user)) {
return $this->json($response, ['code' => -1, 'msg' => UserFeatureRestrictionService::RECHARGE_MESSAGE], 503);
}
try {
$order = (new PaytaroPaymentService())->createOrder(
$user,

@ -6,19 +6,12 @@ use App\Models\UsdtPaymentOrder;
use App\Services\Auth;
use App\Services\Payment\UsdtConfig;
use App\Services\Payment\UsdtPaymentService;
use App\Services\UserFeatureRestrictionService;
class UsdtController extends BaseController
{
public function create($request, $response, $args)
{
$user = Auth::getUser();
if (UserFeatureRestrictionService::isRechargeRestricted($user)) {
return $this->json($response, [
'code' => -1,
'msg' => UserFeatureRestrictionService::RECHARGE_MESSAGE,
], 503);
}
if (!UsdtConfig::canUserAccess($user)) {
return $this->json($response, ['code' => -1, 'msg' => 'USDT 充值当前不可用'], 403);
}

@ -33,7 +33,6 @@ use App\Services\ReferralConfig;
use App\Services\Payment\UsdtConfig;
use App\Services\Payment\YipayConfig;
use App\Services\Payment\PaytaroConfig;
use App\Services\UserFeatureRestrictionService;
use App\Services\TicketAttachmentService;
use App\Services\TicketReplyService;
use App\Services\UserDrawerService;
@ -274,29 +273,21 @@ class UserController extends BaseController
public function code($request, $response, $args)
{
$codes = null;
$transactionRecordsRestricted = UserFeatureRestrictionService::isTransactionRecordsRestricted($this->user);
if (!$transactionRecordsRestricted) {
$pageNum = 1;
if (isset($request->getQueryParams()["page"])) {
$pageNum = $request->getQueryParams()["page"];
}
$codes = Code::where('type', '<>', '-2')->where('userid', '=', $this->user->id)->orderBy('id', 'desc')->paginate(15, ['*'], 'page', $pageNum);
$codes->setPath('/user/code');
$pageNum = 1;
if (isset($request->getQueryParams()["page"])) {
$pageNum = $request->getQueryParams()["page"];
}
$codes = Code::where('type', '<>', '-2')->where('userid', '=', $this->user->id)->orderBy('id', 'desc')->paginate(15, ['*'], 'page', $pageNum);
$codes->setPath('/user/code');
$yipayConfig = YipayConfig::values();
$yipayMethods = YipayConfig::visibleMethods($this->user, $yipayConfig);
$yipayAlipayVisible = in_array('alipay', $yipayMethods, true);
$rechargeRestricted = UserFeatureRestrictionService::isRechargeRestricted($this->user);
return $this->view()
->assign('codes', $codes)
->assign('usdt_enabled', UsdtConfig::isUserVisible($this->user))
->assign('paytaro_enabled', PaytaroConfig::isUserVisible($this->user))
->assign('yipay_alipay_enabled', $yipayAlipayVisible)
->assign('yipay_wxpay_enabled', in_array('wxpay', $yipayMethods, true))
->assign('recharge_restricted', $rechargeRestricted)
->assign('transaction_records_restricted', $transactionRecordsRestricted)
->assign("cdn", $this->cdn)
->assign("backup_cdn", $this->backup_cdn)
->display('user/paytaro.tpl');
@ -449,7 +440,6 @@ class UserController extends BaseController
public function invite($request, $response, $args)
{
$user = Auth::getUser();
$inviteRestricted = UserFeatureRestrictionService::isInviteRestricted($user);
$inviteEnabled = $user->canInvite();
$inviteCode = null;
if ($inviteEnabled) {
@ -462,7 +452,7 @@ class UserController extends BaseController
$referralValues[ReferralConfig::VALID_DAYS_KEY] ?? ReferralConfig::DEFAULT_VALID_DAYS
);
return $this->view()->assign('invite_link', $invite_link)->assign('invite_enabled', $inviteEnabled)->assign('invite_restricted', $inviteRestricted)->assign('has_invite_code', $inviteCode !== null)->assign('aff_method', $this->aff_method)->assign('referral_rate', number_format(ReferralConfig::rateFor($user), 2, '.', ''))->assign('referral_days', $referralDays)->assign("cdn", $this->cdn)->assign("backup_cdn", $this->backup_cdn)->display('user/invite.tpl');
return $this->view()->assign('invite_link', $invite_link)->assign('invite_enabled', $inviteEnabled)->assign('has_invite_code', $inviteCode !== null)->assign('aff_method', $this->aff_method)->assign('referral_rate', number_format(ReferralConfig::rateFor($user), 2, '.', ''))->assign('referral_days', $referralDays)->assign("cdn", $this->cdn)->assign("backup_cdn", $this->backup_cdn)->display('user/invite.tpl');
}
public function doAff($request, $response, $args)
@ -540,13 +530,6 @@ class UserController extends BaseController
if ($csrf !== null) {
return $csrf;
}
if (UserFeatureRestrictionService::isInviteRestricted($this->user)) {
return $this->echoJson($response, [
'ret' => 0,
'msg' => UserFeatureRestrictionService::INVITE_MESSAGE,
]);
}
if (!$this->user->canInvite()) {
return $this->echoJson($response, [
'ret' => 0,
@ -622,10 +605,6 @@ class UserController extends BaseController
public function ticket($request, $response, $args)
{
if ($this->ticketAccessRestricted()) {
return $this->ticketPageRestrictedResponse($response);
}
$pageNum = 1;
if (isset($request->getQueryParams()["page"])) {
$pageNum = $request->getQueryParams()["page"];
@ -645,19 +624,12 @@ class UserController extends BaseController
public function ticket_create($request, $response, $args)
{
if ($this->ticketAccessRestricted()) {
return $this->ticketPageRestrictedResponse($response);
}
return $this->view()->assign('instances', $this->ticketInstances())
->display('user/ticket_create.tpl');
}
public function ticket_add($request, $response, $args)
{
if ($this->ticketAccessRestricted()) {
return $this->ticketActionRestrictedResponse($response);
}
if (!AdminCsrf::verify($request)) {
return $this->echoJson($response, ['ret' => 0, 'msg' => '请求已过期,请刷新页面后重试']);
}
@ -720,9 +692,6 @@ class UserController extends BaseController
public function ticket_update($request, $response, $args)
{
if ($this->ticketAccessRestricted()) {
return $this->ticketActionRestrictedResponse($response);
}
if (!AdminCsrf::verify($request)) {
return $this->echoJson($response, ['ret' => 0, 'msg' => '请求已过期,请刷新页面后重试']);
}
@ -767,10 +736,6 @@ class UserController extends BaseController
public function ticket_view($request, $response, $args)
{
if ($this->ticketAccessRestricted()) {
return $this->ticketPageRestrictedResponse($response);
}
$id = $args['id'];
$ticket_main = Ticket::where("id", "=", $id)->where("rootid", "=", 0)->first();
if ($ticket_main == null || $ticket_main->userid != $this->user->id) {
@ -808,9 +773,6 @@ class UserController extends BaseController
public function ticket_attachment($request, $response, $args)
{
if ($this->ticketAccessRestricted()) {
return $response->withStatus(404);
}
if (!$this->ticketAttachmentsAvailable()) {
return $response->withStatus(404);
}
@ -825,11 +787,6 @@ class UserController extends BaseController
return $this->streamTicketAttachment($response, $attachment);
}
private function ticketAccessRestricted()
{
return UserFeatureRestrictionService::isTicketRestricted($this->user);
}
private function notifyTicketAdmins($event, $ticket, $content)
{
foreach (User::where('is_admin', 1)->get() as $admin) {
@ -930,19 +887,6 @@ class UserController extends BaseController
}
}
private function ticketPageRestrictedResponse($response)
{
return $response->withStatus(302)->withHeader('Location', '/user');
}
private function ticketActionRestrictedResponse($response)
{
return $this->echoJson($response, [
'ret' => 0,
'msg' => UserFeatureRestrictionService::TICKET_MESSAGE,
]);
}
public function disable($request, $response, $args)
{
return $this->view()->display('user/disable.tpl');
@ -964,13 +908,6 @@ class UserController extends BaseController
$user = Auth::getUser();
if (UserFeatureRestrictionService::isInviteRestricted($user)) {
return $this->echoJson($response, [
'ret' => 0,
'msg' => UserFeatureRestrictionService::INVITE_MESSAGE,
]);
}
if (!$user->canInvite()) {
return $this->echoJson($response, [
'ret' => 0,

@ -8,19 +8,12 @@ use App\Models\YipayOrder;
use App\Services\Auth;
use App\Services\Config;
use App\Services\Payment\YipayPaymentService;
use App\Services\UserFeatureRestrictionService;
class YipayController extends BaseController
{
public function create($request, $response, $args)
{
$user = Auth::getUser();
if (UserFeatureRestrictionService::isRechargeRestricted($user)) {
return $this->json($response, [
'code' => -1,
'msg' => UserFeatureRestrictionService::RECHARGE_MESSAGE,
], 503);
}
try {
$order = (new YipayPaymentService())->createOrder(
$user,

@ -9,7 +9,6 @@ namespace App\Models;
use App\Utils\Hash;
use App\Models\InviteCode;
use App\Services\ReferralService;
use App\Services\UserFeatureRestrictionService;
use App\Services\UserDataDeletionService;
class User extends Model
@ -23,13 +22,6 @@ class User extends Model
protected $casts = [
"enable" => 'int',
'restrict_recharge' => 'int',
'restrict_balance_purchase' => 'int',
'restrict_invite' => 'int',
'restrict_ticket' => 'int',
'restrict_transaction_records' => 'int',
'restriction_updated_at' => 'int',
'restriction_operator_id' => 'int',
'login_session_version' => 'int',
'is_admin' => 'boolean',
];
@ -61,7 +53,7 @@ class User extends Model
public function canInvite()
{
return (int) $this->enable === 1 && !UserFeatureRestrictionService::isInviteRestricted($this);
return (int) $this->enable === 1;
}
public function isAdmin()

@ -5,7 +5,6 @@ namespace App\Services\Cloud;
use App\Models\CloudInvoice;
use App\Models\User;
use App\Services\AdminCsrf;
use App\Services\UserFeatureRestrictionService;
/**
* Owner-scoped invoice detail payload shared by the HTML first paint and API.
@ -41,8 +40,7 @@ final class CloudInvoiceDetailPageService
'invoice' => $detail,
'payment_methods' => ($detail['payable'] ?? false)
? CloudInvoicePaymentService::methods($user) : [],
'balance_payment_allowed' => (int) $user->enable === 1
&& !UserFeatureRestrictionService::isBalancePurchaseRestricted($user),
'balance_payment_allowed' => (int) $user->enable === 1,
'balance' => (string) $user->money,
'csrf_token' => AdminCsrf::token(),
'user_id' => (string) $user->id,

@ -16,7 +16,6 @@ use App\Services\Payment\UsdtConfig;
use App\Services\Payment\UsdtPaymentService;
use App\Services\Payment\YipayConfig;
use App\Services\Payment\YipayPaymentService;
use App\Services\UserFeatureRestrictionService;
final class CloudInvoicePaymentService
{
@ -95,7 +94,7 @@ final class CloudInvoicePaymentService
* Recheck the account at the final, row-locked provider-order boundary.
*
* The controller performs the same validation for a useful early error,
* but an administrator can change account restrictions before the payment
* but an administrator can disable the account before the payment
* provider's transaction begins. Each provider calls this method after it
* locks the user row so a disabled account cannot still receive a real
* external payment order through that race window.
@ -105,20 +104,10 @@ final class CloudInvoicePaymentService
if ((int) $user->enable !== 1) {
throw new CloudError('账户不存在或不可用', 403);
}
if (UserFeatureRestrictionService::isBalancePurchaseRestricted($user)) {
throw new CloudError(UserFeatureRestrictionService::PURCHASE_MESSAGE, 403);
}
if (UserFeatureRestrictionService::isRechargeRestricted($user)) {
throw new CloudError(UserFeatureRestrictionService::RECHARGE_MESSAGE, 403);
}
}
public static function methods(User $user): array
{
if (UserFeatureRestrictionService::isRechargeRestricted($user)
|| UserFeatureRestrictionService::isBalancePurchaseRestricted($user)) {
return [];
}
$methods = [];
foreach (YipayConfig::visibleMethods($user) as $method) {
$methods[] = ['id' => 'yipay_' . $method,
@ -137,26 +126,12 @@ final class CloudInvoicePaymentService
string $clientIp, string $userAgent): array
{
CloudInput::only($input, ['method', 'idempotency_key']);
if (UserFeatureRestrictionService::isBalancePurchaseRestricted($user)) {
throw new CloudError(UserFeatureRestrictionService::PURCHASE_MESSAGE, 403);
}
if (UserFeatureRestrictionService::isRechargeRestricted($user)) {
throw new CloudError(UserFeatureRestrictionService::RECHARGE_MESSAGE, 403);
}
$validated = (new CloudInstance())->getConnection()->transaction(
function () use ($invoice, $user) {
$lockedUser = User::where('id', $user->id)->lockForUpdate()->first();
if ($lockedUser === null || (int) $lockedUser->enable !== 1) {
return ['error' => '账户不存在或不可用', 'status' => 403];
}
if (UserFeatureRestrictionService::isBalancePurchaseRestricted($lockedUser)) {
return ['error' => UserFeatureRestrictionService::PURCHASE_MESSAGE,
'status' => 403];
}
if (UserFeatureRestrictionService::isRechargeRestricted($lockedUser)) {
return ['error' => UserFeatureRestrictionService::RECHARGE_MESSAGE,
'status' => 403];
}
if ((string) ($invoice->purpose ?: 'renewal') === 'provision') {
$current = CloudInvoice::where('id', $invoice->id)
->where('user_id', $user->id)->lockForUpdate()->first();

@ -918,9 +918,6 @@ final class CloudInvoiceService
if ($user === null || (int) $user->enable !== 1) {
throw new CloudError('账户不存在或不可用', 403);
}
if ((int) $user->restrict_balance_purchase === 1) {
throw new CloudError('账户套餐购买服务已被管理员停用', 403);
}
$sourcePurpose = (string) ($source->purpose ?: 'renewal');
$instance = null;
if ($sourcePurpose !== 'provision') {

@ -2471,9 +2471,6 @@ final class CloudJobService
if ($billingUser === null || (int) $billingUser->enable !== 1) {
throw new CloudError('账户不可用', 403);
}
if ((int) $billingUser->restrict_balance_purchase === 1) {
throw new CloudError('账户付费操作已被管理员停用', 403);
}
if ((int) $locked->user_id !== (int) $billingUser->id) {
throw new CloudError('只能为自己持有的实例更换 IP', 403);
}

@ -45,9 +45,6 @@ final class CloudOrderService
if ($user === null || (int) $user->enable !== 1) {
throw new CloudError('账户不可用', 403);
}
if ((int) $user->restrict_balance_purchase === 1) {
throw new CloudError('账户套餐购买服务已被管理员停用', 403);
}
$existing = CloudOrder::where('user_id', $user->id)->where('idempotency_key', $idempotency)->first();
if ($existing !== null) {
if (!hash_equals($existing->request_hash, $requestHash)) {

@ -28,9 +28,6 @@ final class CloudRenewalService
if ($user === null || (int) $user->enable !== 1) {
throw new CloudError('账户不可用', 403);
}
if ((int) $user->restrict_balance_purchase === 1) {
throw new CloudError('账户套餐购买服务已被管理员停用', 403);
}
$existing = CloudRenewal::where('user_id', $user->id)
->where('idempotency_key', $idempotency)->first();
if ($existing !== null) {

@ -1,54 +0,0 @@
<?php
namespace App\Services;
use App\Models\User;
class UserFeatureRestrictionService
{
public const RECHARGE_MESSAGE = '充值服务暂时无法使用,请稍后再试。';
public const PURCHASE_MESSAGE = '套餐购买服务暂时无法使用,请稍后再试。';
public const INVITE_MESSAGE = '邀请服务暂时无法使用,请稍后再试。';
public const TICKET_MESSAGE = '工单服务暂时无法使用,请稍后再试。';
public static function isRechargeRestricted(User $user)
{
return (int) $user->restrict_recharge === 1;
}
public static function isBalancePurchaseRestricted(User $user)
{
return (int) $user->restrict_balance_purchase === 1;
}
public static function isInviteRestricted(User $user)
{
return (int) $user->restrict_invite === 1;
}
public static function isTicketRestricted(User $user)
{
return (int) $user->restrict_ticket === 1;
}
public static function isTransactionRecordsRestricted(User $user)
{
return (int) $user->restrict_transaction_records === 1;
}
public static function hasManualRestrictions(User $user)
{
return in_array(true, self::status($user), true);
}
public static function status(User $user)
{
return [
'recharge' => self::isRechargeRestricted($user),
'balance_purchase' => self::isBalancePurchaseRestricted($user),
'invite' => self::isInviteRestricted($user),
'ticket' => self::isTicketRestricted($user),
'transaction_records' => self::isTransactionRecordsRestricted($user),
];
}
}

@ -1,300 +0,0 @@
<?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,
];
}
}

@ -46,16 +46,6 @@ class View
'admin_display_user_name',
is_object($user) && isset($user->user_name) ? AdminDataMasker::account($user->user_name) : ''
);
$smarty->assign(
'ticket_navigation_enabled',
$user === null || !$user->isLogin || !UserFeatureRestrictionService::isTicketRestricted($user)
);
$smarty->assign(
'transaction_records_visible',
$user === null || !$user->isLogin || !UserFeatureRestrictionService::isTransactionRecordsRestricted($user)
);
// Navigation is rendered server-side, but the API repeats this check.
// Hiding this link is never treated as the authorisation boundary.
$smarty->assign('user_iso_enabled', is_object($user) && $user->isLogin
? CloudUserIsoFeature::enabled() : false);
return $smarty;

@ -13,8 +13,7 @@
<div class="vu-compact-panel-heading"><div><span class="vu-panel-kicker">REFERRAL LINK</span><h2 id="vuPromotionLinkTitle">推广链接</h2></div><span class="vu-panel-badge">{$referral_rate}% 返利</span></div>
<p class="vu-compact-hint vu-referral-hint"><i class="mdi mdi-information-outline" aria-hidden="true"></i><span>好友通过此链接注册后,{$referral_days} 天内符合条件的充值将计入返利。</span></p>
<div class="vu-compact-link-row">
{if $invite_restricted}<code>推广服务暂时无法使用</code>
{elseif !$invite_enabled}<code>推广功能暂不可用</code>
{if !$invite_enabled}<code>推广功能暂不可用</code>
{elseif $invite_link != ''}<code id="aff_link">{$invite_link|escape:'html'}</code><button class="vu-icon-btn" type="button" data-copy="{$invite_link|escape:'html'}" aria-label="复制推广链接"><i class="mdi mdi-content-copy"></i></button>
{else}<code>尚未生成推广链接</code>{/if}
</div>

@ -32,12 +32,10 @@
<i class="mdi mdi-file-document-outline nav-icon" aria-hidden="true"></i><span>账单信息</span>
</a>
{if !empty($ticket_navigation_enabled)}
<div class="sidebar-section-label">支持</div>
<a class="sidebar-link{if $panel_active_key == 'ticket'} active{/if}" href="/user/ticket">
<i class="mdi mdi-lifebuoy nav-icon" aria-hidden="true"></i><span>工单支持</span>
</a>
{/if}
</nav>
<div class="sidebar-bottom panel-sidebar-bottom">

@ -5,7 +5,7 @@
<h1>充值结果</h1>
</div>
<div class="vu-top-actions">
<button class="vu-btn vu-btn-ghost" type="button" data-account-drawer-open="balance" data-drawer-title="余额充值" data-drawer-description="选择充值金额和可用支付方式"><i class="mdi mdi-wallet-outline"></i><span>{if $transaction_records_visible}充值记录{else}返回充值{/if}</span></button>
<button class="vu-btn vu-btn-ghost" type="button" data-account-drawer-open="balance" data-drawer-title="余额充值" data-drawer-description="选择充值金额和可用支付方式"><i class="mdi mdi-wallet-outline"></i><span>充值记录</span></button>
<a class="vu-btn" href="/user/cloud/deploy"><i class="mdi mdi-cart-outline"></i><span>购买套餐</span></a>
</div>
</header>

@ -11,18 +11,13 @@
<div class="vu-compact-stack">
<section class="vu-compact-panel vu-recharge-panel" aria-labelledby="vuRechargeFormTitle">
<div class="vu-compact-panel-heading"><div><span class="vu-panel-kicker">WALLET</span><h2 id="vuRechargeFormTitle">输入金额</h2></div><span class="vu-panel-badge"><i class="mdi mdi-shield-check-outline"></i>安全支付</span></div>
{if $recharge_restricted}
<div class="vu-inline-empty"><i class="mdi mdi-clock-alert-outline"></i><span>充值服务暂时无法使用,请稍后再试。</span></div>
{else}
<form class="vu-compact-form" id="vuPayForm" data-csrf-token="{$account_csrf_token|default:''|escape:'html'}" autocomplete="off">
<label class="vu-compact-field" for="price"><span>充值金额(美元)</span><div class="vu-amount-field"><b>$</b><input class="vu-input" id="price" name="price" type="number" min="0.01" step="0.01" inputmode="decimal" placeholder="请输入美元金额" aria-describedby="vuRechargeHint"></div></label>
<p class="vu-compact-hint" id="vuRechargeHint">填写金额后选择可用支付方式。</p>
<div class="vu-recharge-methods" id="vuRechargeMethods" hidden aria-live="polite"></div>
</form>
{/if}
</section>
{if !$transaction_records_restricted}
<details class="vu-compact-panel vu-history-panel">
<summary><span class="vu-summary-icon"><i class="mdi mdi-receipt-text-clock-outline"></i></span><span class="vu-summary-copy"><strong>充值记录</strong><small>查看最近的余额入账记录</small></span><span class="vu-summary-count">{$codes->total()}</span><i class="mdi mdi-chevron-down vu-summary-chevron"></i></summary>
<div class="vu-compact-panel-body vu-history-body">
@ -37,7 +32,6 @@
<div class="vu-table-footer"><span>共 {$codes->total()} 条</span><div class="vu-pagination-wrap">{$codes->links()}</div></div>
</div>
</details>
{/if}
</div>
</section>

@ -322,15 +322,7 @@ CREATE TABLE `user` (
`login_session_version` bigint(20) UNSIGNED NOT NULL DEFAULT 0,
`remark` text DEFAULT NULL,
`aff_money` decimal(12,2) NOT NULL DEFAULT 0.00,
`aff_rate` int(11) NOT NULL DEFAULT 20,
`restrict_recharge` tinyint(1) UNSIGNED NOT NULL DEFAULT 0,
`restrict_balance_purchase` tinyint(1) UNSIGNED NOT NULL DEFAULT 0,
`restrict_invite` tinyint(1) UNSIGNED NOT NULL DEFAULT 0,
`restrict_ticket` tinyint(1) UNSIGNED NOT NULL DEFAULT 0,
`restrict_transaction_records` tinyint(1) UNSIGNED NOT NULL DEFAULT 0,
`restriction_reason` varchar(255) NOT NULL DEFAULT '',
`restriction_updated_at` bigint(20) UNSIGNED NOT NULL DEFAULT 0,
`restriction_operator_id` int(11) UNSIGNED NOT NULL DEFAULT 0
`aff_rate` int(11) NOT NULL DEFAULT 20
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci;
CREATE TABLE `user_surveys` (

@ -1,11 +0,0 @@
-- Import this file before deploying the user feature restriction code.
ALTER TABLE `user`
ADD COLUMN IF NOT EXISTS `restrict_recharge` tinyint(1) UNSIGNED NOT NULL DEFAULT 0 AFTER `user_tcp_limit`,
ADD COLUMN IF NOT EXISTS `restrict_balance_purchase` tinyint(1) UNSIGNED NOT NULL DEFAULT 0 AFTER `restrict_recharge`,
ADD COLUMN IF NOT EXISTS `restrict_subscription` tinyint(1) UNSIGNED NOT NULL DEFAULT 0 AFTER `restrict_balance_purchase`,
ADD COLUMN IF NOT EXISTS `restrict_invite` tinyint(1) UNSIGNED NOT NULL DEFAULT 0 AFTER `restrict_subscription`,
ADD COLUMN IF NOT EXISTS `restrict_ticket` tinyint(1) UNSIGNED NOT NULL DEFAULT 0 AFTER `restrict_invite`,
ADD COLUMN IF NOT EXISTS `restrict_transaction_records` tinyint(1) UNSIGNED NOT NULL DEFAULT 0 AFTER `restrict_ticket`,
ADD COLUMN IF NOT EXISTS `restriction_reason` varchar(255) NOT NULL DEFAULT '' AFTER `restrict_transaction_records`,
ADD COLUMN IF NOT EXISTS `restriction_updated_at` bigint(20) UNSIGNED NOT NULL DEFAULT 0 AFTER `restriction_reason`,
ADD COLUMN IF NOT EXISTS `restriction_operator_id` int(11) UNSIGNED NOT NULL DEFAULT 0 AFTER `restriction_updated_at`;

@ -1,2 +0,0 @@
ALTER TABLE `user`
ADD COLUMN IF NOT EXISTS `restrict_ticket` tinyint(1) UNSIGNED NOT NULL DEFAULT 0;

@ -1,2 +0,0 @@
ALTER TABLE `user`
ADD COLUMN IF NOT EXISTS `restrict_transaction_records` tinyint(1) UNSIGNED NOT NULL DEFAULT 0;

@ -93,7 +93,6 @@ namespace {
$table->increments('id');
$table->string('money');
$table->integer('enable')->default(1);
$table->integer('restrict_balance_purchase')->default(0);
});
$schema->create('cloud_instances', static function (Blueprint $table): void {
$table->increments('id');
@ -274,7 +273,6 @@ namespace {
$user->id = 1;
$user->money = '100.00';
$user->enable = 1;
$user->restrict_balance_purchase = 0;
$user->save();
$now = time();

@ -229,7 +229,7 @@ namespace {
$capsule->addConnection(['driver' => 'sqlite', 'database' => ':memory:'], 'default');
$capsule->setAsGlobal(); $capsule->bootEloquent();
$schema = $capsule->schema('default');
$schema->create('user', function (Blueprint $t) { $t->increments('id'); $t->string('user_name')->default(''); $t->string('email')->default(''); $t->string('money'); $t->integer('enable')->default(1); $t->integer('is_admin')->default(0); $t->integer('restrict_balance_purchase')->default(0); });
$schema->create('user', function (Blueprint $t) { $t->increments('id'); $t->string('user_name')->default(''); $t->string('email')->default(''); $t->string('money'); $t->integer('enable')->default(1); $t->integer('is_admin')->default(0); });
$schema->create('configurations', function (Blueprint $t) { $t->increments('id'); $t->string('name')->unique(); $t->text('value'); });
$schema->create('shop', function (Blueprint $t) { $t->increments('id'); $t->string('name'); foreach (['cpu_cores', 'memory_mib', 'bandwidth_mbps', 'disk_gib', 'validity_days', 'traffic_quota_bytes', 'status', 'sort'] as $v) { $t->integer($v)->default(0); } });
$schema->create('cloud_regions', function (Blueprint $t) { $t->increments('id'); $t->string('code'); $t->string('name'); $t->string('country_code'); $t->string('status'); $t->integer('sort')->default(0); $t->integer('created_at'); $t->integer('updated_at'); });

@ -58,8 +58,6 @@ namespace {
$schema = $capsule->schema('default');
$schema->create('user', static function (Blueprint $table): void {
$table->increments('id'); $table->string('money'); $table->integer('enable')->default(1);
$table->integer('restrict_recharge')->default(0);
$table->integer('restrict_balance_purchase')->default(0);
});
$schema->create('cloud_instances', static function (Blueprint $table): void {
$table->increments('id'); $table->integer('host_id'); $table->integer('user_id');
@ -167,7 +165,7 @@ namespace {
});
$user = new User(); $user->id = 1; $user->money = '50.00'; $user->enable = 1;
$user->restrict_balance_purchase = 0; $user->save();
$user->save();
$now = time();
$instance = new CloudInstance(); $instance->host_id = 1; $instance->user_id = 1; $instance->plan_id = 8;
$instance->uuid = '11111111-2222-4333-8444-555555555555'; $instance->name = 'invoice-vm';

@ -133,7 +133,7 @@ namespace {
$assert(str_contains($invoicePaymentService, 'assertInvoicePaymentAllowed')
&& substr_count($paymentProviders,
'CloudInvoicePaymentService::assertInvoicePaymentAllowed($lockedUser)') === 3,
'Every online provider must recheck account restrictions inside its final row-locked order transaction.');
'Every online provider must recheck account availability inside its final row-locked order transaction.');
$assert(str_contains($shopViews, '内存(GB)')
&& str_contains($shopViews, '每期流量额度(TB)')
&& str_contains($shopViews, '价格(USD)')

@ -10,14 +10,9 @@ $disabled->enable = 0;
$enabled = new User();
$enabled->enable = 1;
$restricted = new User();
$restricted->enable = 1;
$restricted->restrict_invite = 1;
$cases = [
'disabled account cannot invite' => [$disabled->canInvite(), false],
'enabled account can invite without membership' => [$enabled->canInvite(), true],
'manually restricted account cannot invite' => [$restricted->canInvite(), false],
'disabled account has no invitation link' => [$disabled->getAffLink(), ''],
];

@ -192,8 +192,6 @@ $schema->create('user', function (Blueprint $table) {
$table->increments('id');
$table->decimal('money', 12, 2)->default(0);
$table->integer('enable')->default(1);
$table->integer('restrict_balance_purchase')->default(0);
$table->integer('restrict_recharge')->default(0);
$table->integer('ref_by')->default(0);
$table->dateTime('reg_date');
$table->decimal('aff_rate', 8, 2)->default(0);

@ -59,8 +59,6 @@ $schema->create('user', function (Blueprint $table) {
$table->integer('is_admin')->default(0);
$table->decimal('money', 12, 2)->default(0);
$table->integer('enable')->default(1);
$table->integer('restrict_balance_purchase')->default(0);
$table->integer('restrict_recharge')->default(0);
$table->integer('ref_by')->default(0);
$table->dateTime('reg_date');
$table->decimal('aff_rate', 8, 2)->default(0);

@ -18,7 +18,6 @@ $smarty->assign('config', ['appName' => 'Venix Test', 'jump_delay' => 1000]);
$smarty->assign('cdn', '');
$smarty->assign('user', (object) ['user_name' => '演示用户']);
$smarty->assign('admin_can_manage', false);
$smarty->assign('ticket_navigation_enabled', true);
$smarty->assign('user_iso_enabled', false);
$preview = '<section class="host-card"><h1>用户页面预览</h1><p>此处仅使用合成数据,公告首屏使用安全摘要并在打开后静默校验。</p></section>'
. str_repeat('<section class="host-card"><h2>预览内容</h2><p>用于检查打开公告前后页面滚动位置。</p></section>', 8);

@ -1,55 +0,0 @@
<?php
// Pure field-contract fixture: no Eloquent bootstrap or database connection.
namespace App\Models {
class User
{
public int $id = 0;
public int $is_admin = 0;
public int $restrict_recharge = 0;
public int $restrict_balance_purchase = 0;
public int $restrict_invite = 0;
public int $restrict_ticket = 0;
public int $restrict_transaction_records = 0;
}
}
namespace {
require dirname(__DIR__) . '/app/Services/UserFeatureRestrictionService.php';
use App\Models\User;
use App\Services\UserFeatureRestrictionService;
$fields = [
'restrict_recharge' => 'recharge',
'restrict_balance_purchase' => 'balance_purchase',
'restrict_invite' => 'invite',
'restrict_ticket' => 'ticket',
'restrict_transaction_records' => 'transaction_records',
];
foreach (array_merge([null], array_keys($fields)) as $restrictedField) {
$user = new User();
$user->id = 42;
$user->is_admin = 0;
foreach ($fields as $field => $statusKey) {
$user->$field = $field === $restrictedField ? 1 : 0;
}
$status = UserFeatureRestrictionService::status($user);
foreach ($fields as $field => $statusKey) {
if ($status[$statusKey] !== ($field === $restrictedField)) {
fwrite(STDERR, 'Manual restriction affected the wrong feature: ' . $statusKey . PHP_EOL);
exit(1);
}
}
if (UserFeatureRestrictionService::hasManualRestrictions($user) !== ($restrictedField !== null)) {
fwrite(STDERR, 'Manual restriction presence check failed.' . PHP_EOL);
exit(1);
}
}
if (method_exists(UserFeatureRestrictionService::class, 'isAutomaticCommerceRestricted')
|| method_exists(UserFeatureRestrictionService::class, 'isSubscriptionRestricted')) {
fwrite(STDERR, 'Retired membership/subscription restrictions remain.' . PHP_EOL);
exit(1);
}
echo 'Independent manual restrictions passed without membership or proxy fields.' . PHP_EOL;
}

@ -1,133 +0,0 @@
<?php
require dirname(__DIR__) . '/vendor/autoload.php';
use App\Models\Configurations;
use App\Models\EmailVerify;
use App\Models\User;
use App\Services\Mail;
use App\Services\RedisClient;
use App\Services\UserRestrictionEnforcementService;
use Illuminate\Database\Capsule\Manager as Capsule;
use Illuminate\Database\Schema\Blueprint;
$raw = "existing@example.com\n*@blocked.example\ncommented@example.com # legacy";
$merged = UserRestrictionEnforcementService::mergeEmailBlacklist($raw, [
'NEW@example.com',
'existing@example.com',
'Commented@example.com',
'not-an-email',
]);
$cases = [
'only new valid email is appended' => [$merged['added'], ['new@example.com']],
'existing rules are preserved' => [strpos($merged['value'], '*@blocked.example') !== false, true],
'new email is normalized' => [substr_count($merged['value'], 'new@example.com'), 1],
];
$second = UserRestrictionEnforcementService::mergeEmailBlacklist($merged['value'], [
'new@example.com',
'EXISTING@example.com',
]);
$cases['repeated enforcement is idempotent'] = [$second['added'], []];
$cases['idempotent merge keeps value unchanged'] = [$second['value'], $merged['value']];
$removed = UserRestrictionEnforcementService::removeEmailsFromBlacklist($merged['value'], [
'EXISTING@example.com',
'commented@example.com',
]);
$cases['exact emails are removed case-insensitively'] = [$removed['removed'], ['existing@example.com', 'commented@example.com']];
$cases['wildcard blacklist rule is preserved on release'] = [strpos($removed['value'], '*@blocked.example') !== false, true];
$cases['unrelated exact email is preserved on release'] = [strpos($removed['value'], 'new@example.com') !== false, true];
$repeatRemoval = UserRestrictionEnforcementService::removeEmailsFromBlacklist($removed['value'], [
'existing@example.com',
]);
$cases['repeated release is idempotent'] = [$repeatRemoval['removed'], []];
$cases['idempotent release keeps value unchanged'] = [$repeatRemoval['value'], $removed['value']];
$mailRules = Mail::parseEmailBlacklistRules("Exact@Example.com\n*@blocked.example\n@other.example\n# ignored");
$cases['mail blacklist matches exact email'] = [Mail::isRecipientBlacklistedByRules('exact@example.com', $mailRules), true];
$cases['mail blacklist matches wildcard domain'] = [Mail::isRecipientBlacklistedByRules('user@blocked.example', $mailRules), true];
$cases['mail blacklist matches at-domain rule'] = [Mail::isRecipientBlacklistedByRules('user@other.example', $mailRules), true];
$cases['mail blacklist leaves unrelated email available'] = [Mail::isRecipientBlacklistedByRules('user@allowed.example', $mailRules), false];
$capsule = new Capsule();
$capsule->addConnection(['driver' => 'sqlite', 'database' => ':memory:'], 'default');
$capsule->setAsGlobal();
$capsule->bootEloquent();
$capsule->schema('default')->create('configurations', function (Blueprint $table) {
$table->increments('id');
$table->string('name', 256)->nullable();
$table->string('value', 512)->nullable();
});
$capsule->schema('default')->create('email_verify', function (Blueprint $table) {
$table->increments('id');
$table->text('email');
$table->text('ip');
$table->text('code');
$table->bigInteger('expire_in');
});
$email = 'restricted@example.com';
$capsule->table('email_verify')->insert([
'email' => $email,
'ip' => '127.0.0.1',
'code' => '123456',
'expire_in' => time() + 600,
]);
$user = new User();
$user->id = 42;
$user->email = $email;
$user->is_admin = false;
$redis = new class extends RedisClient {
private $fakeClient;
public function __construct()
{
$this->fakeClient = new class {
public function executeRaw($command)
{
return ['0', []];
}
};
}
public function getClient()
{
return $this->fakeClient;
}
public function del($key)
{
}
};
$enforcement = UserRestrictionEnforcementService::enforceUsers([$user], $redis);
$cases['database-backed enforcement succeeds'] = [$enforcement['database_error'], false];
$cases['database-backed enforcement appends email'] = [$enforcement['emails_added'], 1];
$cases['database-backed enforcement stores email'] = [Configurations::where('name', 'email_blacklist')->value('value'), $email];
$cases['database-backed enforcement invalidates verification codes'] = [EmailVerify::where('email', $email)->count(), 0];
$repeatEnforcement = UserRestrictionEnforcementService::enforceUsers([$user], $redis);
$cases['database-backed enforcement stays idempotent'] = [$repeatEnforcement['emails_added'], 0];
$release = UserRestrictionEnforcementService::releaseUsers([$user], $redis);
$cases['database-backed release succeeds'] = [$release['database_error'], false];
$cases['database-backed release removes email'] = [$release['emails_removed'], 1];
$cases['database-backed release updates stored blacklist'] = [Configurations::where('name', 'email_blacklist')->value('value'), ''];
$repeatRelease = UserRestrictionEnforcementService::releaseUsers([$user], $redis);
$cases['database-backed release stays idempotent'] = [$repeatRelease['emails_removed'], 0];
foreach ($cases as $name => [$actual, $expected]) {
if ($actual !== $expected) {
fwrite(STDERR, sprintf("%s failed: expected %s, got %s\n", $name, var_export($expected, true), var_export($actual, true)));
exit(1);
}
}
echo "User restriction enforcement tests passed.\n";

@ -68,8 +68,6 @@ $schema->create('user', function (Blueprint $table) {
$table->increments('id');
$table->decimal('money', 12, 2)->default(0);
$table->integer('enable')->default(1);
$table->integer('restrict_balance_purchase')->default(0);
$table->integer('restrict_recharge')->default(0);
$table->integer('ref_by')->default(0);
$table->dateTime('reg_date');
$table->decimal('aff_rate', 8, 2)->default(0);

Loading…
Cancel
Save