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:
@@ -7,7 +7,8 @@ using PnvPanel.Domain.Activation;
|
||||
|
||||
namespace PnvPanel.Application.Activation;
|
||||
|
||||
public sealed class RequestActivationCommandHandler(IAppDbContext dbContext, ICurrentUser currentUser)
|
||||
public sealed class RequestActivationCommandHandler(
|
||||
IAppDbContext dbContext, IRealtimeNotifier notifier, ITelegramNotifier telegramNotifier, ICurrentUser currentUser)
|
||||
: ICommandHandler<RequestActivationCommand, Result<ActivationRequestDto>>
|
||||
{
|
||||
public async Task<Result<ActivationRequestDto>> Handle(RequestActivationCommand command, CancellationToken cancellationToken)
|
||||
@@ -24,6 +25,11 @@ public sealed class RequestActivationCommandHandler(IAppDbContext dbContext, ICu
|
||||
var request = ActivationRequest.Create(userId, command.Comment);
|
||||
dbContext.ActivationRequests.Add(request);
|
||||
|
||||
var userName = currentUser.UserName ?? userId.ToString();
|
||||
|
||||
await notifier.NotifyActivationRequestedAsync(request.Id, userId, userName, request.Comment, request.CreatedAt, cancellationToken);
|
||||
await telegramNotifier.NotifyAdminsActivationRequestedAsync(request.Id, userName, request.Comment, cancellationToken);
|
||||
|
||||
return Result.Success(new ActivationRequestDto(request.Id, request.Comment, request.CreatedAt));
|
||||
}
|
||||
}
|
||||
|
||||
+8
-2
@@ -8,7 +8,8 @@ using PnvPanel.Domain.Activation;
|
||||
|
||||
namespace PnvPanel.Application.Admin.Activation;
|
||||
|
||||
public sealed class ApproveActivationCommandHandler(IAppDbContext dbContext, IIdentityService identityService, ICurrentUser currentUser)
|
||||
public sealed class ApproveActivationCommandHandler(
|
||||
IAppDbContext dbContext, IIdentityService identityService, IRealtimeNotifier notifier, ICurrentUser currentUser)
|
||||
: ICommandHandler<ApproveActivationCommand, Result>
|
||||
{
|
||||
public async Task<Result> Handle(ApproveActivationCommand command, CancellationToken cancellationToken)
|
||||
@@ -27,6 +28,11 @@ public sealed class ApproveActivationCommandHandler(IAppDbContext dbContext, IId
|
||||
|
||||
request.Approve(adminId);
|
||||
|
||||
return await identityService.ActivateUserAsync(request.UserId, adminId, cancellationToken);
|
||||
var activateResult = await identityService.ActivateUserAsync(request.UserId, adminId, cancellationToken);
|
||||
if (!activateResult.IsSuccess)
|
||||
return activateResult;
|
||||
|
||||
await notifier.NotifyUserActivatedAsync(request.UserId, cancellationToken);
|
||||
return Result.Success();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
using PnvPanel.Domain.Apps;
|
||||
|
||||
namespace PnvPanel.Application.Admin.Apps;
|
||||
|
||||
public sealed record AdminAppDto(
|
||||
Guid Id, string Name, string DownloadUrl, OsPlatform OperatingSystem, string? Description,
|
||||
string? IconUrl, int SortOrder, bool IsEnabled)
|
||||
{
|
||||
public static AdminAppDto FromDomain(ClientApp app) => new(
|
||||
app.Id, app.Name, app.DownloadUrl.ToString(), app.OperatingSystem, app.Description,
|
||||
app.IconUrl, app.SortOrder, app.IsEnabled);
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
using PnvPanel.Application.Common.Models;
|
||||
|
||||
namespace PnvPanel.Application.Admin.Apps;
|
||||
|
||||
public static class AppErrors
|
||||
{
|
||||
public static readonly Error NotFound = Error.NotFound("Apps.NotFound", "Приложение не найдено.");
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
using PnvPanel.Application.Common.Messaging;
|
||||
using PnvPanel.Application.Common.Models;
|
||||
using PnvPanel.Domain.Apps;
|
||||
|
||||
namespace PnvPanel.Application.Admin.Apps;
|
||||
|
||||
public sealed record CreateAppCommand(
|
||||
string Name, string DownloadUrl, OsPlatform OperatingSystem, string? Description, string? IconUrl, int SortOrder)
|
||||
: ICommand<Result<AdminAppDto>>;
|
||||
@@ -0,0 +1,20 @@
|
||||
using PnvPanel.Application.Common.Interfaces;
|
||||
using PnvPanel.Application.Common.Messaging;
|
||||
using PnvPanel.Application.Common.Models;
|
||||
using PnvPanel.Domain.Apps;
|
||||
|
||||
namespace PnvPanel.Application.Admin.Apps;
|
||||
|
||||
public sealed class CreateAppCommandHandler(IAppDbContext dbContext) : ICommandHandler<CreateAppCommand, Result<AdminAppDto>>
|
||||
{
|
||||
public Task<Result<AdminAppDto>> Handle(CreateAppCommand command, CancellationToken cancellationToken)
|
||||
{
|
||||
var app = ClientApp.Create(
|
||||
command.Name, new Uri(command.DownloadUrl, UriKind.Absolute), command.OperatingSystem,
|
||||
command.Description, command.IconUrl, command.SortOrder);
|
||||
|
||||
dbContext.ClientApps.Add(app);
|
||||
|
||||
return Task.FromResult(Result.Success(AdminAppDto.FromDomain(app)));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
using FluentValidation;
|
||||
|
||||
namespace PnvPanel.Application.Admin.Apps;
|
||||
|
||||
public sealed class CreateAppCommandValidator : AbstractValidator<CreateAppCommand>
|
||||
{
|
||||
public CreateAppCommandValidator()
|
||||
{
|
||||
RuleFor(x => x.Name).NotEmpty().MaximumLength(100);
|
||||
RuleFor(x => x.DownloadUrl).NotEmpty().MaximumLength(500);
|
||||
RuleFor(x => x.OperatingSystem).IsInEnum();
|
||||
RuleFor(x => x.Description).MaximumLength(300);
|
||||
RuleFor(x => x.SortOrder).GreaterThanOrEqualTo(0);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
using PnvPanel.Application.Common.Messaging;
|
||||
using PnvPanel.Application.Common.Models;
|
||||
|
||||
namespace PnvPanel.Application.Admin.Apps;
|
||||
|
||||
public sealed record DeleteAppCommand(Guid AppId) : ICommand<Result>;
|
||||
@@ -0,0 +1,19 @@
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using PnvPanel.Application.Common.Interfaces;
|
||||
using PnvPanel.Application.Common.Messaging;
|
||||
using PnvPanel.Application.Common.Models;
|
||||
|
||||
namespace PnvPanel.Application.Admin.Apps;
|
||||
|
||||
public sealed class DeleteAppCommandHandler(IAppDbContext dbContext) : ICommandHandler<DeleteAppCommand, Result>
|
||||
{
|
||||
public async Task<Result> Handle(DeleteAppCommand command, CancellationToken cancellationToken)
|
||||
{
|
||||
var app = await dbContext.ClientApps.FirstOrDefaultAsync(a => a.Id == command.AppId, cancellationToken);
|
||||
if (app is null)
|
||||
return Result.Failure(AppErrors.NotFound);
|
||||
|
||||
dbContext.ClientApps.Remove(app);
|
||||
return Result.Success();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
using PnvPanel.Application.Common.Messaging;
|
||||
using PnvPanel.Application.Common.Models;
|
||||
|
||||
namespace PnvPanel.Application.Admin.Apps;
|
||||
|
||||
public sealed record ListAdminAppsQuery : IQuery<Result<IReadOnlyList<AdminAppDto>>>;
|
||||
@@ -0,0 +1,18 @@
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using PnvPanel.Application.Common.Interfaces;
|
||||
using PnvPanel.Application.Common.Messaging;
|
||||
using PnvPanel.Application.Common.Models;
|
||||
|
||||
namespace PnvPanel.Application.Admin.Apps;
|
||||
|
||||
public sealed class ListAdminAppsQueryHandler(IAppDbContext dbContext) : IQueryHandler<ListAdminAppsQuery, Result<IReadOnlyList<AdminAppDto>>>
|
||||
{
|
||||
public async Task<Result<IReadOnlyList<AdminAppDto>>> Handle(ListAdminAppsQuery query, CancellationToken cancellationToken)
|
||||
{
|
||||
var apps = await dbContext.ClientApps.AsNoTracking()
|
||||
.OrderBy(a => a.OperatingSystem).ThenBy(a => a.SortOrder)
|
||||
.ToListAsync(cancellationToken);
|
||||
|
||||
return Result.Success<IReadOnlyList<AdminAppDto>>(apps.Select(AdminAppDto.FromDomain).ToList());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
using PnvPanel.Application.Common.Messaging;
|
||||
using PnvPanel.Application.Common.Models;
|
||||
using PnvPanel.Domain.Apps;
|
||||
|
||||
namespace PnvPanel.Application.Admin.Apps;
|
||||
|
||||
public sealed record UpdateAppCommand(
|
||||
Guid AppId, string Name, string DownloadUrl, OsPlatform OperatingSystem, string? Description,
|
||||
string? IconUrl, int SortOrder, bool IsEnabled)
|
||||
: ICommand<Result<AdminAppDto>>;
|
||||
@@ -0,0 +1,22 @@
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using PnvPanel.Application.Common.Interfaces;
|
||||
using PnvPanel.Application.Common.Messaging;
|
||||
using PnvPanel.Application.Common.Models;
|
||||
|
||||
namespace PnvPanel.Application.Admin.Apps;
|
||||
|
||||
public sealed class UpdateAppCommandHandler(IAppDbContext dbContext) : ICommandHandler<UpdateAppCommand, Result<AdminAppDto>>
|
||||
{
|
||||
public async Task<Result<AdminAppDto>> Handle(UpdateAppCommand command, CancellationToken cancellationToken)
|
||||
{
|
||||
var app = await dbContext.ClientApps.FirstOrDefaultAsync(a => a.Id == command.AppId, cancellationToken);
|
||||
if (app is null)
|
||||
return Result.Failure<AdminAppDto>(AppErrors.NotFound);
|
||||
|
||||
app.Update(
|
||||
command.Name, new Uri(command.DownloadUrl, UriKind.Absolute), command.OperatingSystem,
|
||||
command.Description, command.IconUrl, command.SortOrder, command.IsEnabled);
|
||||
|
||||
return Result.Success(AdminAppDto.FromDomain(app));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
using FluentValidation;
|
||||
|
||||
namespace PnvPanel.Application.Admin.Apps;
|
||||
|
||||
public sealed class UpdateAppCommandValidator : AbstractValidator<UpdateAppCommand>
|
||||
{
|
||||
public UpdateAppCommandValidator()
|
||||
{
|
||||
RuleFor(x => x.Name).NotEmpty().MaximumLength(100);
|
||||
RuleFor(x => x.DownloadUrl).NotEmpty().MaximumLength(500);
|
||||
RuleFor(x => x.OperatingSystem).IsInEnum();
|
||||
RuleFor(x => x.Description).MaximumLength(300);
|
||||
RuleFor(x => x.SortOrder).GreaterThanOrEqualTo(0);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
using PnvPanel.Application.Common.Messaging;
|
||||
using PnvPanel.Application.Common.Models;
|
||||
using PnvPanel.Domain.Audit;
|
||||
|
||||
namespace PnvPanel.Application.Admin.Audit;
|
||||
|
||||
public sealed record ListAuditLogsQuery(int Page, int PageSize) : IQuery<Result<PagedList<AuditLogDto>>>;
|
||||
|
||||
public sealed record AuditLogDto(
|
||||
long Id, Guid? ActorId, string Action, string TargetType, string TargetId, string? Metadata,
|
||||
AuditSource Source, DateTimeOffset CreatedAt);
|
||||
@@ -0,0 +1,22 @@
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using PnvPanel.Application.Common.Interfaces;
|
||||
using PnvPanel.Application.Common.Messaging;
|
||||
using PnvPanel.Application.Common.Models;
|
||||
|
||||
namespace PnvPanel.Application.Admin.Audit;
|
||||
|
||||
public sealed class ListAuditLogsQueryHandler(IAppDbContext dbContext) : IQueryHandler<ListAuditLogsQuery, Result<PagedList<AuditLogDto>>>
|
||||
{
|
||||
public async Task<Result<PagedList<AuditLogDto>>> Handle(ListAuditLogsQuery query, CancellationToken cancellationToken)
|
||||
{
|
||||
var page = query.Page <= 0 ? 1 : query.Page;
|
||||
var pageSize = query.PageSize is <= 0 or > 200 ? 50 : query.PageSize;
|
||||
|
||||
var result = await dbContext.AuditLogs.AsNoTracking()
|
||||
.OrderByDescending(a => a.CreatedAt)
|
||||
.Select(a => new AuditLogDto(a.Id, a.ActorId, a.Action, a.TargetType, a.TargetId, a.Metadata, a.Source, a.CreatedAt))
|
||||
.ToPagedListAsync(page, pageSize, cancellationToken);
|
||||
|
||||
return Result.Success(result);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
using PnvPanel.Application.Common.Messaging;
|
||||
using PnvPanel.Application.Common.Models;
|
||||
|
||||
namespace PnvPanel.Application.Admin.Stats;
|
||||
|
||||
public sealed record GetStatsQuery : IQuery<Result<StatsDto>>;
|
||||
|
||||
public sealed record StatsDto(
|
||||
int TotalUsers, int ActivatedUsers, int PendingActivationRequests,
|
||||
int TotalNodes, int OnlineNodes, int TotalConfigs, int ActiveConfigs,
|
||||
long TotalUsedUpBytes, long TotalUsedDownBytes);
|
||||
@@ -0,0 +1,37 @@
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using PnvPanel.Application.Common.Interfaces;
|
||||
using PnvPanel.Application.Common.Messaging;
|
||||
using PnvPanel.Application.Common.Models;
|
||||
using PnvPanel.Domain.Activation;
|
||||
using PnvPanel.Domain.Configs;
|
||||
using PnvPanel.Domain.Nodes;
|
||||
|
||||
namespace PnvPanel.Application.Admin.Stats;
|
||||
|
||||
public sealed class GetStatsQueryHandler(IAppDbContext dbContext, IIdentityService identityService)
|
||||
: IQueryHandler<GetStatsQuery, Result<StatsDto>>
|
||||
{
|
||||
public async Task<Result<StatsDto>> Handle(GetStatsQuery query, CancellationToken cancellationToken)
|
||||
{
|
||||
var userStats = await identityService.GetUserStatsAsync(cancellationToken);
|
||||
|
||||
var pendingActivations = await dbContext.ActivationRequests
|
||||
.CountAsync(r => r.Status == ActivationStatus.Pending, cancellationToken);
|
||||
|
||||
var totalNodes = await dbContext.Nodes.CountAsync(cancellationToken);
|
||||
var onlineNodes = await dbContext.Nodes.CountAsync(n => n.Status == NodeStatus.Online, cancellationToken);
|
||||
|
||||
var totalConfigs = await dbContext.VpnConfigs.CountAsync(cancellationToken);
|
||||
var activeConfigs = await dbContext.VpnConfigs.CountAsync(c => c.Status == ConfigStatus.Active, cancellationToken);
|
||||
|
||||
var trafficTotals = await dbContext.VpnConfigs
|
||||
.GroupBy(_ => 1)
|
||||
.Select(g => new { Up = g.Sum(c => c.UsedUpBytes), Down = g.Sum(c => c.UsedDownBytes) })
|
||||
.FirstOrDefaultAsync(cancellationToken);
|
||||
|
||||
return Result.Success(new StatsDto(
|
||||
userStats.Total, userStats.Activated, pendingActivations,
|
||||
totalNodes, onlineNodes, totalConfigs, activeConfigs,
|
||||
trafficTotals?.Up ?? 0, trafficTotals?.Down ?? 0));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
using PnvPanel.Application.Common.Messaging;
|
||||
using PnvPanel.Application.Common.Models;
|
||||
|
||||
namespace PnvPanel.Application.Admin.Users;
|
||||
|
||||
public sealed record BlockUserCommand(Guid UserId) : ICommand<Result>;
|
||||
@@ -0,0 +1,49 @@
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
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, ICurrentUser currentUser)
|
||||
: 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)
|
||||
{
|
||||
await gateway.UpdateClientAsync(
|
||||
node, inbound.RemoteInboundId, config.ClientExternalId, config.Protocol,
|
||||
config.Label ?? config.ClientEmail, config.DeviceLimit, enable: false, cancellationToken);
|
||||
}
|
||||
|
||||
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));
|
||||
|
||||
return Result.Success();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
using PnvPanel.Application.Common.Messaging;
|
||||
using PnvPanel.Application.Common.Models;
|
||||
|
||||
namespace PnvPanel.Application.Admin.Users;
|
||||
|
||||
public sealed record ForceRevokeConfigCommand(Guid ConfigId) : ICommand<Result>;
|
||||
@@ -0,0 +1,40 @@
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using PnvPanel.Application.Common.Interfaces;
|
||||
using PnvPanel.Application.Common.Messaging;
|
||||
using PnvPanel.Application.Common.Models;
|
||||
using PnvPanel.Application.Configs;
|
||||
using PnvPanel.Domain.Audit;
|
||||
using PnvPanel.Domain.Configs;
|
||||
|
||||
namespace PnvPanel.Application.Admin.Users;
|
||||
|
||||
public sealed class ForceRevokeConfigCommandHandler(
|
||||
IAppDbContext dbContext, IXuiPanelGateway gateway, IRealtimeNotifier notifier, ICurrentUser currentUser)
|
||||
: ICommandHandler<ForceRevokeConfigCommand, Result>
|
||||
{
|
||||
public async Task<Result> Handle(ForceRevokeConfigCommand command, CancellationToken cancellationToken)
|
||||
{
|
||||
var config = await dbContext.VpnConfigs.FirstOrDefaultAsync(c => c.Id == command.ConfigId, cancellationToken);
|
||||
if (config is null)
|
||||
return Result.Failure(ConfigErrors.NotFound);
|
||||
|
||||
if (config.Status == ConfigStatus.Revoked)
|
||||
return Result.Success();
|
||||
|
||||
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)
|
||||
await gateway.RemoveClientAsync(node, inbound.RemoteInboundId, config.ClientExternalId, config.Protocol, cancellationToken);
|
||||
|
||||
config.Revoke();
|
||||
await notifier.NotifyConfigStatusChangedAsync(config.UserId, config.Id, config.Status, cancellationToken);
|
||||
|
||||
dbContext.AuditLogs.Add(AuditLog.Create(
|
||||
currentUser.UserId, "ConfigForceRevoked", "VpnConfig", config.Id.ToString(), metadata: null, AuditSource.Web));
|
||||
|
||||
return Result.Success();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
using PnvPanel.Application.Common.Messaging;
|
||||
using PnvPanel.Application.Common.Models;
|
||||
using PnvPanel.Application.Configs;
|
||||
|
||||
namespace PnvPanel.Application.Admin.Users;
|
||||
|
||||
public sealed record GetUserConfigsQuery(Guid UserId) : IQuery<Result<IReadOnlyList<VpnConfigDto>>>;
|
||||
@@ -0,0 +1,24 @@
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using PnvPanel.Application.Common.Interfaces;
|
||||
using PnvPanel.Application.Common.Messaging;
|
||||
using PnvPanel.Application.Common.Models;
|
||||
using PnvPanel.Application.Configs;
|
||||
using PnvPanel.Domain.Configs;
|
||||
|
||||
namespace PnvPanel.Application.Admin.Users;
|
||||
|
||||
public sealed class GetUserConfigsQueryHandler(IAppDbContext dbContext)
|
||||
: IQueryHandler<GetUserConfigsQuery, Result<IReadOnlyList<VpnConfigDto>>>
|
||||
{
|
||||
public async Task<Result<IReadOnlyList<VpnConfigDto>>> Handle(GetUserConfigsQuery query, CancellationToken cancellationToken)
|
||||
{
|
||||
var rows = await dbContext.VpnConfigs.AsNoTracking()
|
||||
.Where(c => c.UserId == query.UserId && c.Status != ConfigStatus.Revoked)
|
||||
.Join(dbContext.Inbounds.AsNoTracking(), c => c.InboundId, i => i.Id, (c, i) => new { Config = c, Inbound = i })
|
||||
.OrderByDescending(x => x.Config.CreatedAt)
|
||||
.ToListAsync(cancellationToken);
|
||||
|
||||
var dtos = rows.Select(x => VpnConfigDto.FromDomain(x.Config, x.Inbound)).ToList();
|
||||
return Result.Success<IReadOnlyList<VpnConfigDto>>(dtos);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
using PnvPanel.Application.Common.Interfaces;
|
||||
using PnvPanel.Application.Common.Messaging;
|
||||
using PnvPanel.Application.Common.Models;
|
||||
|
||||
namespace PnvPanel.Application.Admin.Users;
|
||||
|
||||
public sealed record ListUsersQuery(int Page, int PageSize, string? Search) : IQuery<Result<PagedList<UserSummaryDto>>>;
|
||||
@@ -0,0 +1,18 @@
|
||||
using PnvPanel.Application.Common.Interfaces;
|
||||
using PnvPanel.Application.Common.Messaging;
|
||||
using PnvPanel.Application.Common.Models;
|
||||
|
||||
namespace PnvPanel.Application.Admin.Users;
|
||||
|
||||
public sealed class ListUsersQueryHandler(IIdentityService identityService)
|
||||
: IQueryHandler<ListUsersQuery, Result<PagedList<UserSummaryDto>>>
|
||||
{
|
||||
public async Task<Result<PagedList<UserSummaryDto>>> Handle(ListUsersQuery query, CancellationToken cancellationToken)
|
||||
{
|
||||
var page = query.Page <= 0 ? 1 : query.Page;
|
||||
var pageSize = query.PageSize is <= 0 or > 100 ? 20 : query.PageSize;
|
||||
|
||||
var result = await identityService.ListUsersAsync(page, pageSize, query.Search, cancellationToken);
|
||||
return Result.Success(result);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
using PnvPanel.Application.Common.Messaging;
|
||||
using PnvPanel.Application.Common.Models;
|
||||
|
||||
namespace PnvPanel.Application.Admin.Users;
|
||||
|
||||
public sealed record ResetUserPasswordCommand(Guid UserId, string NewPassword) : ICommand<Result>;
|
||||
@@ -0,0 +1,23 @@
|
||||
using PnvPanel.Application.Common.Interfaces;
|
||||
using PnvPanel.Application.Common.Messaging;
|
||||
using PnvPanel.Application.Common.Models;
|
||||
using PnvPanel.Domain.Audit;
|
||||
|
||||
namespace PnvPanel.Application.Admin.Users;
|
||||
|
||||
public sealed class ResetUserPasswordCommandHandler(IAppDbContext dbContext, IIdentityService identityService, ICurrentUser currentUser)
|
||||
: ICommandHandler<ResetUserPasswordCommand, Result>
|
||||
{
|
||||
public async Task<Result> Handle(ResetUserPasswordCommand command, CancellationToken cancellationToken)
|
||||
{
|
||||
var result = await identityService.ResetPasswordAsync(command.UserId, command.NewPassword, cancellationToken);
|
||||
if (!result.IsSuccess)
|
||||
return result;
|
||||
|
||||
dbContext.AuditLogs.Add(AuditLog.Create(
|
||||
currentUser.UserId, "UserPasswordReset", "User", command.UserId.ToString(), metadata: null, AuditSource.Web));
|
||||
await dbContext.SaveChangesAsync(cancellationToken);
|
||||
|
||||
return Result.Success();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
using PnvPanel.Application.Common.Messaging;
|
||||
using PnvPanel.Application.Common.Models;
|
||||
|
||||
namespace PnvPanel.Application.Admin.Users;
|
||||
|
||||
public sealed record UnblockUserCommand(Guid UserId) : ICommand<Result>;
|
||||
@@ -0,0 +1,49 @@
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
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 только конфиги, погашенные блокировкой (Disabled).</summary>
|
||||
public sealed class UnblockUserCommandHandler(
|
||||
IAppDbContext dbContext, IIdentityService identityService, IXuiPanelGateway gateway,
|
||||
IRealtimeNotifier notifier, ICurrentUser currentUser)
|
||||
: ICommandHandler<UnblockUserCommand, Result>
|
||||
{
|
||||
public async Task<Result> Handle(UnblockUserCommand command, CancellationToken cancellationToken)
|
||||
{
|
||||
var unblockResult = await identityService.UnblockUserAsync(command.UserId, cancellationToken);
|
||||
if (!unblockResult.IsSuccess)
|
||||
return unblockResult;
|
||||
|
||||
var configs = await dbContext.VpnConfigs
|
||||
.Where(c => c.UserId == command.UserId && c.Status == ConfigStatus.Disabled)
|
||||
.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)
|
||||
{
|
||||
await gateway.UpdateClientAsync(
|
||||
node, inbound.RemoteInboundId, config.ClientExternalId, config.Protocol,
|
||||
config.Label ?? config.ClientEmail, config.DeviceLimit, enable: true, cancellationToken);
|
||||
}
|
||||
|
||||
config.Enable();
|
||||
await notifier.NotifyConfigStatusChangedAsync(config.UserId, config.Id, config.Status, cancellationToken);
|
||||
}
|
||||
|
||||
dbContext.AuditLogs.Add(AuditLog.Create(
|
||||
currentUser.UserId, "UserUnblocked", "User", command.UserId.ToString(), metadata: null, AuditSource.Web));
|
||||
|
||||
return Result.Success();
|
||||
}
|
||||
}
|
||||
@@ -18,4 +18,7 @@ public static class AuthErrors
|
||||
|
||||
public static readonly Error Unauthorized =
|
||||
Error.Unauthorized("Auth.Unauthorized", "Требуется аутентификация.");
|
||||
|
||||
public static readonly Error UserBlocked =
|
||||
Error.Forbidden("Auth.UserBlocked", "Аккаунт заблокирован администратором.");
|
||||
}
|
||||
|
||||
@@ -1,3 +1,3 @@
|
||||
namespace PnvPanel.Application.Auth;
|
||||
|
||||
public sealed record CurrentUserDto(Guid Id, string UserName, string Role, bool IsActivated);
|
||||
public sealed record CurrentUserDto(Guid Id, string UserName, string Role, bool IsActivated, bool TelegramLinked);
|
||||
|
||||
@@ -23,7 +23,8 @@ public sealed class LoginCommandHandler(
|
||||
var (accessToken, accessExpiresAt) = jwtTokenService.GenerateAccessToken(user);
|
||||
var refreshToken = await refreshTokenService.IssueAsync(user.Id, cancellationToken);
|
||||
|
||||
var dto = new CurrentUserDto(profile.Id, profile.UserName, profile.Role, profile.IsActivated);
|
||||
var telegramInfo = await identityService.GetTelegramLinkInfoAsync(profile.Id, cancellationToken);
|
||||
var dto = new CurrentUserDto(profile.Id, profile.UserName, profile.Role, profile.IsActivated, telegramInfo.IsLinked);
|
||||
|
||||
return Result.Success(new AuthResult(
|
||||
accessToken,
|
||||
|
||||
@@ -16,6 +16,8 @@ public sealed class GetCurrentUserQueryHandler(IIdentityService identityService,
|
||||
if (profile is null)
|
||||
return Result.Failure<CurrentUserDto>(AuthErrors.Unauthorized);
|
||||
|
||||
return Result.Success(new CurrentUserDto(profile.Id, profile.UserName, profile.Role, profile.IsActivated));
|
||||
var telegramInfo = await identityService.GetTelegramLinkInfoAsync(userId, cancellationToken);
|
||||
|
||||
return Result.Success(new CurrentUserDto(profile.Id, profile.UserName, profile.Role, profile.IsActivated, telegramInfo.IsLinked));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -22,7 +22,8 @@ public sealed class RefreshCommandHandler(
|
||||
var authUser = new AuthenticatedUser(profile.Id, profile.UserName, profile.Role);
|
||||
var (accessToken, accessExpiresAt) = jwtTokenService.GenerateAccessToken(authUser);
|
||||
|
||||
var dto = new CurrentUserDto(profile.Id, profile.UserName, profile.Role, profile.IsActivated);
|
||||
var telegramInfo = await identityService.GetTelegramLinkInfoAsync(profile.Id, cancellationToken);
|
||||
var dto = new CurrentUserDto(profile.Id, profile.UserName, profile.Role, profile.IsActivated, telegramInfo.IsLinked);
|
||||
|
||||
return Result.Success(new AuthResult(
|
||||
accessToken,
|
||||
|
||||
@@ -2,9 +2,11 @@ using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.EntityFrameworkCore.Infrastructure;
|
||||
using PnvPanel.Domain.Activation;
|
||||
using PnvPanel.Domain.Apps;
|
||||
using PnvPanel.Domain.Audit;
|
||||
using PnvPanel.Domain.Configs;
|
||||
using PnvPanel.Domain.Inbounds;
|
||||
using PnvPanel.Domain.Nodes;
|
||||
using PnvPanel.Domain.Telegram;
|
||||
|
||||
namespace PnvPanel.Application.Common.Interfaces;
|
||||
|
||||
@@ -12,12 +14,20 @@ public interface IAppDbContext
|
||||
{
|
||||
DbSet<ActivationRequest> ActivationRequests { get; }
|
||||
|
||||
DbSet<AuditLog> AuditLogs { get; }
|
||||
|
||||
DbSet<TelegramLinkToken> TelegramLinkTokens { get; }
|
||||
|
||||
DbSet<TelegramLoginRequest> TelegramLoginRequests { get; }
|
||||
|
||||
DbSet<Node> Nodes { get; }
|
||||
|
||||
DbSet<Inbound> Inbounds { get; }
|
||||
|
||||
DbSet<VpnConfig> VpnConfigs { get; }
|
||||
|
||||
DbSet<TrafficSample> TrafficSamples { get; }
|
||||
|
||||
DbSet<ClientApp> ClientApps { get; }
|
||||
|
||||
/// <summary>Нужен для advisory-lock при проверке квоты конфигов (см. CreateVpnConfigCommandHandler).</summary>
|
||||
|
||||
@@ -6,3 +6,13 @@ public interface ICurrentUser
|
||||
string? UserName { get; }
|
||||
bool IsAuthenticated { get; }
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Только для фоновых/не-HTTP контекстов (Telegram-бот): задаёт "текущего" пользователя в рамках
|
||||
/// одного DI-scope, чтобы переиспользовать те же команды/запросы, что и веб (которые читают
|
||||
/// ICurrentUser). Реализуется тем же классом, что и ICurrentUser — см. CurrentUser (Infrastructure).
|
||||
/// </summary>
|
||||
public interface ICurrentUserSetter
|
||||
{
|
||||
void SetUser(Guid userId, string userName);
|
||||
}
|
||||
|
||||
@@ -4,7 +4,13 @@ namespace PnvPanel.Application.Common.Interfaces;
|
||||
|
||||
public sealed record AuthenticatedUser(Guid Id, string UserName, string Role);
|
||||
|
||||
public sealed record CurrentUserProfile(Guid Id, string UserName, Guid RoleId, string Role, bool IsActivated, int MaxConfigs);
|
||||
public sealed record CurrentUserProfile(Guid Id, string UserName, Guid RoleId, string Role, bool IsActivated, bool IsBlocked, int MaxConfigs);
|
||||
|
||||
public sealed record UserSummaryDto(Guid Id, string UserName, string Role, bool IsActivated, bool IsBlocked, DateTimeOffset? ActivatedAt);
|
||||
|
||||
public sealed record UserStatsDto(int Total, int Activated);
|
||||
|
||||
public sealed record TelegramLinkInfo(bool IsLinked, long? TelegramUserId, string? Username);
|
||||
|
||||
public interface IIdentityService
|
||||
{
|
||||
@@ -30,4 +36,24 @@ public interface IIdentityService
|
||||
|
||||
/// <summary>Для агрегированной подписки /sub/{userToken} (все активные конфиги пользователя).</summary>
|
||||
Task<Guid?> FindUserIdBySubscriptionTokenAsync(string token, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>Блокировка: вход запрещён (см. ValidateCredentialsAsync). Конфиги гасит вызывающая сторона.</summary>
|
||||
Task<Result> BlockUserAsync(Guid userId, CancellationToken cancellationToken);
|
||||
|
||||
Task<Result> UnblockUserAsync(Guid userId, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>Сброс пароля админом — для пользователей без привязанного Telegram (M7).</summary>
|
||||
Task<Result> ResetPasswordAsync(Guid userId, string newPassword, CancellationToken cancellationToken);
|
||||
|
||||
Task<PagedList<UserSummaryDto>> ListUsersAsync(int page, int pageSize, string? search, CancellationToken cancellationToken);
|
||||
|
||||
Task<UserStatsDto> GetUserStatsAsync(CancellationToken cancellationToken);
|
||||
|
||||
Task<Result> LinkTelegramAsync(Guid userId, long telegramUserId, string? telegramUsername, CancellationToken cancellationToken);
|
||||
|
||||
Task<Result> UnlinkTelegramAsync(Guid userId, CancellationToken cancellationToken);
|
||||
|
||||
Task<Guid?> FindUserIdByTelegramUserIdAsync(long telegramUserId, CancellationToken cancellationToken);
|
||||
|
||||
Task<TelegramLinkInfo> GetTelegramLinkInfoAsync(Guid userId, CancellationToken cancellationToken);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
using PnvPanel.Domain.Configs;
|
||||
using PnvPanel.Domain.Nodes;
|
||||
|
||||
namespace PnvPanel.Application.Common.Interfaces;
|
||||
|
||||
/// <summary>
|
||||
/// Пуш событий через SignalR. Реализация (SignalRRealtimeNotifier) живёт в Api (не в Infrastructure) —
|
||||
/// ей нужен IHubContext<PanelHub>, а Hub, будучи транспортным механизмом, определён в Api;
|
||||
/// Infrastructure не может ссылаться на Api (обратное направление зависимостей).
|
||||
/// </summary>
|
||||
public interface IRealtimeNotifier
|
||||
{
|
||||
Task NotifyConfigTrafficUpdatedAsync(
|
||||
Guid userId, Guid configId, long usedUpBytes, long usedDownBytes, CancellationToken cancellationToken);
|
||||
|
||||
Task NotifyConfigStatusChangedAsync(Guid userId, Guid configId, ConfigStatus status, CancellationToken cancellationToken);
|
||||
|
||||
Task NotifyNodeStatusChangedAsync(Guid nodeId, NodeStatus status, DateTimeOffset? lastSyncAt, CancellationToken cancellationToken);
|
||||
|
||||
Task NotifyActivationRequestedAsync(
|
||||
Guid requestId, Guid userId, string userName, string? comment, DateTimeOffset createdAt, CancellationToken cancellationToken);
|
||||
|
||||
Task NotifyUserActivatedAsync(Guid userId, CancellationToken cancellationToken);
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
namespace PnvPanel.Application.Common.Interfaces;
|
||||
|
||||
/// <summary>
|
||||
/// Проактивные DM-уведомления через бота. Реализация — в Api (нужен ITelegramBotClient,
|
||||
/// который там же и регистрируется), аналогично IRealtimeNotifier/PanelHub. Если BotToken не
|
||||
/// задан — реализация тихо не отправляет ничего (бот работает без Telegram).
|
||||
/// </summary>
|
||||
public interface ITelegramNotifier
|
||||
{
|
||||
Task NotifyAdminsActivationRequestedAsync(
|
||||
Guid requestId, string userName, string? comment, CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>Личное сообщение пользователю, если у него привязан Telegram (иначе no-op).</summary>
|
||||
Task NotifyUserAsync(Guid userId, string message, CancellationToken cancellationToken);
|
||||
}
|
||||
@@ -8,6 +8,8 @@ public sealed record RemoteInboundInfo(string RemoteInboundId, VpnProtocol Proto
|
||||
|
||||
public sealed record NodeProbeResult(bool IsReachable, string? ErrorMessage);
|
||||
|
||||
public sealed record ClientTrafficInfo(long UpBytes, long DownBytes);
|
||||
|
||||
/// <summary>
|
||||
/// Оркестрация панелей 3x-ui через ThreeXui.Net. Один BaseAddress в библиотеке, но нод много —
|
||||
/// реализация держит клиента per-node (кэш по NodeId), см. XuiPanelGateway.
|
||||
@@ -38,4 +40,11 @@ public interface IXuiPanelGateway
|
||||
Task<Result<string>> BuildConnectionStringAsync(
|
||||
Node node, Inbound inbound, string clientExternalId, string clientName, string publicHost,
|
||||
CancellationToken cancellationToken);
|
||||
|
||||
/// <summary>
|
||||
/// Трафик по клиентам инбаунда, ключ — ClientEmail. ThreeXui.Net не даёт типизированного метода
|
||||
/// для этого — извлекается из сырого clientStats[] в RawInboundJson (стандартное поле 3x-ui API).
|
||||
/// </summary>
|
||||
Task<Result<IReadOnlyDictionary<string, ClientTrafficInfo>>> GetClientTrafficAsync(
|
||||
Node node, string inboundRemoteId, CancellationToken cancellationToken);
|
||||
}
|
||||
|
||||
@@ -7,7 +7,8 @@ using PnvPanel.Domain.Configs;
|
||||
|
||||
namespace PnvPanel.Application.Configs.Revoke;
|
||||
|
||||
public sealed class RevokeVpnConfigCommandHandler(IAppDbContext dbContext, IXuiPanelGateway gateway, ICurrentUser currentUser)
|
||||
public sealed class RevokeVpnConfigCommandHandler(
|
||||
IAppDbContext dbContext, IXuiPanelGateway gateway, IRealtimeNotifier notifier, ICurrentUser currentUser)
|
||||
: ICommandHandler<RevokeVpnConfigCommand, Result>
|
||||
{
|
||||
public async Task<Result> Handle(RevokeVpnConfigCommand command, CancellationToken cancellationToken)
|
||||
@@ -32,6 +33,8 @@ public sealed class RevokeVpnConfigCommandHandler(IAppDbContext dbContext, IXuiP
|
||||
await gateway.RemoveClientAsync(node, inbound.RemoteInboundId, config.ClientExternalId, config.Protocol, cancellationToken);
|
||||
|
||||
config.Revoke();
|
||||
await notifier.NotifyConfigStatusChangedAsync(userId, config.Id, config.Status, cancellationToken);
|
||||
|
||||
return Result.Success();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
using PnvPanel.Application.Common.Messaging;
|
||||
using PnvPanel.Application.Common.Models;
|
||||
|
||||
namespace PnvPanel.Application.Telegram.Bot;
|
||||
|
||||
public sealed record ApproveTelegramLoginCommand(Guid RequestId, long TelegramUserId) : ICommand<Result>;
|
||||
@@ -0,0 +1,33 @@
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using PnvPanel.Application.Common.Interfaces;
|
||||
using PnvPanel.Application.Common.Messaging;
|
||||
using PnvPanel.Application.Common.Models;
|
||||
using PnvPanel.Domain.Exceptions;
|
||||
|
||||
namespace PnvPanel.Application.Telegram.Bot;
|
||||
|
||||
public sealed class ApproveTelegramLoginCommandHandler(IAppDbContext dbContext, IIdentityService identityService)
|
||||
: ICommandHandler<ApproveTelegramLoginCommand, Result>
|
||||
{
|
||||
public async Task<Result> Handle(ApproveTelegramLoginCommand command, CancellationToken cancellationToken)
|
||||
{
|
||||
var userId = await identityService.FindUserIdByTelegramUserIdAsync(command.TelegramUserId, cancellationToken);
|
||||
if (userId is null)
|
||||
return Result.Failure(TelegramErrors.NotLinked);
|
||||
|
||||
var request = await dbContext.TelegramLoginRequests.FirstOrDefaultAsync(r => r.Id == command.RequestId, cancellationToken);
|
||||
if (request is null)
|
||||
return Result.Failure(TelegramErrors.LoginRequestNotFound);
|
||||
|
||||
try
|
||||
{
|
||||
request.Approve(userId.Value);
|
||||
}
|
||||
catch (DomainException ex)
|
||||
{
|
||||
return Result.Failure(Error.Conflict("Telegram.LoginRequestInvalid", ex.Message));
|
||||
}
|
||||
|
||||
return Result.Success();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
using PnvPanel.Application.Common.Messaging;
|
||||
using PnvPanel.Application.Common.Models;
|
||||
|
||||
namespace PnvPanel.Application.Telegram.Bot;
|
||||
|
||||
/// <summary>Вызывается только из TelegramBotHostedService (обработка "/start link_<token>").</summary>
|
||||
public sealed record LinkTelegramCommand(string Token, long TelegramUserId, string? TelegramUsername) : ICommand<Result<Guid>>;
|
||||
@@ -0,0 +1,26 @@
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using PnvPanel.Application.Common.Interfaces;
|
||||
using PnvPanel.Application.Common.Messaging;
|
||||
using PnvPanel.Application.Common.Models;
|
||||
|
||||
namespace PnvPanel.Application.Telegram.Bot;
|
||||
|
||||
public sealed class LinkTelegramCommandHandler(IAppDbContext dbContext, IIdentityService identityService)
|
||||
: ICommandHandler<LinkTelegramCommand, Result<Guid>>
|
||||
{
|
||||
public async Task<Result<Guid>> Handle(LinkTelegramCommand command, CancellationToken cancellationToken)
|
||||
{
|
||||
var linkToken = await dbContext.TelegramLinkTokens.FirstOrDefaultAsync(t => t.Token == command.Token, cancellationToken);
|
||||
if (linkToken is null || !linkToken.IsValid)
|
||||
return Result.Failure<Guid>(TelegramErrors.LinkTokenNotFound);
|
||||
|
||||
var linkResult = await identityService.LinkTelegramAsync(
|
||||
linkToken.UserId, command.TelegramUserId, command.TelegramUsername, cancellationToken);
|
||||
if (!linkResult.IsSuccess)
|
||||
return Result.Failure<Guid>(linkResult.Error);
|
||||
|
||||
linkToken.Consume();
|
||||
|
||||
return Result.Success(linkToken.UserId);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
using PnvPanel.Application.Common.Messaging;
|
||||
using PnvPanel.Application.Common.Models;
|
||||
|
||||
namespace PnvPanel.Application.Telegram.Bot;
|
||||
|
||||
public sealed record RejectTelegramLoginCommand(Guid RequestId, long TelegramUserId) : ICommand<Result>;
|
||||
@@ -0,0 +1,33 @@
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using PnvPanel.Application.Common.Interfaces;
|
||||
using PnvPanel.Application.Common.Messaging;
|
||||
using PnvPanel.Application.Common.Models;
|
||||
using PnvPanel.Domain.Exceptions;
|
||||
|
||||
namespace PnvPanel.Application.Telegram.Bot;
|
||||
|
||||
public sealed class RejectTelegramLoginCommandHandler(IAppDbContext dbContext, IIdentityService identityService)
|
||||
: ICommandHandler<RejectTelegramLoginCommand, Result>
|
||||
{
|
||||
public async Task<Result> Handle(RejectTelegramLoginCommand command, CancellationToken cancellationToken)
|
||||
{
|
||||
var userId = await identityService.FindUserIdByTelegramUserIdAsync(command.TelegramUserId, cancellationToken);
|
||||
if (userId is null)
|
||||
return Result.Failure(TelegramErrors.NotLinked);
|
||||
|
||||
var request = await dbContext.TelegramLoginRequests.FirstOrDefaultAsync(r => r.Id == command.RequestId, cancellationToken);
|
||||
if (request is null)
|
||||
return Result.Failure(TelegramErrors.LoginRequestNotFound);
|
||||
|
||||
try
|
||||
{
|
||||
request.Reject();
|
||||
}
|
||||
catch (DomainException ex)
|
||||
{
|
||||
return Result.Failure(Error.Conflict("Telegram.LoginRequestInvalid", ex.Message));
|
||||
}
|
||||
|
||||
return Result.Success();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
using PnvPanel.Application.Common.Messaging;
|
||||
using PnvPanel.Application.Common.Models;
|
||||
|
||||
namespace PnvPanel.Application.Telegram;
|
||||
|
||||
public sealed record CreateLinkTokenCommand : ICommand<Result<LinkTokenDto>>;
|
||||
|
||||
public sealed record LinkTokenDto(string Token, DateTimeOffset ExpiresAt);
|
||||
@@ -0,0 +1,24 @@
|
||||
using PnvPanel.Application.Auth;
|
||||
using PnvPanel.Application.Common.Interfaces;
|
||||
using PnvPanel.Application.Common.Messaging;
|
||||
using PnvPanel.Application.Common.Models;
|
||||
using PnvPanel.Domain.Telegram;
|
||||
|
||||
namespace PnvPanel.Application.Telegram;
|
||||
|
||||
public sealed class CreateLinkTokenCommandHandler(IAppDbContext dbContext, ICurrentUser currentUser)
|
||||
: ICommandHandler<CreateLinkTokenCommand, Result<LinkTokenDto>>
|
||||
{
|
||||
private static readonly TimeSpan Ttl = TimeSpan.FromMinutes(5);
|
||||
|
||||
public Task<Result<LinkTokenDto>> Handle(CreateLinkTokenCommand command, CancellationToken cancellationToken)
|
||||
{
|
||||
if (currentUser.UserId is not { } userId)
|
||||
return Task.FromResult(Result.Failure<LinkTokenDto>(AuthErrors.Unauthorized));
|
||||
|
||||
var token = TelegramLinkToken.Create(userId, Ttl);
|
||||
dbContext.TelegramLinkTokens.Add(token);
|
||||
|
||||
return Task.FromResult(Result.Success(new LinkTokenDto(token.Token, token.ExpiresAt)));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
using PnvPanel.Application.Common.Messaging;
|
||||
using PnvPanel.Application.Common.Models;
|
||||
|
||||
namespace PnvPanel.Application.Telegram;
|
||||
|
||||
/// <summary>Публичная команда (пользователь ещё не залогинен) — начинает passwordless-вход.</summary>
|
||||
public sealed record CreateLoginRequestCommand(string? Context) : ICommand<Result<LoginRequestDto>>;
|
||||
|
||||
public sealed record LoginRequestDto(Guid RequestId, DateTimeOffset ExpiresAt);
|
||||
@@ -0,0 +1,20 @@
|
||||
using PnvPanel.Application.Common.Interfaces;
|
||||
using PnvPanel.Application.Common.Messaging;
|
||||
using PnvPanel.Application.Common.Models;
|
||||
using PnvPanel.Domain.Telegram;
|
||||
|
||||
namespace PnvPanel.Application.Telegram;
|
||||
|
||||
public sealed class CreateLoginRequestCommandHandler(IAppDbContext dbContext)
|
||||
: ICommandHandler<CreateLoginRequestCommand, Result<LoginRequestDto>>
|
||||
{
|
||||
private static readonly TimeSpan Ttl = TimeSpan.FromMinutes(5);
|
||||
|
||||
public Task<Result<LoginRequestDto>> Handle(CreateLoginRequestCommand command, CancellationToken cancellationToken)
|
||||
{
|
||||
var request = TelegramLoginRequest.Create(Ttl, command.Context);
|
||||
dbContext.TelegramLoginRequests.Add(request);
|
||||
|
||||
return Task.FromResult(Result.Success(new LoginRequestDto(request.Id, request.ExpiresAt)));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
using PnvPanel.Application.Auth;
|
||||
using PnvPanel.Application.Common.Messaging;
|
||||
using PnvPanel.Application.Common.Models;
|
||||
using PnvPanel.Domain.Telegram;
|
||||
|
||||
namespace PnvPanel.Application.Telegram;
|
||||
|
||||
public sealed record GetLoginRequestStatusQuery(Guid RequestId) : IQuery<Result<LoginRequestStatusDto>>;
|
||||
|
||||
public sealed record LoginRequestStatusDto(TelegramLoginStatus Status, AuthResult? Auth);
|
||||
@@ -0,0 +1,48 @@
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using PnvPanel.Application.Auth;
|
||||
using PnvPanel.Application.Common.Interfaces;
|
||||
using PnvPanel.Application.Common.Messaging;
|
||||
using PnvPanel.Application.Common.Models;
|
||||
using PnvPanel.Domain.Telegram;
|
||||
|
||||
namespace PnvPanel.Application.Telegram;
|
||||
|
||||
/// <summary>
|
||||
/// Формально Query, но при первом наблюдении Approved-статуса атомарно "забирает" вход:
|
||||
/// выпускает JWT и переводит запрос в Consumed (одноразовый claim), см. api-design.md.
|
||||
/// Осознанное отступление от чистого CQRS ради простого поллинга без отдельного claim-эндпоинта.
|
||||
/// </summary>
|
||||
public sealed class GetLoginRequestStatusQueryHandler(
|
||||
IAppDbContext dbContext, IIdentityService identityService, IJwtTokenService jwtTokenService, IRefreshTokenService refreshTokenService)
|
||||
: IQueryHandler<GetLoginRequestStatusQuery, Result<LoginRequestStatusDto>>
|
||||
{
|
||||
public async Task<Result<LoginRequestStatusDto>> Handle(GetLoginRequestStatusQuery query, CancellationToken cancellationToken)
|
||||
{
|
||||
var request = await dbContext.TelegramLoginRequests.FirstOrDefaultAsync(r => r.Id == query.RequestId, cancellationToken);
|
||||
if (request is null)
|
||||
return Result.Failure<LoginRequestStatusDto>(TelegramErrors.LoginRequestNotFound);
|
||||
|
||||
if (request.Status == TelegramLoginStatus.Pending && request.IsExpired)
|
||||
return Result.Success(new LoginRequestStatusDto(TelegramLoginStatus.Expired, null));
|
||||
|
||||
if (request.Status != TelegramLoginStatus.Approved)
|
||||
return Result.Success(new LoginRequestStatusDto(request.Status, null));
|
||||
|
||||
var profile = await identityService.GetProfileAsync(request.UserId!.Value, cancellationToken);
|
||||
if (profile is null)
|
||||
return Result.Failure<LoginRequestStatusDto>(AuthErrors.Unauthorized);
|
||||
|
||||
var authUser = new AuthenticatedUser(profile.Id, profile.UserName, profile.Role);
|
||||
var (accessToken, accessExpiresAt) = jwtTokenService.GenerateAccessToken(authUser);
|
||||
|
||||
request.Consume();
|
||||
// IssueAsync сохраняет весь SaveChanges (в т.ч. Consume() выше) — см. RefreshTokenService.
|
||||
var refreshToken = await refreshTokenService.IssueAsync(profile.Id, cancellationToken);
|
||||
|
||||
// Пользователь только что подтвердил вход через бота — Telegram точно привязан.
|
||||
var dto = new CurrentUserDto(profile.Id, profile.UserName, profile.Role, profile.IsActivated, TelegramLinked: true);
|
||||
var auth = new AuthResult(accessToken, accessExpiresAt, refreshToken.RawToken, refreshToken.ExpiresAt, dto);
|
||||
|
||||
return Result.Success(new LoginRequestStatusDto(TelegramLoginStatus.Approved, auth));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
using PnvPanel.Application.Common.Models;
|
||||
|
||||
namespace PnvPanel.Application.Telegram;
|
||||
|
||||
public static class TelegramErrors
|
||||
{
|
||||
public static readonly Error LinkTokenNotFound =
|
||||
Error.NotFound("Telegram.LinkTokenNotFound", "Токен привязки не найден или истёк.");
|
||||
|
||||
public static readonly Error LoginRequestNotFound =
|
||||
Error.NotFound("Telegram.LoginRequestNotFound", "Запрос на вход не найден.");
|
||||
|
||||
public static readonly Error NotLinked =
|
||||
Error.Conflict("Telegram.NotLinked", "Telegram не привязан ни к одному аккаунту.");
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
using PnvPanel.Application.Common.Messaging;
|
||||
using PnvPanel.Application.Common.Models;
|
||||
|
||||
namespace PnvPanel.Application.Telegram;
|
||||
|
||||
public sealed record UnlinkTelegramCommand : ICommand<Result>;
|
||||
@@ -0,0 +1,18 @@
|
||||
using PnvPanel.Application.Auth;
|
||||
using PnvPanel.Application.Common.Interfaces;
|
||||
using PnvPanel.Application.Common.Messaging;
|
||||
using PnvPanel.Application.Common.Models;
|
||||
|
||||
namespace PnvPanel.Application.Telegram;
|
||||
|
||||
public sealed class UnlinkTelegramCommandHandler(IIdentityService identityService, ICurrentUser currentUser)
|
||||
: ICommandHandler<UnlinkTelegramCommand, Result>
|
||||
{
|
||||
public Task<Result> Handle(UnlinkTelegramCommand command, CancellationToken cancellationToken)
|
||||
{
|
||||
if (currentUser.UserId is not { } userId)
|
||||
return Task.FromResult(Result.Failure(AuthErrors.Unauthorized));
|
||||
|
||||
return identityService.UnlinkTelegramAsync(userId, cancellationToken);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user