tuitio/IdentityServer.Application/Stores/SecurityStore.cs

55 lines
1.7 KiB
C#

using IdentityServer.Domain.Models;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
namespace IdentityServer.Application.Stores
{
public class SecurityStore : ISecurityStore
{
private ConcurrentDictionary<int, List<Token>> Tokens { get; }
public SecurityStore()
{
Tokens = new ConcurrentDictionary<int, List<Token>>();
}
public void SetToken(string token, int userId)
{
var registered = Tokens.TryGetValue(userId, out List<Token> list);
if (registered)
list.Add(new Token() { Raw = token });
else
Tokens.TryAdd(userId, new List<Token>() { new Token() { Raw = token } });
}
public TokenValidation ValidateToken(string token)
{
var lastIndexOfSeparator = token.LastIndexOf('-');
if (lastIndexOfSeparator == -1)
return InvalidToken;
var indexOfNextCharacterAfterSeparator = lastIndexOfSeparator + 1;
var userIdString = token.Substring(indexOfNextCharacterAfterSeparator, token.Length - indexOfNextCharacterAfterSeparator);
if (!int.TryParse(userIdString, out int userId))
return InvalidToken;
var registered = Tokens.TryGetValue(userId, out List<Token> list);
if (!registered)
return InvalidToken;
var valid = list.FirstOrDefault(z => z.Raw == token);
if (valid != null)
return new TokenValidation() { Success = true, UserId = userId };
return InvalidToken;
}
private TokenValidation InvalidToken => new TokenValidation() { Success = false };
}
}