2025-02-17 22:12:35 -05:00

83 lines
3.4 KiB
C#

using Microsoft.AspNetCore.SignalR;
using Newtonsoft.Json.Linq;
using QuestShare.Server.Managers;
namespace QuestShare.Server.Hubs
{
public partial class ShareHub : Hub
{
[HubMethodName(nameof(Authorize))]
public async Task Server_Authorize(Authorize.Request request)
{
if (BanManager.IsBanned(Context))
{
Log.Error($"[AUTHORIZE] Client {Context.ConnectionId} is banned.");
Context.Abort();
return;
}
var error = Error.None;
if (request.CharacterId == 0) error = Error.InvalidCharacterId;
if (request.Version != Common.Constants.Version) error = Error.InvalidVersion;
if (error != Error.None)
{
Log.Warning($"[AUTHORIZE] Client {Context.ConnectionId} failed authorization with error {error}.");
await Clients.Caller.SendAsync(nameof(Authorize), new Authorize.Response
{
Success = false,
Error = error,
});
Context.Abort();
return;
}
var client = ClientManager.GetClient(Context.ConnectionId, request.Token);
var clientCharacterId = ClientManager.GetClient(request.CharacterId);
if (client == null && clientCharacterId == null)
{
// create new client
var token = ClientManager.AddClient(Context.ConnectionId, request.CharacterId);
Context.Items.Add("Token", token);
Log.Information($"[AUTHORIZE] Client {Context.ConnectionId} authorized with token {token}.");
await Clients.Caller.SendAsync(nameof(Authorize), new Authorize.Response
{
Success = true,
Token = token,
});
}
else if (client == null && clientCharacterId != null)
{
error = Error.Unauthorized;
if (BanManager.CheckBadRequests(Context, nameof(Authorize)))
{
error = Error.BannedTooManyBadRequests;
}
Log.Warning($"[AUTHORIZE] MISMATCH Client {Context.ConnectionId} failed authorization with error {error}.");
await Clients.Caller.SendAsync(nameof(Authorize), new Authorize.Response
{
Success = false,
Error = error,
});
Context.Abort();
}
else if (client != null && clientCharacterId != null)
{
Log.Information($"[AUTHORIZE] Client {Context.ConnectionId} reauthorized with token {client.Token}.");
Context.Items.Add("Token", client.Token);
ClientManager.ChangeClientConnectionId(clientCharacterId.ConnectionId, Context.ConnectionId);
await Clients.Caller.SendAsync(nameof(Authorize), new Authorize.Response
{
Success = true,
Token = client.Token,
});
}
else
{
await Clients.Caller.SendAsync(nameof(Authorize), new Authorize.Response
{
Success = false,
Error = Error.Unauthorized,
});
}
}
}
}