Authentication Service
This commit is contained in:
@@ -4,6 +4,9 @@ using System.Net.Sockets;
|
||||
using System.Net.WebSockets;
|
||||
using Microsoft.AspNetCore.Http;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Server.Redis;
|
||||
using Server.Services.Auth;
|
||||
using StackExchange.Redis;
|
||||
|
||||
namespace Server.Networking;
|
||||
|
||||
@@ -12,15 +15,19 @@ public sealed class NetworkManager
|
||||
private readonly ILogger<NetworkManager> _log;
|
||||
private readonly MessageRouter _router;
|
||||
private readonly ConcurrentDictionary<Guid, IConnection> _connections = new();
|
||||
private readonly ISessionRegistry _sessions;
|
||||
private readonly IRedisManager _redis;
|
||||
|
||||
private readonly TimeSpan _tickInterval;
|
||||
private readonly TimeSpan _idleTimeout;
|
||||
private readonly int _maxConnections;
|
||||
|
||||
public NetworkManager(ILogger<NetworkManager> log, MessageRouter router)
|
||||
public NetworkManager(ILogger<NetworkManager> log, MessageRouter router, ISessionRegistry sessions, IRedisManager redis)
|
||||
{
|
||||
_log = log;
|
||||
_router = router;
|
||||
_sessions = sessions;
|
||||
_redis = redis;
|
||||
|
||||
var tickHz = int.TryParse(Environment.GetEnvironmentVariable("TICK_RATE_HZ"), out var hz) ? Math.Clamp(hz, 1, 120) : 20;
|
||||
_tickInterval = TimeSpan.FromMilliseconds(1000.0 / tickHz);
|
||||
@@ -136,9 +143,39 @@ public sealed class NetworkManager
|
||||
{
|
||||
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) && accountId != 0 && !string.IsNullOrEmpty(token))
|
||||
{
|
||||
try
|
||||
{
|
||||
var onlineKey = $"online:acct:{accountId}";
|
||||
var sessKey = $"sess:{token}";
|
||||
|
||||
const string lua = @"
|
||||
if redis.call('GET', KEYS[1]) == ARGV[1] then
|
||||
redis.call('DEL', KEYS[1])
|
||||
end
|
||||
redis.call('DEL', KEYS[2])
|
||||
return 1";
|
||||
|
||||
await _redis.Db.ScriptEvaluateAsync(lua,
|
||||
new RedisKey[] { onlineKey, sessKey },
|
||||
new RedisValue[] { token });
|
||||
|
||||
_sessions.Unbind(conn.Id);
|
||||
_log.LogInformation("Logged out account {AccountId} on disconnect", accountId);
|
||||
}
|
||||
catch (Exception ex)
|
||||
{
|
||||
_log.LogWarning(ex, "Failed Redis logout cleanup for account {AccountId}", accountId);
|
||||
_sessions.Unbind(conn.Id);
|
||||
}
|
||||
}
|
||||
|
||||
_log.LogInformation("Disconnected {Id} ({Reason})", conn.Id, reason);
|
||||
await conn.CloseAsync(reason);
|
||||
await conn.DisposeAsync();
|
||||
try { await conn.CloseAsync(reason); } catch { }
|
||||
try { await conn.DisposeAsync(); } catch { }
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user