Add Telegram bot integration and enhance user management features

- Introduced Telegram.Bot package for bot functionality.
- Updated user management to include Telegram linking and blocking features.
- Enhanced activation request handling with notifications via Telegram.
- Added new database entities for Telegram link tokens and login requests.
- Implemented traffic synchronization for client stats in the XuiPanelGateway.
- Updated application structure to support new test projects and improved dependency injection for Telegram services.
This commit is contained in:
Leonid Pershin
2026-07-02 01:01:03 +03:00
parent 1a8d33efa3
commit 7b6fe9ad78
142 changed files with 7570 additions and 22 deletions
@@ -0,0 +1,66 @@
using PnvPanel.Application.Admin.Inbounds;
using PnvPanel.Application.Tests.TestSupport;
using PnvPanel.Domain.Inbounds;
using Xunit;
namespace PnvPanel.Application.Tests.Admin.Inbounds;
public class PublishInboundCommandHandlerTests
{
[Fact]
public async Task Handle_WhenPublishingExistingInbound_UpdatesPublishState()
{
using var dbContext = InMemoryDbContextFactory.Create();
var inbound = Inbound.FromRemote(Guid.NewGuid(), "1", VpnProtocol.Vless, "remark", 443);
dbContext.Inbounds.Add(inbound);
await dbContext.SaveChangesAsync(CancellationToken.None);
var roleId = Guid.NewGuid();
var handler = new PublishInboundCommandHandler(dbContext);
var command = new PublishInboundCommand(inbound.Id, true, "EU Fast", [roleId], 100);
var result = await handler.Handle(command, CancellationToken.None);
Assert.True(result.IsSuccess);
Assert.True(inbound.IsPublished);
Assert.Equal("EU Fast", inbound.DisplayName);
Assert.Equal(100, inbound.MaxClients);
Assert.Contains(roleId, inbound.AllowedRoleIds);
Assert.Equal("EU Fast", result.Value.DisplayName);
}
[Fact]
public async Task Handle_WhenUnpublishing_ClearsPublishedFlag()
{
using var dbContext = InMemoryDbContextFactory.Create();
var inbound = Inbound.FromRemote(Guid.NewGuid(), "1", VpnProtocol.Vless, "remark", 443);
inbound.Publish("EU Fast", [Guid.NewGuid()], 100);
dbContext.Inbounds.Add(inbound);
await dbContext.SaveChangesAsync(CancellationToken.None);
var handler = new PublishInboundCommandHandler(dbContext);
var command = new PublishInboundCommand(inbound.Id, false, null, [], null);
var result = await handler.Handle(command, CancellationToken.None);
Assert.True(result.IsSuccess);
Assert.False(inbound.IsPublished);
}
[Fact]
public async Task Handle_WhenInboundNotFound_ReturnsNotFound()
{
using var dbContext = InMemoryDbContextFactory.Create();
var handler = new PublishInboundCommandHandler(dbContext);
var command = new PublishInboundCommand(Guid.NewGuid(), true, "EU Fast", [], null);
var result = await handler.Handle(command, CancellationToken.None);
Assert.False(result.IsSuccess);
Assert.Equal(InboundErrors.NotFound, result.Error);
}
}
@@ -0,0 +1,71 @@
using NSubstitute;
using PnvPanel.Application.Admin.Nodes;
using PnvPanel.Application.Common.Interfaces;
using PnvPanel.Application.Common.Models;
using PnvPanel.Application.Tests.TestSupport;
using Xunit;
namespace PnvPanel.Application.Tests.Admin.Nodes;
public class RegisterNodeCommandHandlerTests
{
private readonly IXuiPanelGateway _gateway = Substitute.For<IXuiPanelGateway>();
private readonly ISecretProtector _secretProtector = Substitute.For<ISecretProtector>();
[Fact]
public async Task Handle_WithValidAddress_RegistersNodeWithProtectedPassword()
{
using var dbContext = InMemoryDbContextFactory.Create();
_gateway.ValidateBaseAddress(Arg.Any<Uri>()).Returns(Result.Success());
_secretProtector.Protect("secret-password").Returns("protected-secret-password");
var handler = new RegisterNodeCommandHandler(dbContext, _gateway, _secretProtector);
var command = new RegisterNodeCommand("node-1", "https://node1.example.com", "admin", "secret-password", "eu-west");
var result = await handler.Handle(command, CancellationToken.None);
Assert.True(result.IsSuccess);
Assert.Equal("node-1", result.Value.Name);
Assert.Equal("admin", result.Value.Username);
Assert.Single(dbContext.Nodes.Local);
Assert.Equal("protected-secret-password", dbContext.Nodes.Local.Single().Credentials.ProtectedPassword);
}
[Fact]
public async Task Handle_WithInvalidBaseAddress_ReturnsValidationErrorWithoutTouchingGateway()
{
using var dbContext = InMemoryDbContextFactory.Create();
var handler = new RegisterNodeCommandHandler(dbContext, _gateway, _secretProtector);
var command = new RegisterNodeCommand("node-1", "not-a-uri", "admin", "secret-password", null);
var result = await handler.Handle(command, CancellationToken.None);
Assert.False(result.IsSuccess);
Assert.Equal(NodeErrors.InvalidBaseAddress, result.Error);
_gateway.DidNotReceive().ValidateBaseAddress(Arg.Any<Uri>());
Assert.Empty(dbContext.Nodes.Local);
}
[Fact]
public async Task Handle_WhenGatewayRejectsBaseAddress_ReturnsFailureWithoutRegisteringNode()
{
using var dbContext = InMemoryDbContextFactory.Create();
var error = Error.Validation("Nodes.SchemeNotAllowed", "Разрешён только HTTPS.");
_gateway.ValidateBaseAddress(Arg.Any<Uri>()).Returns(Result.Failure(error));
var handler = new RegisterNodeCommandHandler(dbContext, _gateway, _secretProtector);
var command = new RegisterNodeCommand("node-1", "http://node1.example.com", "admin", "secret-password", null);
var result = await handler.Handle(command, CancellationToken.None);
Assert.False(result.IsSuccess);
Assert.Equal(error, result.Error);
Assert.Empty(dbContext.Nodes.Local);
}
}
@@ -0,0 +1,93 @@
using NSubstitute;
using PnvPanel.Application.Admin.Users;
using PnvPanel.Application.Common.Interfaces;
using PnvPanel.Application.Common.Models;
using PnvPanel.Application.Tests.TestSupport;
using PnvPanel.Domain.Configs;
using PnvPanel.Domain.Inbounds;
using PnvPanel.Domain.Nodes;
using Xunit;
namespace PnvPanel.Application.Tests.Admin.Users;
public class BlockUserCommandHandlerTests
{
private readonly IIdentityService _identityService = Substitute.For<IIdentityService>();
private readonly IXuiPanelGateway _gateway = Substitute.For<IXuiPanelGateway>();
private readonly IRealtimeNotifier _notifier = Substitute.For<IRealtimeNotifier>();
private readonly ICurrentUser _currentUser = Substitute.For<ICurrentUser>();
[Fact]
public async Task Handle_IdentityServiceFails_ReturnsFailureWithoutTouchingConfigs()
{
using var dbContext = InMemoryDbContextFactory.Create();
var userId = Guid.NewGuid();
var failure = UserErrors.NotFound;
_identityService.BlockUserAsync(userId, Arg.Any<CancellationToken>()).Returns(Result.Failure(failure));
var handler = new BlockUserCommandHandler(dbContext, _identityService, _gateway, _notifier, _currentUser);
var result = await handler.Handle(new BlockUserCommand(userId), CancellationToken.None);
Assert.False(result.IsSuccess);
Assert.Equal(failure, result.Error);
await _gateway.DidNotReceive().UpdateClientAsync(
Arg.Any<Node>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<VpnProtocol>(),
Arg.Any<string>(), Arg.Any<int>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
}
[Fact]
public async Task Handle_Success_DisablesActiveConfigsAndWritesAudit()
{
using var dbContext = InMemoryDbContextFactory.Create();
var userId = Guid.NewGuid();
var adminId = Guid.NewGuid();
var node = Node.Register("node-1", new Uri("https://node1.example.com"), new NodeCredentials("admin", "protected"), null);
var inbound = Inbound.FromRemote(node.Id, "1", VpnProtocol.Vless, "remark", 443);
var config = VpnConfig.Create(userId, inbound.Id, VpnProtocol.Vless, "my-config", 0);
dbContext.Nodes.Add(node);
dbContext.Inbounds.Add(inbound);
dbContext.VpnConfigs.Add(config);
await dbContext.SaveChangesAsync(CancellationToken.None);
_identityService.BlockUserAsync(userId, Arg.Any<CancellationToken>()).Returns(Result.Success());
_currentUser.UserId.Returns(adminId);
var handler = new BlockUserCommandHandler(dbContext, _identityService, _gateway, _notifier, _currentUser);
var result = await handler.Handle(new BlockUserCommand(userId), CancellationToken.None);
Assert.True(result.IsSuccess);
Assert.Equal(ConfigStatus.Disabled, config.Status);
await _gateway.Received(1).UpdateClientAsync(
Arg.Is<Node>(n => n.Id == node.Id), inbound.RemoteInboundId, config.ClientExternalId, config.Protocol,
"my-config", config.DeviceLimit, enable: false, Arg.Any<CancellationToken>());
await _notifier.Received(1).NotifyConfigStatusChangedAsync(userId, config.Id, ConfigStatus.Disabled, Arg.Any<CancellationToken>());
var audit = Assert.Single(dbContext.AuditLogs.Local);
Assert.Equal("UserBlocked", audit.Action);
Assert.Equal(adminId, audit.ActorId);
}
[Fact]
public async Task Handle_NoActiveConfigs_SkipsGatewayCalls()
{
using var dbContext = InMemoryDbContextFactory.Create();
var userId = Guid.NewGuid();
_identityService.BlockUserAsync(userId, Arg.Any<CancellationToken>()).Returns(Result.Success());
_currentUser.UserId.Returns(Guid.NewGuid());
var handler = new BlockUserCommandHandler(dbContext, _identityService, _gateway, _notifier, _currentUser);
var result = await handler.Handle(new BlockUserCommand(userId), CancellationToken.None);
Assert.True(result.IsSuccess);
await _gateway.DidNotReceive().UpdateClientAsync(
Arg.Any<Node>(), Arg.Any<string>(), Arg.Any<string>(), Arg.Any<VpnProtocol>(),
Arg.Any<string>(), Arg.Any<int>(), Arg.Any<bool>(), Arg.Any<CancellationToken>());
}
}
@@ -0,0 +1,43 @@
using NSubstitute;
using PnvPanel.Application.Admin.Users;
using PnvPanel.Application.Common.Interfaces;
using PnvPanel.Application.Common.Models;
using Xunit;
namespace PnvPanel.Application.Tests.Admin.Users;
public class ChangeUserRoleCommandHandlerTests
{
private readonly IRoleService _roleService = Substitute.For<IRoleService>();
[Fact]
public async Task Handle_DelegatesToRoleServiceAndReturnsSuccess()
{
var userId = Guid.NewGuid();
var roleId = Guid.NewGuid();
_roleService.ChangeUserRoleAsync(userId, roleId, Arg.Any<CancellationToken>()).Returns(Result.Success());
var handler = new ChangeUserRoleCommandHandler(_roleService);
var result = await handler.Handle(new ChangeUserRoleCommand(userId, roleId), CancellationToken.None);
Assert.True(result.IsSuccess);
await _roleService.Received(1).ChangeUserRoleAsync(userId, roleId, Arg.Any<CancellationToken>());
}
[Fact]
public async Task Handle_WhenRoleServiceFails_PropagatesFailure()
{
var userId = Guid.NewGuid();
var roleId = Guid.NewGuid();
var error = UserErrors.NotFound;
_roleService.ChangeUserRoleAsync(userId, roleId, Arg.Any<CancellationToken>()).Returns(Result.Failure(error));
var handler = new ChangeUserRoleCommandHandler(_roleService);
var result = await handler.Handle(new ChangeUserRoleCommand(userId, roleId), CancellationToken.None);
Assert.False(result.IsSuccess);
Assert.Equal(error, result.Error);
}
}
@@ -0,0 +1,71 @@
using NSubstitute;
using PnvPanel.Application.Admin.Users;
using PnvPanel.Application.Common.Interfaces;
using PnvPanel.Application.Common.Models;
using PnvPanel.Application.Tests.TestSupport;
using PnvPanel.Domain.Configs;
using PnvPanel.Domain.Inbounds;
using PnvPanel.Domain.Nodes;
using Xunit;
namespace PnvPanel.Application.Tests.Admin.Users;
public class UnblockUserCommandHandlerTests
{
private readonly IIdentityService _identityService = Substitute.For<IIdentityService>();
private readonly IXuiPanelGateway _gateway = Substitute.For<IXuiPanelGateway>();
private readonly IRealtimeNotifier _notifier = Substitute.For<IRealtimeNotifier>();
private readonly ICurrentUser _currentUser = Substitute.For<ICurrentUser>();
[Fact]
public async Task Handle_WhenUnblockSucceeds_ReEnablesDisabledConfigsAndWritesAudit()
{
using var dbContext = InMemoryDbContextFactory.Create();
var userId = Guid.NewGuid();
var adminId = Guid.NewGuid();
var node = Node.Register("node-1", new Uri("https://node1.example.com"), new NodeCredentials("admin", "protected"), null);
var inbound = Inbound.FromRemote(node.Id, "1", VpnProtocol.Vless, "remark", 443);
var config = VpnConfig.Create(userId, inbound.Id, VpnProtocol.Vless, "my-config", 0);
config.Disable();
dbContext.Nodes.Add(node);
dbContext.Inbounds.Add(inbound);
dbContext.VpnConfigs.Add(config);
await dbContext.SaveChangesAsync(CancellationToken.None);
_currentUser.UserId.Returns(adminId);
_identityService.UnblockUserAsync(userId, Arg.Any<CancellationToken>()).Returns(Result.Success());
var handler = new UnblockUserCommandHandler(dbContext, _identityService, _gateway, _notifier, _currentUser);
var result = await handler.Handle(new UnblockUserCommand(userId), CancellationToken.None);
Assert.True(result.IsSuccess);
Assert.Equal(ConfigStatus.Active, config.Status);
await _gateway.Received(1).UpdateClientAsync(
node, inbound.RemoteInboundId, config.ClientExternalId, config.Protocol,
Arg.Any<string>(), config.DeviceLimit, true, Arg.Any<CancellationToken>());
await _notifier.Received(1).NotifyConfigStatusChangedAsync(userId, config.Id, ConfigStatus.Active, Arg.Any<CancellationToken>());
Assert.Single(dbContext.AuditLogs.Local);
Assert.Equal("UserUnblocked", dbContext.AuditLogs.Local.Single().Action);
}
[Fact]
public async Task Handle_WhenIdentityServiceFails_ReturnsFailureWithoutTouchingConfigs()
{
using var dbContext = InMemoryDbContextFactory.Create();
var userId = Guid.NewGuid();
var error = UserErrors.NotFound;
_identityService.UnblockUserAsync(userId, Arg.Any<CancellationToken>()).Returns(Result.Failure(error));
var handler = new UnblockUserCommandHandler(dbContext, _identityService, _gateway, _notifier, _currentUser);
var result = await handler.Handle(new UnblockUserCommand(userId), CancellationToken.None);
Assert.False(result.IsSuccess);
Assert.Equal(error, result.Error);
Assert.Empty(dbContext.AuditLogs);
}
}