52 lines
1.5 KiB
C#
52 lines
1.5 KiB
C#
using System.Collections.Concurrent;
|
|
|
|
namespace LmxFakeProxy.Sessions;
|
|
|
|
public record SessionInfo(string ClientId, long ConnectedSinceUtcTicks);
|
|
|
|
public class SessionManager
|
|
{
|
|
private readonly string? _requiredApiKey;
|
|
private readonly ConcurrentDictionary<string, SessionInfo> _sessions = new();
|
|
|
|
public SessionManager(string? requiredApiKey)
|
|
{
|
|
_requiredApiKey = requiredApiKey;
|
|
}
|
|
|
|
public (bool Success, string Message, string SessionId) Connect(string clientId, string apiKey)
|
|
{
|
|
if (!CheckApiKey(apiKey))
|
|
return (false, "Invalid API key", string.Empty);
|
|
|
|
var sessionId = Guid.NewGuid().ToString("N");
|
|
var info = new SessionInfo(clientId, DateTime.UtcNow.Ticks);
|
|
_sessions[sessionId] = info;
|
|
return (true, "Connected", sessionId);
|
|
}
|
|
|
|
public bool Disconnect(string sessionId)
|
|
{
|
|
return _sessions.TryRemove(sessionId, out _);
|
|
}
|
|
|
|
public bool ValidateSession(string sessionId)
|
|
{
|
|
return _sessions.ContainsKey(sessionId);
|
|
}
|
|
|
|
public (bool Found, string ClientId, long ConnectedSinceUtcTicks) GetConnectionState(string sessionId)
|
|
{
|
|
if (_sessions.TryGetValue(sessionId, out var info))
|
|
return (true, info.ClientId, info.ConnectedSinceUtcTicks);
|
|
return (false, string.Empty, 0);
|
|
}
|
|
|
|
public bool CheckApiKey(string apiKey)
|
|
{
|
|
if (string.IsNullOrEmpty(_requiredApiKey))
|
|
return true;
|
|
return apiKey == _requiredApiKey;
|
|
}
|
|
}
|