IW4M-Admin/Application/Misc/TokenAuthentication.cs

101 lines
2.8 KiB
C#
Raw Permalink Normal View History

using SharedLibraryCore.Helpers;
using SharedLibraryCore.Interfaces;
using System;
using System.Collections.Concurrent;
using System.Security.Cryptography;
using System.Text;
namespace IW4MAdmin.Application.Misc
{
2022-01-26 11:32:16 -05:00
internal class TokenAuthentication : ITokenAuthentication
{
private readonly ConcurrentDictionary<long, TokenState> _tokens;
2022-01-26 11:32:16 -05:00
private readonly RandomNumberGenerator _random;
private static readonly TimeSpan TimeoutPeriod = new TimeSpan(0, 0, 120);
private const short TokenLength = 4;
public TokenAuthentication()
{
_tokens = new ConcurrentDictionary<long, TokenState>();
2022-01-26 11:32:16 -05:00
_random = RandomNumberGenerator.Create();
}
public bool AuthorizeToken(long networkId, string token)
{
2022-01-26 11:32:16 -05:00
var authorizeSuccessful = _tokens.ContainsKey(networkId) && _tokens[networkId].Token == token;
if (authorizeSuccessful)
{
2022-01-26 11:32:16 -05:00
_tokens.TryRemove(networkId, out _);
}
return authorizeSuccessful;
}
public TokenState GenerateNextToken(long networkId)
{
2022-01-26 11:32:16 -05:00
TokenState state;
if (_tokens.ContainsKey(networkId))
{
state = _tokens[networkId];
2022-01-26 11:32:16 -05:00
if ((DateTime.Now - state.RequestTime) > TimeoutPeriod)
{
2022-01-26 11:32:16 -05:00
_tokens.TryRemove(networkId, out _);
}
else
{
return state;
}
}
2022-01-26 11:32:16 -05:00
state = new TokenState
{
NetworkId = networkId,
Token = _generateToken(),
2022-01-26 11:32:16 -05:00
TokenDuration = TimeoutPeriod
};
_tokens.TryAdd(networkId, state);
// perform some housekeeping so we don't have built up tokens if they're not ever used
foreach (var (key, value) in _tokens)
{
2022-01-26 11:32:16 -05:00
if ((DateTime.Now - value.RequestTime) > TimeoutPeriod)
{
2022-01-26 11:32:16 -05:00
_tokens.TryRemove(key, out _);
}
}
return state;
}
2022-01-26 11:32:16 -05:00
private string _generateToken()
{
2022-01-26 11:32:16 -05:00
bool ValidCharacter(char c)
{
// this ensure that the characters are 0-9, A-Z, a-z
return (c > 47 && c < 58) || (c > 64 && c < 91) || (c > 96 && c < 123);
}
2022-01-26 11:32:16 -05:00
var token = new StringBuilder();
2022-01-26 11:32:16 -05:00
var charSet = new byte[1];
while (token.Length < TokenLength)
{
_random.GetBytes(charSet);
2022-01-26 11:32:16 -05:00
if (ValidCharacter((char)charSet[0]))
{
token.Append((char)charSet[0]);
}
}
_random.Dispose();
return token.ToString();
}
}
}