using System; using System.Collections.Generic; using System.Linq; using System.Security.Authentication; using System.Text; using System.Threading.Tasks; using Tango.Transport.Web; namespace Tango.Web.Security { public class TokensManager where T : IEquatable { private Dictionary _tokens; private class TokenWrapper : IEquatable { public WebToken WebToken { get; set; } public T Value { get; set; } public bool Equals(TokenWrapper other) { return Value.Equals(other.Value); } } public TokensManager() { _tokens = new Dictionary(); ExpirationTime = TimeSpan.FromHours(1); } public TimeSpan ExpirationTime { get; set; } public WebToken GetOrCreate(T tokenObject) { var existing_token = _tokens.FirstOrDefault(x => x.Value.Value.Equals(tokenObject)); if (existing_token.Key != null) { return existing_token.Value.WebToken; } else { String token = Guid.NewGuid().ToString(); TokenWrapper wrapper = new TokenWrapper() { Value = tokenObject, WebToken = new WebToken() { //AccessToken = token, //Expiration = DateTime.UtcNow.Add(ExpirationTime) }, }; _tokens.Add(token, wrapper); return wrapper.WebToken; } } public void Validate(String token) { GetTokenObject(token); } public T GetTokenObject(String token) { if (!_tokens.ContainsKey(token)) { throw new AuthenticationException("Invalid token."); } if (DateTime.UtcNow > _tokens[token].WebToken.Expiration) { _tokens.Remove(token); throw new TokenExpiredException("Session Expired."); } return _tokens[token].Value; } } }