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:
@@ -0,0 +1,33 @@
|
||||
namespace PnvPanel.Domain.Audit;
|
||||
|
||||
/// <summary>Append-only журнал значимых действий. Id — long (не Guid), см. TrafficSample.</summary>
|
||||
public sealed class AuditLog
|
||||
{
|
||||
public long Id { get; private set; }
|
||||
public Guid? ActorId { get; private set; }
|
||||
public string Action { get; private set; } = string.Empty;
|
||||
public string TargetType { get; private set; } = string.Empty;
|
||||
public string TargetId { get; private set; } = string.Empty;
|
||||
public string? Metadata { get; private set; }
|
||||
public AuditSource Source { get; private set; }
|
||||
public DateTimeOffset CreatedAt { get; private set; }
|
||||
|
||||
private AuditLog()
|
||||
{
|
||||
}
|
||||
|
||||
public static AuditLog Create(
|
||||
Guid? actorId, string action, string targetType, string targetId, string? metadata, AuditSource source)
|
||||
{
|
||||
return new AuditLog
|
||||
{
|
||||
ActorId = actorId,
|
||||
Action = action,
|
||||
TargetType = targetType,
|
||||
TargetId = targetId,
|
||||
Metadata = metadata,
|
||||
Source = source,
|
||||
CreatedAt = DateTimeOffset.UtcNow,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
namespace PnvPanel.Domain.Audit;
|
||||
|
||||
public enum AuditSource
|
||||
{
|
||||
Web,
|
||||
Telegram,
|
||||
System,
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
namespace PnvPanel.Domain.Configs;
|
||||
|
||||
/// <summary>
|
||||
/// Точка истории трафика. Id — long (не Guid, как у Entity) — таблица растёт быстро,
|
||||
/// авто-инкремент компактнее для высокочастотной записи. TTL-ретеншн — см. TrafficRetentionService.
|
||||
/// </summary>
|
||||
public sealed class TrafficSample
|
||||
{
|
||||
public long Id { get; private set; }
|
||||
public Guid ConfigId { get; private set; }
|
||||
public DateTimeOffset Timestamp { get; private set; }
|
||||
public long UpBytes { get; private set; }
|
||||
public long DownBytes { get; private set; }
|
||||
|
||||
private TrafficSample()
|
||||
{
|
||||
}
|
||||
|
||||
public static TrafficSample Create(Guid configId, DateTimeOffset timestamp, long upBytes, long downBytes)
|
||||
{
|
||||
return new TrafficSample
|
||||
{
|
||||
ConfigId = configId,
|
||||
Timestamp = timestamp,
|
||||
UpBytes = upBytes,
|
||||
DownBytes = downBytes,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -72,6 +72,28 @@ public sealed class VpnConfig : Entity
|
||||
Status = ConfigStatus.Revoked;
|
||||
}
|
||||
|
||||
/// <summary>Синхронизация из 3x-ui (см. TrafficSyncService).</summary>
|
||||
public void UpdateTraffic(long usedUpBytes, long usedDownBytes)
|
||||
{
|
||||
UsedUpBytes = usedUpBytes;
|
||||
UsedDownBytes = usedDownBytes;
|
||||
LastSyncAt = DateTimeOffset.UtcNow;
|
||||
}
|
||||
|
||||
/// <summary>Блокировка пользователя админом — гасит клиента в 3x-ui, но не отзывает запись.</summary>
|
||||
public void Disable()
|
||||
{
|
||||
if (Status == ConfigStatus.Active)
|
||||
Status = ConfigStatus.Disabled;
|
||||
}
|
||||
|
||||
/// <summary>Разблокировка — возвращает в Active только то, что было погашено блокировкой.</summary>
|
||||
public void Enable()
|
||||
{
|
||||
if (Status == ConfigStatus.Disabled)
|
||||
Status = ConfigStatus.Active;
|
||||
}
|
||||
|
||||
private void EnsureActive(string action)
|
||||
{
|
||||
if (Status != ConfigStatus.Active)
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
using System.Security.Cryptography;
|
||||
using PnvPanel.Domain.Common;
|
||||
using PnvPanel.Domain.Exceptions;
|
||||
|
||||
namespace PnvPanel.Domain.Telegram;
|
||||
|
||||
/// <summary>Короткоживущий одноразовый токен для флоу привязки Telegram (deep-link в бота).</summary>
|
||||
public sealed class TelegramLinkToken : Entity
|
||||
{
|
||||
public string Token { get; private set; } = string.Empty;
|
||||
public Guid UserId { get; private set; }
|
||||
public DateTimeOffset ExpiresAt { get; private set; }
|
||||
public DateTimeOffset? ConsumedAt { get; private set; }
|
||||
|
||||
private TelegramLinkToken()
|
||||
{
|
||||
}
|
||||
|
||||
public static TelegramLinkToken Create(Guid userId, TimeSpan ttl)
|
||||
{
|
||||
return new TelegramLinkToken
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
Token = GenerateToken(),
|
||||
UserId = userId,
|
||||
ExpiresAt = DateTimeOffset.UtcNow.Add(ttl),
|
||||
};
|
||||
}
|
||||
|
||||
public bool IsValid => ConsumedAt is null && DateTimeOffset.UtcNow < ExpiresAt;
|
||||
|
||||
public void Consume()
|
||||
{
|
||||
if (!IsValid)
|
||||
throw new DomainException("Токен привязки недействителен или уже использован.");
|
||||
|
||||
ConsumedAt = DateTimeOffset.UtcNow;
|
||||
}
|
||||
|
||||
private static string GenerateToken() => Convert.ToHexString(RandomNumberGenerator.GetBytes(24)).ToLowerInvariant();
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
using PnvPanel.Domain.Common;
|
||||
using PnvPanel.Domain.Exceptions;
|
||||
|
||||
namespace PnvPanel.Domain.Telegram;
|
||||
|
||||
/// <summary>
|
||||
/// Passwordless-вход: сайт создаёт запрос (Id = nonce в deep-link), пользователь подтверждает
|
||||
/// в боте. Context — IP/устройство инициатора, показывается при подтверждении (защита от фишинга).
|
||||
/// </summary>
|
||||
public sealed class TelegramLoginRequest : Entity
|
||||
{
|
||||
public TelegramLoginStatus Status { get; private set; }
|
||||
public Guid? UserId { get; private set; }
|
||||
public string? Context { get; private set; }
|
||||
public DateTimeOffset CreatedAt { get; private set; }
|
||||
public DateTimeOffset ExpiresAt { get; private set; }
|
||||
|
||||
private TelegramLoginRequest()
|
||||
{
|
||||
}
|
||||
|
||||
public static TelegramLoginRequest Create(TimeSpan ttl, string? context)
|
||||
{
|
||||
return new TelegramLoginRequest
|
||||
{
|
||||
Id = Guid.NewGuid(),
|
||||
Status = TelegramLoginStatus.Pending,
|
||||
Context = context,
|
||||
CreatedAt = DateTimeOffset.UtcNow,
|
||||
ExpiresAt = DateTimeOffset.UtcNow.Add(ttl),
|
||||
};
|
||||
}
|
||||
|
||||
public bool IsExpired => DateTimeOffset.UtcNow >= ExpiresAt;
|
||||
|
||||
public void Approve(Guid userId)
|
||||
{
|
||||
EnsurePending();
|
||||
Status = TelegramLoginStatus.Approved;
|
||||
UserId = userId;
|
||||
}
|
||||
|
||||
public void Reject()
|
||||
{
|
||||
EnsurePending();
|
||||
Status = TelegramLoginStatus.Rejected;
|
||||
}
|
||||
|
||||
/// <summary>Помечает выданным (после того как сайт забрал JWT по этому запросу).</summary>
|
||||
public void Consume()
|
||||
{
|
||||
if (Status != TelegramLoginStatus.Approved)
|
||||
throw new DomainException("Запрос ещё не подтверждён.");
|
||||
|
||||
Status = TelegramLoginStatus.Consumed;
|
||||
}
|
||||
|
||||
private void EnsurePending()
|
||||
{
|
||||
if (IsExpired)
|
||||
{
|
||||
Status = TelegramLoginStatus.Expired;
|
||||
throw new DomainException("Запрос на вход истёк.");
|
||||
}
|
||||
|
||||
if (Status != TelegramLoginStatus.Pending)
|
||||
throw new DomainException("Запрос на вход уже обработан.");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
namespace PnvPanel.Domain.Telegram;
|
||||
|
||||
public enum TelegramLoginStatus
|
||||
{
|
||||
Pending,
|
||||
Approved,
|
||||
Rejected,
|
||||
Expired,
|
||||
Consumed,
|
||||
}
|
||||
Reference in New Issue
Block a user