- Updated the `UpdateClientAsync` method in `IXuiPanelGateway` to accept nullable parameters for `name` and `expiresAt`, allowing for more flexible client management without unintended modifications. - Adjusted the `BlockUserCommandHandler`, `UnblockUserCommandHandler`, and other related command handlers to utilize the new nullable parameters, ensuring that client names remain unchanged during block/unblock operations and that expiration dates are managed correctly. - Enhanced the billing and configuration handling to reflect the new logic for managing client states based on expiration rather than enabling/disabling, improving reliability in client status management. - Updated tests to cover the new behavior and ensure proper functionality across the application.
105 lines
4.2 KiB
C#
105 lines
4.2 KiB
C#
using Microsoft.EntityFrameworkCore;
|
|
using Microsoft.Extensions.Logging;
|
|
using PnvPanel.Application.Common.Interfaces;
|
|
using PnvPanel.Application.Common.Messaging;
|
|
using PnvPanel.Application.Common.Models;
|
|
using PnvPanel.Domain.Audit;
|
|
using PnvPanel.Domain.Configs;
|
|
|
|
namespace PnvPanel.Application.Admin.Users;
|
|
|
|
/// <summary>Блокировка гасит все активные конфиги в 3x-ui (см. architecture.md).</summary>
|
|
public sealed class BlockUserCommandHandler(
|
|
IAppDbContext dbContext,
|
|
IIdentityService identityService,
|
|
IXuiPanelGateway gateway,
|
|
IRealtimeNotifier notifier,
|
|
ITelegramNotifier telegramNotifier,
|
|
ICurrentUser currentUser,
|
|
ILogger<BlockUserCommandHandler> logger
|
|
) : ICommandHandler<BlockUserCommand, Result>
|
|
{
|
|
public async Task<Result> Handle(BlockUserCommand command, CancellationToken cancellationToken)
|
|
{
|
|
var blockResult = await identityService.BlockUserAsync(command.UserId, cancellationToken);
|
|
if (!blockResult.IsSuccess)
|
|
return blockResult;
|
|
|
|
var configs = await dbContext
|
|
.VpnConfigs.Where(c => c.UserId == command.UserId && c.Status == ConfigStatus.Active)
|
|
.ToListAsync(cancellationToken);
|
|
|
|
foreach (var config in configs)
|
|
{
|
|
var inbound = await dbContext
|
|
.Inbounds.AsNoTracking()
|
|
.FirstOrDefaultAsync(i => i.Id == config.InboundId, cancellationToken);
|
|
var node = inbound is null
|
|
? null
|
|
: await dbContext
|
|
.Nodes.AsNoTracking()
|
|
.FirstOrDefaultAsync(n => n.Id == inbound.NodeId, cancellationToken);
|
|
|
|
if (inbound is not null && node is not null)
|
|
{
|
|
// name: null — не трогаем текущее имя клиента в панели, это не переименование.
|
|
// expiresAt: null — блокировка админом отдельная ось от биллинга (см.
|
|
// IXuiPanelGateway.UpdateClientAsync), срок оплаты не трогаем.
|
|
var updateResult = await gateway.UpdateClientAsync(
|
|
node,
|
|
inbound.RemoteInboundId,
|
|
config.ClientExternalId,
|
|
config.Protocol,
|
|
name: null,
|
|
enable: false,
|
|
expiresAt: null,
|
|
cancellationToken
|
|
);
|
|
|
|
if (!updateResult.IsSuccess)
|
|
{
|
|
// Нода недоступна/сбой панели — не помечаем Disabled локально, иначе БД разойдётся
|
|
// с реальным состоянием клиента в 3x-ui (пользователь решит, что VPN погашен, а он жив).
|
|
// Конфиг останется Active и будет подхвачен повторным BlockUserCommand (идемпотентен).
|
|
logger.LogWarning(
|
|
"Failed to disable client for config {ConfigId} on node {NodeId} while blocking user {UserId}: {Error}",
|
|
config.Id,
|
|
node.Id,
|
|
command.UserId,
|
|
updateResult.Error
|
|
);
|
|
continue;
|
|
}
|
|
}
|
|
|
|
config.Disable();
|
|
await notifier.NotifyConfigStatusChangedAsync(
|
|
config.UserId,
|
|
config.Id,
|
|
config.Status,
|
|
cancellationToken
|
|
);
|
|
}
|
|
|
|
dbContext.AuditLogs.Add(
|
|
AuditLog.Create(
|
|
currentUser.UserId,
|
|
"UserBlocked",
|
|
"User",
|
|
command.UserId.ToString(),
|
|
metadata: null,
|
|
AuditSource.Web
|
|
)
|
|
);
|
|
|
|
await telegramNotifier.NotifyUserAsync(
|
|
command.UserId,
|
|
"⛔ Ваш аккаунт заблокирован администратором.",
|
|
null,
|
|
cancellationToken
|
|
);
|
|
|
|
return Result.Success();
|
|
}
|
|
}
|