diff --git a/Networking/Handling/HandlerContext.cs b/Networking/Handling/HandlerContext.cs new file mode 100644 index 0000000..d2f845a --- /dev/null +++ b/Networking/Handling/HandlerContext.cs @@ -0,0 +1,27 @@ +using System.Threading; +using System.Threading.Tasks; +using Server.Networking.Messages; + +namespace Server.Networking.Handling; + +public sealed class HandlerContext +{ + private readonly IMessageSerializer _serializer; + + public HandlerContext(IMessageSerializer serializer) => _serializer = serializer; + + public Task ReplyObjectAsync(IConnection connection, int opCode, object payload, CancellationToken ct) + { + var payloadBytes = _serializer.Serialize(payload); + var serverMessage = new ServerMessage(opCode, payloadBytes); + var wireBytes = _serializer.Serialize(serverMessage); + return connection.SendAsync(wireBytes, ct).AsTask(); + } + + public Task EchoAsync(IConnection connection, ReadOnlyMemory payload, CancellationToken ct) + { + var serverMessage = new ServerMessage(OpCodes.ECHO, payload.ToArray()); + var wireBytes = _serializer.Serialize(serverMessage); + return connection.SendAsync(wireBytes, ct).AsTask(); + } +} diff --git a/Networking/Handling/IClientMessageHandler.cs b/Networking/Handling/IClientMessageHandler.cs new file mode 100644 index 0000000..bdcf892 --- /dev/null +++ b/Networking/Handling/IClientMessageHandler.cs @@ -0,0 +1,19 @@ +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; + +namespace Server.Networking.Handling; + +public interface IClientMessageHandler +{ + // Which opcodes this handler will process + IReadOnlyCollection SupportedOpCodes { get; } + + // Handle a single incoming message + Task HandleAsync( + int opCode, + IConnection connection, + ReadOnlyMemory payload, + CancellationToken cancellationToken); +} diff --git a/Networking/MessageRouter.cs b/Networking/MessageRouter.cs index da0f640..313e60c 100644 --- a/Networking/MessageRouter.cs +++ b/Networking/MessageRouter.cs @@ -1,115 +1,58 @@ -// Networking/MessageRouter.cs -using System; +using System; +using System.Collections.Generic; +using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.Logging; +using Server.Networking.Handling; using Server.Networking.Messages; -using Server.Services.Auth; namespace Server.Networking; public sealed class MessageRouter { private readonly ILogger _logger; - private readonly IAuthService _auth; - private readonly ISessionRegistry _sessions; - private readonly IMessageSerializer _serializer = new JsonSerializerAdapter(); + private readonly IMessageSerializer _serializer; + private readonly Dictionary _handlersByOpcode; - public MessageRouter(ILogger logger, IAuthService auth, ISessionRegistry sessions) + public MessageRouter( + ILogger logger, + IMessageSerializer serializer, + IEnumerable handlers) { _logger = logger; - _auth = auth; - _sessions = sessions; + _serializer = serializer; + + // Build a direct lookup table: opcode -> handler + _handlersByOpcode = new Dictionary(); + foreach (var h in handlers) + foreach (var op in h.SupportedOpCodes) + _handlersByOpcode[op] = h; // last-in wins if duplicates } public async Task OnMessageAsync(IConnection connection, ReadOnlyMemory data, CancellationToken cancellationToken) { var clientMessage = _serializer.Deserialize(data); - switch (clientMessage.OpCode) + if (_handlersByOpcode.TryGetValue(clientMessage.OpCode, out var handler)) { - 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(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(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(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); - return; + await handler.HandleAsync(clientMessage.OpCode, connection, clientMessage.Payload, cancellationToken); + return; } + + if (clientMessage.OpCode == OpCodes.ECHO) + { + _logger.LogDebug("ECHO from {ConnectionId}", connection.Id); + var wire = _serializer.Serialize(new ServerMessage(OpCodes.ECHO, clientMessage.Payload)); + await connection.SendAsync(wire, cancellationToken); + return; + } + + _logger.LogWarning("Unknown opcode {OpCode} from {ConnectionId}", clientMessage.OpCode, connection.Id); + // Optionally reply with a standard error message + var errPayload = _serializer.Serialize(new { error = "unknown_opcode", op = clientMessage.OpCode }); + var errWire = _serializer.Serialize(new ServerMessage(OpCodes.ERROR, errPayload)); + await connection.SendAsync(errWire, cancellationToken); } - // Helpers - private Task ReplyAsync(IConnection connection, int opCode, byte[] payloadBytes, CancellationToken ct) - { - var msg = new ServerMessage(opCode, payloadBytes); - var wire = _serializer.Serialize(msg); - return connection.SendAsync(wire, ct).AsTask(); - } - - private Task ReplyObjectAsync(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); } diff --git a/Program.cs b/Program.cs index 40e06e3..a1fabce 100644 --- a/Program.cs +++ b/Program.cs @@ -8,11 +8,14 @@ using Microsoft.Extensions.Diagnostics.HealthChecks; using Microsoft.Extensions.Hosting; using Server.Data; using Server.Networking; +using Server.Networking.Handling; +using Server.Networking.Messages; using Server.Persistence; using Server.Redis; using Server.Services; using Server.Services.Auth; + var builder = WebApplication.CreateBuilder(args); // ---- MySQL conn string from env ---- @@ -45,6 +48,9 @@ builder.Services.AddScoped(); builder.Services.AddSingleton(); builder.Services.AddScoped(); builder.Services.AddSingleton(); +builder.Services.AddSingleton(); // if not already +builder.Services.AddSingleton(); // add more handlers similarly +builder.Services.AddSingleton(); // Health checks (optional DB/Redis implementations) builder.Services.AddHealthChecks() diff --git a/Services/Auth/AuthHandler.cs b/Services/Auth/AuthHandler.cs new file mode 100644 index 0000000..db7aff0 --- /dev/null +++ b/Services/Auth/AuthHandler.cs @@ -0,0 +1,114 @@ +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; +using Microsoft.Extensions.Logging; +using Server.Networking; +using Server.Networking.Handling; +using Server.Networking.Messages; + +namespace Server.Services.Auth; + +public sealed class AuthHandler : IClientMessageHandler +{ + private readonly ILogger _log; + private readonly IAuthService _authService; + private readonly ISessionRegistry _sessions; + private readonly IMessageSerializer _serializer; + private readonly HandlerContext _ctx; + + public AuthHandler( + ILogger log, + IAuthService authService, + ISessionRegistry sessions, + IMessageSerializer serializer) + { + _log = log; + _authService = authService; + _sessions = sessions; + _serializer = serializer; + _ctx = new HandlerContext(serializer); + } + + public IReadOnlyCollection SupportedOpCodes => new[] + { + OpCodes.AUTH_REGISTER, + OpCodes.AUTH_LOGIN, + OpCodes.AUTH_WITH_TOKEN + }; + + public async Task HandleAsync(int opCode, IConnection connection, ReadOnlyMemory payload, CancellationToken ct) + { + switch (opCode) + { + case OpCodes.AUTH_REGISTER: + await HandleRegisterAsync(connection, payload, ct); + break; + + case OpCodes.AUTH_LOGIN: + await HandleLoginAsync(connection, payload, ct); + break; + + case OpCodes.AUTH_WITH_TOKEN: + await HandleAuthWithTokenAsync(connection, payload, ct); + break; + + default: + _log.LogWarning("AuthHandler received unsupported opcode {Op}", opCode); + break; + } + } + + private async Task HandleRegisterAsync(IConnection connection, ReadOnlyMemory payload, CancellationToken ct) + { + var request = _serializer.Deserialize(payload); + var (ok, error) = await _authService.RegisterAsync(request.Username, request.Password, request.Email, ct); + + string? uiMessage = 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 _ctx.ReplyObjectAsync(connection, OpCodes.AUTH_REGISTER_RESULT, + new AuthRegisterResponse(ok, error, uiMessage), ct); + } + + private async Task HandleLoginAsync(IConnection connection, ReadOnlyMemory payload, CancellationToken ct) + { + var request = _serializer.Deserialize(payload); + var ip = connection.RemoteEndPoint?.ToString(); + var userAgent = "gameclient"; + + var (ok, error, token, accountId) = + await _authService.LoginAsync(request.UsernameOrEmail, request.Password, ip, userAgent, TimeSpan.FromHours(24), ct); + + if (ok && token is not null) + { + _sessions.Bind(connection.Id, accountId, token); + _log.LogInformation("Account {AccountId} logged in on {Conn}", accountId, connection.Id); + } + + // If you want to include BannedUntilUtc, extend the service to return it + await _ctx.ReplyObjectAsync(connection, OpCodes.AUTH_LOGIN_RESULT, + new AuthLoginResponse(ok, error, token, accountId, null), ct); + } + + private async Task HandleAuthWithTokenAsync(IConnection connection, ReadOnlyMemory payload, CancellationToken ct) + { + var request = _serializer.Deserialize(payload); + var (ok, error, accountId) = await _authService.ValidateTokenAsync(request.Token, ct); + + if (ok) + { + _sessions.Bind(connection.Id, accountId, request.Token); + _log.LogInformation("Account {AccountId} authenticated via token on {Conn}", accountId, connection.Id); + } + + await _ctx.ReplyObjectAsync(connection, OpCodes.AUTH_WITH_TOKEN_RESULT, + new AuthWithTokenResponse(ok, error, accountId), ct); + } +}