Files
PnvPanel/backend/src/PnvPanel.Application/Admin/Users/BlockUserCommandHandler.cs
T
Leonid Pershin bea2b5fcf7
CI / Backend (build + test) (push) Successful in 1m24s
CI / Frontend (lint + typecheck + build) (push) Successful in 30s
Refactor VPN configuration handling to remove device limit management
- Updated the VPN configuration commands and handlers to eliminate the device limit parameter, simplifying the configuration process.
- Adjusted related API documentation to reflect the removal of device limit management, clarifying that this setting is now handled directly in the 3x-ui by node administrators.
- Enhanced the overall codebase by removing unnecessary device limit references across various components, ensuring a cleaner and more maintainable code structure.
2026-07-02 23:21:26 +03:00

65 lines
3.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)
{
var updateResult = await gateway.UpdateClientAsync(
node, inbound.RemoteInboundId, config.ClientExternalId, config.Protocol,
config.Label ?? config.ClientEmail, enable: false, 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, "⛔ Ваш аккаунт заблокирован администратором.", cancellationToken);
return Result.Success();
}
}