88 lines
3.1 KiB
C#
88 lines
3.1 KiB
C#
using QuestShare.Server.Models;
|
|
using System.Collections.ObjectModel;
|
|
using System.Collections.Specialized;
|
|
using System.Security.Cryptography;
|
|
|
|
namespace QuestShare.Server.Managers
|
|
{
|
|
public static class ClientManager
|
|
{
|
|
public static string AddClient(string connectionId, ulong characterId)
|
|
{
|
|
using var context = new QuestShareContext();
|
|
var token = GenerateToken();
|
|
context.Clients.Add(new Client
|
|
{
|
|
ConnectionId = connectionId,
|
|
CharacterId = characterId,
|
|
Token = token
|
|
});
|
|
context.SaveChanges();
|
|
return token;
|
|
}
|
|
public static void RemoveClient(string connectionId)
|
|
{
|
|
using var context = new QuestShareContext();
|
|
var client = context.Clients.FirstOrDefault(c => c.ConnectionId == connectionId);
|
|
if (client != null)
|
|
{
|
|
context.Clients.Remove(client);
|
|
}
|
|
context.SaveChanges();
|
|
}
|
|
public static Client? GetClient(string connectionId, string token = "")
|
|
{
|
|
using var context = new QuestShareContext();
|
|
var client = context.Clients.FirstOrDefault(c => c.ConnectionId == connectionId || c.Token == token);
|
|
if (client != null)
|
|
{
|
|
if (token != "" && client.Token != token)
|
|
{
|
|
Log.Warning($"[ClientManager] Found a client, but tokens did not match. {token} != {client.Token}");
|
|
return null;
|
|
}
|
|
if (client.ConnectionId != connectionId)
|
|
{
|
|
Log.Information($"[ClientManager] Changing connection ID from {connectionId} to {client.ConnectionId} for token {token}");
|
|
ChangeClientConnectionId(client.ConnectionId, connectionId);
|
|
}
|
|
return client;
|
|
} else
|
|
{
|
|
Log.Warning($"[ClientManager] Unable to find client for {connectionId} or token {token}");
|
|
return null;
|
|
}
|
|
}
|
|
public static Client? GetClient(ulong characterId)
|
|
{
|
|
using var context = new QuestShareContext();
|
|
var client = context.Clients.FirstOrDefault(c => c.CharacterId == characterId);
|
|
if (client != null)
|
|
{
|
|
return client;
|
|
}
|
|
else
|
|
{
|
|
return null;
|
|
}
|
|
}
|
|
|
|
public static void ChangeClientConnectionId(string oldConnectionId, string newConnectionId)
|
|
{
|
|
using var context = new QuestShareContext();
|
|
var client = context.Clients.FirstOrDefault(c => c.ConnectionId == oldConnectionId);
|
|
if (client != null)
|
|
{
|
|
client.ConnectionId = newConnectionId;
|
|
context.SaveChanges();
|
|
}
|
|
}
|
|
|
|
private static string GenerateToken()
|
|
{
|
|
var random = RandomNumberGenerator.GetHexString(32, true);
|
|
return random;
|
|
}
|
|
}
|
|
}
|