feat(infra): add SessionManager with full session tracking and API key validation
This commit is contained in:
51
infra/lmxfakeproxy/Sessions/SessionManager.cs
Normal file
51
infra/lmxfakeproxy/Sessions/SessionManager.cs
Normal file
@@ -0,0 +1,51 @@
|
||||
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;
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user