SessionAudit
This commit is contained in:
@@ -17,17 +17,19 @@ public sealed class NetworkManager
|
|||||||
private readonly ConcurrentDictionary<Guid, IConnection> _connections = new();
|
private readonly ConcurrentDictionary<Guid, IConnection> _connections = new();
|
||||||
private readonly ISessionRegistry _sessions;
|
private readonly ISessionRegistry _sessions;
|
||||||
private readonly IRedisManager _redis;
|
private readonly IRedisManager _redis;
|
||||||
|
private readonly ISessionAudit _sessionAudit;
|
||||||
|
|
||||||
private readonly TimeSpan _tickInterval;
|
private readonly TimeSpan _tickInterval;
|
||||||
private readonly TimeSpan _idleTimeout;
|
private readonly TimeSpan _idleTimeout;
|
||||||
private readonly int _maxConnections;
|
private readonly int _maxConnections;
|
||||||
|
|
||||||
public NetworkManager(ILogger<NetworkManager> log, MessageRouter router, ISessionRegistry sessions, IRedisManager redis)
|
public NetworkManager(ILogger<NetworkManager> log, MessageRouter router, ISessionRegistry sessions, IRedisManager redis, ISessionAudit sessionAudit)
|
||||||
{
|
{
|
||||||
_log = log;
|
_log = log;
|
||||||
_router = router;
|
_router = router;
|
||||||
_sessions = sessions;
|
_sessions = sessions;
|
||||||
_redis = redis;
|
_redis = redis;
|
||||||
|
_sessionAudit = sessionAudit;
|
||||||
|
|
||||||
var tickHz = int.TryParse(Environment.GetEnvironmentVariable("TICK_RATE_HZ"), out var hz) ? Math.Clamp(hz, 1, 120) : 20;
|
var tickHz = int.TryParse(Environment.GetEnvironmentVariable("TICK_RATE_HZ"), out var hz) ? Math.Clamp(hz, 1, 120) : 20;
|
||||||
_tickInterval = TimeSpan.FromMilliseconds(1000.0 / tickHz);
|
_tickInterval = TimeSpan.FromMilliseconds(1000.0 / tickHz);
|
||||||
@@ -143,8 +145,8 @@ public sealed class NetworkManager
|
|||||||
{
|
{
|
||||||
if (_connections.TryRemove(conn.Id, out _))
|
if (_connections.TryRemove(conn.Id, out _))
|
||||||
{
|
{
|
||||||
// If this connection was authenticated, log it out atomically
|
if (_sessions.TryGet(conn.Id, out var accountId, out var token)
|
||||||
if (_sessions.TryGet(conn.Id, out var accountId, out var token) && accountId != 0 && !string.IsNullOrEmpty(token))
|
&& accountId != 0 && !string.IsNullOrEmpty(token))
|
||||||
{
|
{
|
||||||
try
|
try
|
||||||
{
|
{
|
||||||
@@ -159,15 +161,19 @@ public sealed class NetworkManager
|
|||||||
return 1";
|
return 1";
|
||||||
|
|
||||||
await _redis.Db.ScriptEvaluateAsync(lua,
|
await _redis.Db.ScriptEvaluateAsync(lua,
|
||||||
new RedisKey[] { onlineKey, sessKey },
|
new StackExchange.Redis.RedisKey[] { onlineKey, sessKey },
|
||||||
new RedisValue[] { token });
|
new StackExchange.Redis.RedisValue[] { token });
|
||||||
|
|
||||||
|
// NEW: close the SQL session audit row
|
||||||
|
await _sessionAudit.EndAsync(accountId, token, reason);
|
||||||
|
|
||||||
_sessions.Unbind(conn.Id);
|
_sessions.Unbind(conn.Id);
|
||||||
_log.LogInformation("Logged out account {AccountId} on disconnect", accountId);
|
_log.LogInformation("Logged out account {AccountId} on disconnect", accountId);
|
||||||
}
|
}
|
||||||
catch (Exception ex)
|
catch (Exception ex)
|
||||||
{
|
{
|
||||||
_log.LogWarning(ex, "Failed Redis logout cleanup for account {AccountId}", accountId);
|
_log.LogWarning(ex, "Failed logout cleanup for account {AccountId}", accountId);
|
||||||
|
try { await _sessionAudit.EndAsync(accountId, token, reason); } catch { }
|
||||||
_sessions.Unbind(conn.Id);
|
_sessions.Unbind(conn.Id);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -178,4 +184,5 @@ public sealed class NetworkManager
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -45,6 +45,7 @@ builder.Services.AddSingleton<IZoneLeaseService, ZoneLeaseService>();
|
|||||||
builder.Services.AddHostedService(sp => (ZoneLeaseService)sp.GetRequiredService<IZoneLeaseService>());
|
builder.Services.AddHostedService(sp => (ZoneLeaseService)sp.GetRequiredService<IZoneLeaseService>());
|
||||||
builder.Services.AddSingleton<IWalPublisher, WalPublisher>();
|
builder.Services.AddSingleton<IWalPublisher, WalPublisher>();
|
||||||
builder.Services.AddScoped<IAccountsRepository, AccountsRepository>();
|
builder.Services.AddScoped<IAccountsRepository, AccountsRepository>();
|
||||||
|
builder.Services.AddScoped<ISessionAudit, SessionAudit>();
|
||||||
builder.Services.AddSingleton<IPasswordHasher, Pbkdf2PasswordHasher>();
|
builder.Services.AddSingleton<IPasswordHasher, Pbkdf2PasswordHasher>();
|
||||||
builder.Services.AddScoped<IAuthService, AuthService>();
|
builder.Services.AddScoped<IAuthService, AuthService>();
|
||||||
builder.Services.AddSingleton<ISessionRegistry, SessionRegistry>();
|
builder.Services.AddSingleton<ISessionRegistry, SessionRegistry>();
|
||||||
|
|||||||
@@ -0,0 +1,10 @@
|
|||||||
|
using System.Threading;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
|
||||||
|
namespace Server.Services.Auth;
|
||||||
|
|
||||||
|
public interface ISessionAudit
|
||||||
|
{
|
||||||
|
/// <summary>Marks the session as ended (or deletes it) for this account+token.</summary>
|
||||||
|
Task EndAsync(ulong accountId, string token, string reason, CancellationToken ct = default);
|
||||||
|
}
|
||||||
@@ -0,0 +1,64 @@
|
|||||||
|
using System;
|
||||||
|
using System.Linq;
|
||||||
|
using System.Security.Cryptography;
|
||||||
|
using System.Text;
|
||||||
|
using System.Threading;
|
||||||
|
using System.Threading.Tasks;
|
||||||
|
using Microsoft.EntityFrameworkCore;
|
||||||
|
using Microsoft.Extensions.Logging;
|
||||||
|
using Server.Data;
|
||||||
|
|
||||||
|
namespace Server.Services.Auth;
|
||||||
|
|
||||||
|
public sealed class SessionAudit : ISessionAudit
|
||||||
|
{
|
||||||
|
private readonly GameDbContext _db;
|
||||||
|
private readonly ILogger<SessionAudit> _log;
|
||||||
|
|
||||||
|
public SessionAudit(GameDbContext db, ILogger<SessionAudit> log)
|
||||||
|
{
|
||||||
|
_db = db; _log = log;
|
||||||
|
}
|
||||||
|
|
||||||
|
public async Task EndAsync(ulong accountId, string token, string reason, CancellationToken ct = default)
|
||||||
|
{
|
||||||
|
var tokenHash = Sha256Hex(token);
|
||||||
|
|
||||||
|
// Try to mark RevokedAt if the column exists; otherwise delete the row.
|
||||||
|
try
|
||||||
|
{
|
||||||
|
var session = await _db.Set<Session>()
|
||||||
|
.Where(s => s.AccountId == accountId && s.TokenHash == tokenHash)
|
||||||
|
.OrderByDescending(s => s.Id)
|
||||||
|
.FirstOrDefaultAsync(ct);
|
||||||
|
|
||||||
|
if (session is null) return;
|
||||||
|
|
||||||
|
// If you have a RevokedAt column, prefer marking it:
|
||||||
|
var revokedAtProp = _db.Entry(session).Property<DateTime?>("RevokedAt");
|
||||||
|
if (revokedAtProp != null)
|
||||||
|
{
|
||||||
|
revokedAtProp.CurrentValue = DateTime.UtcNow;
|
||||||
|
await _db.SaveChangesAsync(ct);
|
||||||
|
}
|
||||||
|
else
|
||||||
|
{
|
||||||
|
_db.Remove(session);
|
||||||
|
await _db.SaveChangesAsync(ct);
|
||||||
|
}
|
||||||
|
|
||||||
|
_log.LogInformation("Session ended for account {AccountId} (reason={Reason})", accountId, reason);
|
||||||
|
}
|
||||||
|
catch (Exception ex)
|
||||||
|
{
|
||||||
|
_log.LogWarning(ex, "Failed to end SQL session for account {AccountId}", accountId);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private static string Sha256Hex(string s)
|
||||||
|
{
|
||||||
|
using var sha = SHA256.Create();
|
||||||
|
var bytes = sha.ComputeHash(Encoding.UTF8.GetBytes(s));
|
||||||
|
return Convert.ToHexString(bytes).ToLowerInvariant();
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -13,6 +13,8 @@ public sealed class Session
|
|||||||
public string? CreatedIp { get; set; }
|
public string? CreatedIp { get; set; }
|
||||||
public string? UserAgent { get; set; }
|
public string? UserAgent { get; set; }
|
||||||
public Account? Account { get; set; }
|
public Account? Account { get; set; }
|
||||||
|
public DateTime? RevokedAt { get; set; }
|
||||||
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public sealed class SessionConfig : IEntityTypeConfiguration<Session>
|
public sealed class SessionConfig : IEntityTypeConfiguration<Session>
|
||||||
@@ -26,6 +28,7 @@ public sealed class SessionConfig : IEntityTypeConfiguration<Session>
|
|||||||
e.Property(x => x.CreatedIp).HasMaxLength(64);
|
e.Property(x => x.CreatedIp).HasMaxLength(64);
|
||||||
e.Property(x => x.UserAgent).HasMaxLength(256);
|
e.Property(x => x.UserAgent).HasMaxLength(256);
|
||||||
e.Property(x => x.CreatedAt).HasDefaultValueSql("CURRENT_TIMESTAMP(6)");
|
e.Property(x => x.CreatedAt).HasDefaultValueSql("CURRENT_TIMESTAMP(6)");
|
||||||
|
e.Property<DateTime?>("RevokedAt");
|
||||||
e.HasIndex(x => x.AccountId);
|
e.HasIndex(x => x.AccountId);
|
||||||
e.HasIndex(x => x.TokenHash).IsUnique();
|
e.HasIndex(x => x.TokenHash).IsUnique();
|
||||||
|
|
||||||
|
|||||||
Reference in New Issue
Block a user