116 lines
4.9 KiB
C#
116 lines
4.9 KiB
C#
// 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, IAuthService auth, ISessionRegistry sessions)
|
||
{
|
||
_logger = logger;
|
||
_auth = auth;
|
||
_sessions = sessions;
|
||
}
|
||
|
||
public async Task OnMessageAsync(IConnection connection, ReadOnlyMemory<byte> data, CancellationToken cancellationToken)
|
||
{
|
||
var clientMessage = _serializer.Deserialize<ClientMessage>(data);
|
||
|
||
switch (clientMessage.OpCode)
|
||
{
|
||
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);
|
||
return;
|
||
}
|
||
}
|
||
|
||
// 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<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);
|
||
}
|