massive checkpoint
This commit is contained in:
54
Gameboard.ShogiUI.Sockets/Managers/SocketTokenCache.cs
Normal file
54
Gameboard.ShogiUI.Sockets/Managers/SocketTokenCache.cs
Normal file
@@ -0,0 +1,54 @@
|
||||
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 _);
|
||||
});
|
||||
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user