tuitio/IdentityServer.Application/Stores/SecurityStore.cs

55 lines
1.7 KiB
C#
Raw Normal View History

2020-12-20 03:06:43 +02:00
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>>();
}
2020-12-24 04:55:45 +02:00
public void SetToken(Token token, int userId)
2020-12-20 03:06:43 +02:00
{
var registered = Tokens.TryGetValue(userId, out List<Token> list);
if (registered)
2020-12-24 04:55:45 +02:00
list.Add(token);
2020-12-20 03:06:43 +02:00
else
2020-12-24 04:55:45 +02:00
Tokens.TryAdd(userId, new List<Token>() { token });
2020-12-20 03:06:43 +02:00
}
public TokenValidation ValidateToken(string token)
{
2020-12-20 12:33:16 +02:00
var lastIndexOfSeparator = token.LastIndexOf('-');
if (lastIndexOfSeparator == -1)
return InvalidToken;
var indexOfNextCharacterAfterSeparator = lastIndexOfSeparator + 1;
var userIdString = token.Substring(indexOfNextCharacterAfterSeparator, token.Length - indexOfNextCharacterAfterSeparator);
2020-12-20 03:06:43 +02:00
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 };
}
}