Authentication Service
This commit is contained in:
+87
-10
@@ -1,17 +1,26 @@
|
||||
using System;
|
||||
// Networking/MessageRouter.cs
|
||||
using System;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using Microsoft.Extensions.Logging;
|
||||
using Server.Networking.Messages;
|
||||
using Server.Services.Auth;
|
||||
|
||||
namespace Server.Networking;
|
||||
|
||||
public sealed class MessageRouter
|
||||
{
|
||||
private readonly ILogger<MessageRouter> _logger;
|
||||
private readonly IAuthService _auth;
|
||||
private readonly ISessionRegistry _sessions;
|
||||
private readonly IMessageSerializer _serializer = new JsonSerializerAdapter();
|
||||
|
||||
public MessageRouter(ILogger<MessageRouter> logger) => _logger = logger;
|
||||
public MessageRouter(ILogger<MessageRouter> logger, IAuthService auth, ISessionRegistry sessions)
|
||||
{
|
||||
_logger = logger;
|
||||
_auth = auth;
|
||||
_sessions = sessions;
|
||||
}
|
||||
|
||||
public async Task OnMessageAsync(IConnection connection, ReadOnlyMemory<byte> data, CancellationToken cancellationToken)
|
||||
{
|
||||
@@ -19,20 +28,88 @@ public sealed class MessageRouter
|
||||
|
||||
switch (clientMessage.OpCode)
|
||||
{
|
||||
case 1: // Hello / Echo
|
||||
_logger.LogDebug("HELLO from {ConnectionId}", connection.Id);
|
||||
await SendAsync(connection, new ServerMessage(1, clientMessage.Payload), cancellationToken);
|
||||
break;
|
||||
case OpCodes.ECHO:
|
||||
_logger.LogDebug("ECHO from {ConnectionId}", connection.Id);
|
||||
await ReplyAsync(connection, OpCodes.ECHO, clientMessage.Payload, cancellationToken);
|
||||
return;
|
||||
|
||||
case OpCodes.AUTH_REGISTER:
|
||||
{
|
||||
var req = _serializer.Deserialize<AuthRegisterRequest>(clientMessage.Payload);
|
||||
var (ok, error) = await _auth.RegisterAsync(req.Username, req.Password, req.Email, cancellationToken);
|
||||
|
||||
string? msg = error switch
|
||||
{
|
||||
"invalid_username" => "Username must be 3–32 characters.",
|
||||
"weak_password" => "Password must be at least 8 characters.",
|
||||
"username_taken" => "That username is already in use.",
|
||||
"email_taken" => "That email is already registered.",
|
||||
_ => null
|
||||
};
|
||||
|
||||
await ReplyObjectAsync(connection, OpCodes.AUTH_REGISTER_RESULT,
|
||||
new AuthRegisterResponse(ok, error, msg), cancellationToken);
|
||||
return;
|
||||
}
|
||||
|
||||
case OpCodes.AUTH_LOGIN:
|
||||
{
|
||||
var req = _serializer.Deserialize<AuthLoginRequest>(clientMessage.Payload);
|
||||
var ip = connection.RemoteEndPoint?.ToString();
|
||||
var ua = "gameclient";
|
||||
|
||||
var (ok, error, token, accountId) = await _auth.LoginAsync(req.UsernameOrEmail, req.Password, ip, ua, TimeSpan.FromHours(24), cancellationToken);
|
||||
|
||||
// Optionally fetch ban-until if banned (extend AuthService to return it directly if you prefer)
|
||||
DateTime? bannedUntil = null;
|
||||
if (ok) _sessions.Bind(connection.Id, accountId, token!);
|
||||
|
||||
|
||||
await ReplyObjectAsync(connection, OpCodes.AUTH_LOGIN_RESULT,
|
||||
new AuthLoginResponse(ok, error, token, accountId, bannedUntil), cancellationToken);
|
||||
return;
|
||||
}
|
||||
|
||||
case OpCodes.AUTH_WITH_TOKEN:
|
||||
{
|
||||
var req = _serializer.Deserialize<AuthWithTokenRequest>(clientMessage.Payload);
|
||||
var (ok, error, accountId) = await _auth.ValidateTokenAsync(req.Token, cancellationToken);
|
||||
if (ok) _sessions.Bind(connection.Id, accountId, req.Token);
|
||||
|
||||
await ReplyObjectAsync(connection, OpCodes.AUTH_WITH_TOKEN_RESULT,
|
||||
new AuthWithTokenResponse(ok, error, accountId), cancellationToken);
|
||||
return;
|
||||
}
|
||||
|
||||
default:
|
||||
// Gate all other opcodes behind auth
|
||||
if (!_sessions.IsAuthenticated(connection.Id))
|
||||
{
|
||||
// Either ignore or send a standard error
|
||||
await ReplyErrorAsync(connection, "auth_required", cancellationToken);
|
||||
_logger.LogWarning("Unauthenticated message opcode={Op} from {Conn}", clientMessage.OpCode, connection.Id);
|
||||
return;
|
||||
}
|
||||
|
||||
_logger.LogWarning("Unknown opcode {OpCode} from {ConnectionId}", clientMessage.OpCode, connection.Id);
|
||||
break;
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
public Task SendAsync(IConnection connection, ServerMessage message, CancellationToken cancellationToken)
|
||||
// Helpers
|
||||
private Task ReplyAsync(IConnection connection, int opCode, byte[] payloadBytes, CancellationToken ct)
|
||||
{
|
||||
var bytes = _serializer.Serialize(message);
|
||||
return connection.SendAsync(bytes, cancellationToken).AsTask();
|
||||
var msg = new ServerMessage(opCode, payloadBytes);
|
||||
var wire = _serializer.Serialize(msg);
|
||||
return connection.SendAsync(wire, ct).AsTask();
|
||||
}
|
||||
|
||||
private Task ReplyObjectAsync<T>(IConnection connection, int opCode, T obj, CancellationToken ct)
|
||||
{
|
||||
var payload = _serializer.Serialize(obj);
|
||||
return ReplyAsync(connection, opCode, payload, ct);
|
||||
}
|
||||
|
||||
private Task ReplyErrorAsync(IConnection connection, string code, CancellationToken ct)
|
||||
=> ReplyObjectAsync(connection, OpCodes.ERROR, new { error = code }, ct);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,10 @@
|
||||
namespace Server.Networking.Messages;
|
||||
|
||||
public sealed record AuthRegisterRequest(string Username, string Password, string? Email);
|
||||
public sealed record AuthRegisterResponse(bool Ok, string? Error, string? Message);
|
||||
|
||||
public sealed record AuthLoginRequest(string UsernameOrEmail, string Password);
|
||||
public sealed record AuthLoginResponse(bool Ok, string? Error, string? Token, ulong AccountId, System.DateTime? BannedUntilUtc);
|
||||
|
||||
public sealed record AuthWithTokenRequest(string Token);
|
||||
public sealed record AuthWithTokenResponse(bool Ok, string? Error, ulong AccountId);
|
||||
@@ -0,0 +1,17 @@
|
||||
namespace Server.Networking.Messages;
|
||||
|
||||
public static class OpCodes
|
||||
{
|
||||
public const int ECHO = 1;
|
||||
|
||||
public const int AUTH_REGISTER = 100;
|
||||
public const int AUTH_REGISTER_RESULT = 101;
|
||||
|
||||
public const int AUTH_LOGIN = 110;
|
||||
public const int AUTH_LOGIN_RESULT = 111;
|
||||
|
||||
public const int AUTH_WITH_TOKEN = 112;
|
||||
public const int AUTH_WITH_TOKEN_RESULT = 113;
|
||||
|
||||
public const int ERROR = 900; // generic error envelope if you want
|
||||
}
|
||||
@@ -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