Add admin configs endpoint and related UI components
- Introduced a new endpoint to list all admin configs, enhancing the admin interface for better management. - Updated API documentation to include the new `/configs` endpoint with pagination and search capabilities. - Added routing and UI elements for the configs section in the admin panel, improving navigation and accessibility. - Enhanced localization for the configs feature in both Russian and English, ensuring a user-friendly experience.
This commit is contained in:
@@ -1,9 +1,11 @@
|
||||
using PnvPanel.Api.Common;
|
||||
using PnvPanel.Application.Admin.Configs;
|
||||
using PnvPanel.Application.Admin.Users;
|
||||
using PnvPanel.Application.Common.Interfaces;
|
||||
using PnvPanel.Application.Common.Messaging;
|
||||
using PnvPanel.Application.Common.Models;
|
||||
using PnvPanel.Application.Configs;
|
||||
using PnvPanel.Domain.Configs;
|
||||
using PnvPanel.Infrastructure.Identity;
|
||||
|
||||
namespace PnvPanel.Api.Endpoints;
|
||||
@@ -22,6 +24,7 @@ public static class AdminUserEndpoints
|
||||
admin.MapPost("/users/{id:guid}/reset-password", ResetPassword).Produces(StatusCodes.Status204NoContent);
|
||||
admin.MapDelete("/users/{id:guid}", DeleteUser).Produces(StatusCodes.Status204NoContent);
|
||||
admin.MapGet("/users/{id:guid}/configs", GetUserConfigs).Produces<IReadOnlyList<VpnConfigDto>>();
|
||||
admin.MapGet("/configs", ListAllConfigs).Produces<PagedList<AdminVpnConfigDto>>();
|
||||
admin.MapDelete("/configs/{id:guid}", ForceRevokeConfig).Produces(StatusCodes.Status204NoContent);
|
||||
|
||||
return app;
|
||||
@@ -65,6 +68,14 @@ public static class AdminUserEndpoints
|
||||
return result.ToHttpResult();
|
||||
}
|
||||
|
||||
private static async Task<IResult> ListAllConfigs(
|
||||
int page, int pageSize, string? search, ConfigStatus? status, ISender sender, CancellationToken cancellationToken)
|
||||
{
|
||||
var query = new ListAllConfigsQuery(page <= 0 ? 1 : page, pageSize <= 0 ? 20 : pageSize, search, status);
|
||||
var result = await sender.Send(query, cancellationToken);
|
||||
return result.ToHttpResult();
|
||||
}
|
||||
|
||||
private static async Task<IResult> ForceRevokeConfig(Guid id, ISender sender, CancellationToken cancellationToken)
|
||||
{
|
||||
var result = await sender.Send(new ForceRevokeConfigCommand(id), cancellationToken);
|
||||
|
||||
@@ -0,0 +1,11 @@
|
||||
using PnvPanel.Domain.Configs;
|
||||
using PnvPanel.Domain.Inbounds;
|
||||
|
||||
namespace PnvPanel.Application.Admin.Configs;
|
||||
|
||||
/// <summary>Строка глобального списка конфигов для админа — в отличие от VpnConfigDto (self-service)
|
||||
/// содержит владельца и ноду, т.к. список не скоупится одним пользователем.</summary>
|
||||
public sealed record AdminVpnConfigDto(
|
||||
Guid Id, Guid UserId, string UserName, string? Label, string ClientEmail, VpnProtocol Protocol,
|
||||
string Location, string NodeName, long UsedUpBytes, long UsedDownBytes, DateTimeOffset? ExpiresAt,
|
||||
ConfigStatus Status, DateTimeOffset CreatedAt);
|
||||
@@ -0,0 +1,11 @@
|
||||
using PnvPanel.Application.Common.Interfaces;
|
||||
using PnvPanel.Application.Common.Messaging;
|
||||
using PnvPanel.Application.Common.Models;
|
||||
using PnvPanel.Domain.Configs;
|
||||
|
||||
namespace PnvPanel.Application.Admin.Configs;
|
||||
|
||||
/// <summary><paramref name="Search"/> матчится по ClientEmail/Label — это то, по чему админ сверяет
|
||||
/// конфиг с записью в 3x-ui, а не по владельцу (для поиска по пользователю есть /admin/users).</summary>
|
||||
public sealed record ListAllConfigsQuery(int Page, int PageSize, string? Search, ConfigStatus? Status)
|
||||
: IQuery<Result<PagedList<AdminVpnConfigDto>>>;
|
||||
@@ -0,0 +1,58 @@
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using PnvPanel.Application.Common.Interfaces;
|
||||
using PnvPanel.Application.Common.Messaging;
|
||||
using PnvPanel.Application.Common.Models;
|
||||
|
||||
namespace PnvPanel.Application.Admin.Configs;
|
||||
|
||||
public sealed class ListAllConfigsQueryHandler(IAppDbContext dbContext, IIdentityService identityService)
|
||||
: IQueryHandler<ListAllConfigsQuery, Result<PagedList<AdminVpnConfigDto>>>
|
||||
{
|
||||
public async Task<Result<PagedList<AdminVpnConfigDto>>> Handle(ListAllConfigsQuery query, CancellationToken cancellationToken)
|
||||
{
|
||||
var page = query.Page <= 0 ? 1 : query.Page;
|
||||
var pageSize = query.PageSize is <= 0 or > 100 ? 20 : query.PageSize;
|
||||
|
||||
var configsQuery = dbContext.VpnConfigs.AsNoTracking();
|
||||
|
||||
if (query.Status is { } status)
|
||||
configsQuery = configsQuery.Where(c => c.Status == status);
|
||||
|
||||
if (!string.IsNullOrWhiteSpace(query.Search))
|
||||
{
|
||||
var search = query.Search.Trim();
|
||||
configsQuery = configsQuery.Where(c => c.ClientEmail.Contains(search) || (c.Label != null && c.Label.Contains(search)));
|
||||
}
|
||||
|
||||
var pageResult = await configsQuery
|
||||
.OrderByDescending(c => c.CreatedAt)
|
||||
.ToPagedListAsync(page, pageSize, cancellationToken);
|
||||
|
||||
var inboundIds = pageResult.Items.Select(c => c.InboundId).Distinct().ToList();
|
||||
var inbounds = (await dbContext.Inbounds.AsNoTracking()
|
||||
.Where(i => inboundIds.Contains(i.Id))
|
||||
.ToListAsync(cancellationToken))
|
||||
.ToDictionary(i => i.Id);
|
||||
|
||||
var nodeIds = inbounds.Values.Select(i => i.NodeId).Distinct().ToList();
|
||||
var nodes = (await dbContext.Nodes.AsNoTracking()
|
||||
.Where(n => nodeIds.Contains(n.Id))
|
||||
.ToListAsync(cancellationToken))
|
||||
.ToDictionary(n => n.Id);
|
||||
|
||||
var userNames = await identityService.GetUserNamesAsync(
|
||||
pageResult.Items.Select(c => c.UserId).Distinct().ToList(), cancellationToken);
|
||||
|
||||
var items = pageResult.Items.Select(c =>
|
||||
{
|
||||
var inbound = inbounds.GetValueOrDefault(c.InboundId);
|
||||
var node = inbound is null ? null : nodes.GetValueOrDefault(inbound.NodeId);
|
||||
return new AdminVpnConfigDto(
|
||||
c.Id, c.UserId, userNames.GetValueOrDefault(c.UserId, "?"), c.Label, c.ClientEmail, c.Protocol,
|
||||
inbound?.DisplayName ?? inbound?.Remark ?? "?", node?.Name ?? "?",
|
||||
c.UsedUpBytes, c.UsedDownBytes, c.ExpiresAt, c.Status, c.CreatedAt);
|
||||
}).ToList();
|
||||
|
||||
return Result.Success(new PagedList<AdminVpnConfigDto>(items, pageResult.Total, pageResult.Page, pageResult.PageSize));
|
||||
}
|
||||
}
|
||||
+105
@@ -0,0 +1,105 @@
|
||||
using NSubstitute;
|
||||
using PnvPanel.Application.Admin.Configs;
|
||||
using PnvPanel.Application.Common.Interfaces;
|
||||
using PnvPanel.Application.Tests.TestSupport;
|
||||
using PnvPanel.Domain.Configs;
|
||||
using PnvPanel.Domain.Inbounds;
|
||||
using PnvPanel.Domain.Nodes;
|
||||
using Xunit;
|
||||
|
||||
namespace PnvPanel.Application.Tests.Admin.Configs;
|
||||
|
||||
public class ListAllConfigsQueryHandlerTests
|
||||
{
|
||||
private readonly IIdentityService _identityService = Substitute.For<IIdentityService>();
|
||||
|
||||
[Fact]
|
||||
public async Task Handle_ReturnsConfigsAcrossUsersWithOwnerNodeAndUserName()
|
||||
{
|
||||
using var dbContext = InMemoryDbContextFactory.Create();
|
||||
var userId = 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);
|
||||
inbound.Publish("Germany", [], null);
|
||||
var config = VpnConfig.Create(userId, inbound.Id, VpnProtocol.Vless, "my-config");
|
||||
|
||||
dbContext.Nodes.Add(node);
|
||||
dbContext.Inbounds.Add(inbound);
|
||||
dbContext.VpnConfigs.Add(config);
|
||||
await dbContext.SaveChangesAsync(CancellationToken.None);
|
||||
|
||||
_identityService.GetUserNamesAsync(Arg.Any<IReadOnlyCollection<Guid>>(), Arg.Any<CancellationToken>())
|
||||
.Returns(new Dictionary<Guid, string> { [userId] = "alice" });
|
||||
|
||||
var handler = new ListAllConfigsQueryHandler(dbContext, _identityService);
|
||||
|
||||
var result = await handler.Handle(new ListAllConfigsQuery(1, 20, Search: null, Status: null), CancellationToken.None);
|
||||
|
||||
Assert.True(result.IsSuccess);
|
||||
var item = Assert.Single(result.Value.Items);
|
||||
Assert.Equal(config.Id, item.Id);
|
||||
Assert.Equal(userId, item.UserId);
|
||||
Assert.Equal("alice", item.UserName);
|
||||
Assert.Equal("node-1", item.NodeName);
|
||||
Assert.Equal("Germany", item.Location);
|
||||
Assert.Equal(1, result.Value.Total);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Handle_FiltersBySearchAcrossClientEmailAndLabel()
|
||||
{
|
||||
using var dbContext = InMemoryDbContextFactory.Create();
|
||||
var userId = 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 matching = VpnConfig.Create(userId, inbound.Id, VpnProtocol.Vless, "phone-config");
|
||||
var other = VpnConfig.Create(userId, inbound.Id, VpnProtocol.Vless, "laptop-config");
|
||||
|
||||
dbContext.Nodes.Add(node);
|
||||
dbContext.Inbounds.Add(inbound);
|
||||
dbContext.VpnConfigs.AddRange(matching, other);
|
||||
await dbContext.SaveChangesAsync(CancellationToken.None);
|
||||
|
||||
_identityService.GetUserNamesAsync(Arg.Any<IReadOnlyCollection<Guid>>(), Arg.Any<CancellationToken>())
|
||||
.Returns(new Dictionary<Guid, string> { [userId] = "alice" });
|
||||
|
||||
var handler = new ListAllConfigsQueryHandler(dbContext, _identityService);
|
||||
|
||||
var result = await handler.Handle(new ListAllConfigsQuery(1, 20, Search: "phone", Status: null), CancellationToken.None);
|
||||
|
||||
Assert.True(result.IsSuccess);
|
||||
var item = Assert.Single(result.Value.Items);
|
||||
Assert.Equal(matching.Id, item.Id);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task Handle_FiltersByStatus()
|
||||
{
|
||||
using var dbContext = InMemoryDbContextFactory.Create();
|
||||
var userId = 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 active = VpnConfig.Create(userId, inbound.Id, VpnProtocol.Vless, "active-config");
|
||||
var revoked = VpnConfig.Create(userId, inbound.Id, VpnProtocol.Vless, "revoked-config");
|
||||
revoked.Revoke();
|
||||
|
||||
dbContext.Nodes.Add(node);
|
||||
dbContext.Inbounds.Add(inbound);
|
||||
dbContext.VpnConfigs.AddRange(active, revoked);
|
||||
await dbContext.SaveChangesAsync(CancellationToken.None);
|
||||
|
||||
_identityService.GetUserNamesAsync(Arg.Any<IReadOnlyCollection<Guid>>(), Arg.Any<CancellationToken>())
|
||||
.Returns(new Dictionary<Guid, string> { [userId] = "alice" });
|
||||
|
||||
var handler = new ListAllConfigsQueryHandler(dbContext, _identityService);
|
||||
|
||||
var result = await handler.Handle(new ListAllConfigsQuery(1, 20, Search: null, Status: ConfigStatus.Revoked), CancellationToken.None);
|
||||
|
||||
Assert.True(result.IsSuccess);
|
||||
var item = Assert.Single(result.Value.Items);
|
||||
Assert.Equal(revoked.Id, item.Id);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user