55 lines
1.2 KiB
C#
55 lines
1.2 KiB
C#
using System;
|
|
using System.Collections.Concurrent;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using System.Threading.Tasks;
|
|
|
|
namespace Gameboard.ShogiUI.Sockets.Managers
|
|
{
|
|
public interface ISocketTokenCache
|
|
{
|
|
Guid GenerateToken(string s);
|
|
string? GetUsername(Guid g);
|
|
}
|
|
|
|
public class SocketTokenCache : ISocketTokenCache
|
|
{
|
|
/// <summary>
|
|
/// Key is userName or webSessionId
|
|
/// </summary>
|
|
private readonly ConcurrentDictionary<string, Guid> Tokens;
|
|
|
|
public SocketTokenCache()
|
|
{
|
|
Tokens = new ConcurrentDictionary<string, Guid>();
|
|
}
|
|
|
|
public Guid GenerateToken(string userName)
|
|
{
|
|
Tokens.Remove(userName, out _);
|
|
|
|
var guid = Guid.NewGuid();
|
|
Tokens.TryAdd(userName, guid);
|
|
|
|
_ = Task.Run(async () =>
|
|
{
|
|
await Task.Delay(TimeSpan.FromMinutes(1));
|
|
Tokens.Remove(userName, out _);
|
|
}).ConfigureAwait(false);
|
|
|
|
return guid;
|
|
}
|
|
|
|
/// <returns>User name associated to the guid or null.</returns>
|
|
public string? GetUsername(Guid guid)
|
|
{
|
|
var userName = Tokens.FirstOrDefault(kvp => kvp.Value == guid).Key;
|
|
if (userName != null)
|
|
{
|
|
Tokens.Remove(userName, out _);
|
|
}
|
|
return userName;
|
|
}
|
|
}
|
|
}
|