Guest User

Untitled

a guest
Feb 23rd, 2018
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.72 KB | None | 0 0
  1. using JWTSimpleServer.Abstractions;
  2. using MessagePack;
  3. using System;
  4. using MessagePack;
  5. using System.Threading.Tasks;
  6. using System.IO;
  7. using System.Collections.Concurrent;
  8. using System.Threading;
  9.  
  10. namespace JWTSimpleServer.MessagePackRefreshTokenStore
  11. {
  12. public class MessagePackRefreshTokenStore : IRefreshTokenStore
  13. {
  14. private readonly JwtStoreOptions _storeOptions;
  15. private readonly SemaphoreSlim _writeSemaphore = new SemaphoreSlim(1, 1);
  16. public MessagePackRefreshTokenStore(JwtStoreOptions storeOptions)
  17. {
  18. _storeOptions = storeOptions;
  19. }
  20.  
  21. public async Task<Token> GetTokenAsync(string refreshToken)
  22. {
  23. var tokenStore = await ReadBinaryStoreAsync();
  24. if (tokenStore.ContainsKey(refreshToken))
  25. {
  26. return tokenStore[refreshToken];
  27. }
  28. return null;
  29. }
  30.  
  31. public async Task InvalidateRefreshTokenAsync(string refreshToken)
  32. {
  33. var tokenStore = await ReadBinaryStoreAsync();
  34. tokenStore.TryRemove(refreshToken, out Token token);
  35. await WriteBinaryStoreAsync(tokenStore);
  36. }
  37.  
  38. public async Task StoreTokenAsync(Token token)
  39. {
  40. var tokenStore = await ReadBinaryStoreAsync();
  41. tokenStore.TryAdd(token.RefreshToken, token);
  42. await WriteBinaryStoreAsync(tokenStore);
  43. }
  44.  
  45. private Task<ConcurrentDictionary<string, Token>> ReadBinaryStoreAsync()
  46. {
  47. EnsureStore();
  48. using (var binaryStore = new FileStream(_storeOptions.Path, FileMode.Open))
  49. {
  50. return MessagePackSerializer.DeserializeAsync<ConcurrentDictionary<string, Token>>(binaryStore);
  51. }
  52. }
  53.  
  54. private async Task WriteBinaryStoreAsync(ConcurrentDictionary<string, Token> store)
  55. {
  56. await _writeSemaphore.WaitAsync();
  57. try
  58. {
  59. using (var binaryStore = new FileStream(_storeOptions.Path, FileMode.Append))
  60. {
  61. var content = MessagePackSerializer.Serialize(binaryStore);
  62. await binaryStore.WriteAsync(content, 0, content.Length);
  63. }
  64. }
  65. finally
  66. {
  67. _writeSemaphore.Release();
  68. }
  69. }
  70.  
  71. private void EnsureStore()
  72. {
  73. if (!File.Exists(_storeOptions.Path))
  74. {
  75. throw new Exception($"{nameof(MessagePackRefreshTokenStore)} : Error Trying to retrieve data. The store does not exist");
  76. }
  77. }
  78.  
  79. public string GenerateRefreshToken()
  80. {
  81. return Guid.NewGuid().ToString().Replace("-", String.Empty);
  82. }
  83. }
  84. }
Add Comment
Please, Sign In to add comment