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,84 @@
using System.Net;
using System.Net.Http.Json;
using PnvPanel.IntegrationTests.TestSupport;
using Xunit;
namespace PnvPanel.IntegrationTests.Auth;
[Collection(IntegrationTestCollection.Name)]
public class AuthFlowTests(PnvPanelWebApplicationFactory factory)
{
private sealed record RegisterResponse(Guid Id, string UserName);
private sealed record CurrentUserResponse(Guid Id, string UserName, string Role, bool IsActivated, bool TelegramLinked);
private sealed record LoginResponse(string AccessToken, DateTimeOffset ExpiresAt, CurrentUserResponse User);
[Fact]
public async Task RegisterLoginMeRefreshLogout_FullFlow_Succeeds()
{
using var client = factory.CreateClient();
var userName = $"alice_{Guid.NewGuid():N}"[..20];
const string password = "P@ssw0rd123";
var registerResponse = await client.PostJsonAsync("/api/auth/register", new { userName, password });
Assert.Equal(HttpStatusCode.OK, registerResponse.StatusCode);
var registered = await registerResponse.ReadAsAsync<RegisterResponse>();
Assert.NotNull(registered);
Assert.Equal(userName, registered!.UserName);
var loginResponse = await client.PostJsonAsync("/api/auth/login", new { userName, password });
Assert.Equal(HttpStatusCode.OK, loginResponse.StatusCode);
var login = await loginResponse.ReadAsAsync<LoginResponse>();
Assert.NotNull(login);
Assert.False(login!.User.IsActivated);
Assert.False(login.User.TelegramLinked);
Assert.Equal("user", login.User.Role);
client.UseBearerToken(login.AccessToken);
var meResponse = await client.GetAsync("/api/auth/me");
Assert.Equal(HttpStatusCode.OK, meResponse.StatusCode);
var me = await meResponse.ReadAsAsync<CurrentUserResponse>();
Assert.Equal(userName, me!.UserName);
var refreshResponse = await client.PostAsync("/api/auth/refresh", content: null);
Assert.Equal(HttpStatusCode.OK, refreshResponse.StatusCode);
var refreshed = await refreshResponse.ReadAsAsync<LoginResponse>();
Assert.NotNull(refreshed);
Assert.NotEqual(login.AccessToken, refreshed!.AccessToken);
var logoutResponse = await client.PostAsync("/api/auth/logout", content: null);
Assert.Equal(HttpStatusCode.NoContent, logoutResponse.StatusCode);
// Использованный refresh-токен отозван при logout — повторный refresh должен провалиться.
var refreshAfterLogout = await client.PostAsync("/api/auth/refresh", content: null);
Assert.Equal(HttpStatusCode.Unauthorized, refreshAfterLogout.StatusCode);
}
[Fact]
public async Task Login_WithWrongPassword_ReturnsUnauthorized()
{
using var client = factory.CreateClient();
var userName = $"bob_{Guid.NewGuid():N}"[..20];
await client.PostJsonAsync("/api/auth/register", new { userName, password = "CorrectPassword123" });
var loginResponse = await client.PostJsonAsync("/api/auth/login", new { userName, password = "WrongPassword123" });
Assert.Equal(HttpStatusCode.Unauthorized, loginResponse.StatusCode);
}
[Fact]
public async Task Register_WithDuplicateUserName_ReturnsConflict()
{
using var client = factory.CreateClient();
var userName = $"carol_{Guid.NewGuid():N}"[..20];
var first = await client.PostJsonAsync("/api/auth/register", new { userName, password = "P@ssw0rd123" });
Assert.Equal(HttpStatusCode.OK, first.StatusCode);
var second = await client.PostJsonAsync("/api/auth/register", new { userName, password = "AnotherPass123" });
Assert.Equal(HttpStatusCode.Conflict, second.StatusCode);
}
}
@@ -0,0 +1,28 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<IsPackable>false</IsPackable>
<TreatWarningsAsErrors>false</TreatWarningsAsErrors>
<EnforceCodeStyleInBuild>false</EnforceCodeStyleInBuild>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" />
<PackageReference Include="xunit" />
<PackageReference Include="xunit.runner.visualstudio">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="NSubstitute" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" />
<PackageReference Include="Testcontainers.PostgreSql" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\src\PnvPanel.Api\PnvPanel.Api.csproj" />
</ItemGroup>
</Project>
@@ -0,0 +1,33 @@
using System.Net.Http.Json;
namespace PnvPanel.IntegrationTests.TestSupport;
public static class AuthTestHelper
{
public sealed record CurrentUserResponse(Guid Id, string UserName, string Role, bool IsActivated, bool TelegramLinked);
public sealed record LoginResponse(string AccessToken, DateTimeOffset ExpiresAt, CurrentUserResponse User);
public static async Task<(Guid Id, string AccessToken)> RegisterAndLoginAsync(HttpClient client, string userName, string password)
{
var registerResponse = await client.PostJsonAsync("/api/auth/register", new { userName, password });
registerResponse.EnsureSuccessStatusCode();
var (id, accessToken) = await LoginAsync(client, userName, password);
return (id, accessToken);
}
public static async Task<(Guid Id, string AccessToken)> LoginAsync(HttpClient client, string userName, string password)
{
var loginResponse = await client.PostJsonAsync("/api/auth/login", new { userName, password });
loginResponse.EnsureSuccessStatusCode();
var login = await loginResponse.ReadAsAsync<LoginResponse>();
return (login!.User.Id, login.AccessToken);
}
public static async Task<string> LoginAsAdminAsync(HttpClient client)
{
var (_, accessToken) = await LoginAsync(client, PnvPanelWebApplicationFactory.AdminUserName, PnvPanelWebApplicationFactory.AdminPassword);
return accessToken;
}
}
@@ -0,0 +1,57 @@
using PnvPanel.Application.Common.Interfaces;
using PnvPanel.Application.Common.Models;
using PnvPanel.Domain.Inbounds;
using PnvPanel.Domain.Nodes;
namespace PnvPanel.IntegrationTests.TestSupport;
/// <summary>
/// Заглушка 3x-ui для интеграционных тестов — реальной панели нет. Возвращает успех для проб/CRUD
/// клиентов, отдаёт один синтетический inbound на ноду для сценариев с SyncNode.
/// </summary>
public sealed class FakeXuiPanelGateway : IXuiPanelGateway
{
public Result ValidateBaseAddress(Uri baseAddress) => Result.Success();
public Task<NodeProbeResult> ProbeAsync(Node node, CancellationToken cancellationToken)
=> Task.FromResult(new NodeProbeResult(true, null));
public Task<Result<IReadOnlyList<RemoteInboundInfo>>> ListInboundsAsync(Node node, CancellationToken cancellationToken)
{
IReadOnlyList<RemoteInboundInfo> inbounds =
[
new RemoteInboundInfo("1", VpnProtocol.Vless, "Test inbound", 443),
];
return Task.FromResult(Result.Success(inbounds));
}
public void InvalidateClient(Guid nodeId)
{
}
public Task<Result<string>> AddClientAsync(
Node node, string inboundRemoteId, VpnProtocol protocol, string clientEmail, string clientName,
int deviceLimit, CancellationToken cancellationToken)
=> Task.FromResult(Result.Success(Guid.NewGuid().ToString()));
public Task<Result> RemoveClientAsync(
Node node, string inboundRemoteId, string clientExternalId, VpnProtocol protocol, CancellationToken cancellationToken)
=> Task.FromResult(Result.Success());
public Task<Result> UpdateClientAsync(
Node node, string inboundRemoteId, string clientExternalId, VpnProtocol protocol,
string name, int deviceLimit, bool enable, CancellationToken cancellationToken)
=> Task.FromResult(Result.Success());
public Task<Result<string>> BuildConnectionStringAsync(
Node node, Inbound inbound, string clientExternalId, string clientName, string publicHost, CancellationToken cancellationToken)
=> Task.FromResult(Result.Success("vless://fake-connection-string"));
public Task<Result<IReadOnlyDictionary<string, ClientTrafficInfo>>> GetClientTrafficAsync(
Node node, string inboundRemoteId, CancellationToken cancellationToken)
{
IReadOnlyDictionary<string, ClientTrafficInfo> traffic = new Dictionary<string, ClientTrafficInfo>();
return Task.FromResult(Result.Success(traffic));
}
}
@@ -0,0 +1,19 @@
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Text.Json;
namespace PnvPanel.IntegrationTests.TestSupport;
public static class HttpClientJsonExtensions
{
public static readonly JsonSerializerOptions JsonOptions = new(JsonSerializerDefaults.Web);
public static void UseBearerToken(this HttpClient client, string accessToken)
=> client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
public static async Task<T?> ReadAsAsync<T>(this HttpResponseMessage response)
=> await response.Content.ReadFromJsonAsync<T>(JsonOptions);
public static Task<HttpResponseMessage> PostJsonAsync(this HttpClient client, string url, object body)
=> client.PostAsJsonAsync(url, body, JsonOptions);
}
@@ -0,0 +1,9 @@
using Xunit;
namespace PnvPanel.IntegrationTests.TestSupport;
[CollectionDefinition(Name)]
public sealed class IntegrationTestCollection : ICollectionFixture<PnvPanelWebApplicationFactory>
{
public const string Name = "Integration";
}
@@ -0,0 +1,61 @@
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.DependencyInjection.Extensions;
using PnvPanel.Application.Common.Interfaces;
using Testcontainers.PostgreSql;
using Xunit;
namespace PnvPanel.IntegrationTests.TestSupport;
/// <summary>
/// Реальный Postgres через Testcontainers (не InMemory/Sqlite — нужно проверить Postgres-специфичное
/// поведение: pg_advisory_xact_lock для квоты конфигов, uuid[]/jsonb колонки). Program.cs сам
/// применяет миграции и сидит роли/админа при старте хоста — свежий контейнер становится полностью
/// готовой БД без ручных шагов.
/// </summary>
public sealed class PnvPanelWebApplicationFactory : WebApplicationFactory<Program>, IAsyncLifetime
{
public const string AdminUserName = "test-admin";
public const string AdminPassword = "TestAdmin123!";
private readonly PostgreSqlContainer _postgres = new PostgreSqlBuilder()
.WithImage("postgres:17-alpine")
.WithDatabase("pnvpanel")
.WithUsername("pnvpanel")
.WithPassword("pnvpanel")
.Build();
public async Task InitializeAsync() => await _postgres.StartAsync();
async Task IAsyncLifetime.DisposeAsync()
{
await _postgres.StopAsync();
await base.DisposeAsync();
}
protected override void ConfigureWebHost(IWebHostBuilder builder)
{
builder.UseEnvironment("Development");
builder.ConfigureAppConfiguration((_, config) =>
{
config.AddInMemoryCollection(new Dictionary<string, string?>
{
["ConnectionStrings:Default"] = _postgres.GetConnectionString(),
["AdminSeed:Username"] = AdminUserName,
["AdminSeed:Password"] = AdminPassword,
// Пусто — TelegramBotHostedService при пустом токене не стартует (см. Api/Telegram/TelegramBotHostedService.cs).
["Telegram:BotToken"] = "",
});
});
builder.ConfigureServices(services =>
{
// Реальной панели 3x-ui в тестах нет — подменяем гейтвей заглушкой.
services.RemoveAll<IXuiPanelGateway>();
services.AddSingleton<IXuiPanelGateway, FakeXuiPanelGateway>();
});
}
}