ApplyWSToken.cs 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. using System;
  2. using System.Collections.Concurrent;
  3. using System.Linq;
  4. namespace WingNotificationModule.Channel.WebSocket
  5. {
  6. public class ApplyWSToken : IApplyToken
  7. {
  8. private ConcurrentDictionary<string, WSTokenInfo> _tokenDic = new();
  9. /// <summary>
  10. /// Generate token
  11. /// </summary>
  12. /// <param name="clientIpAndPort"></param>
  13. /// <param name="clientDeviceId"></param>
  14. /// <param name="clientSource"></param>
  15. /// <returns>token</returns>
  16. public string GenerateToken(string clientIpAndPort, string clientDeviceId, string clientSource)
  17. {
  18. string token = GetTokenByDeviceId(clientDeviceId);
  19. if (string.IsNullOrWhiteSpace(token))
  20. {
  21. token = Guid.NewGuid().ToString("N");
  22. var tokenInfo = new WSTokenInfo
  23. {
  24. Token = token,
  25. ClientSource = clientSource,
  26. ClientDeviceId = clientDeviceId,
  27. ClientIpAndPort = clientIpAndPort
  28. };
  29. _tokenDic.AddOrUpdate(token, tokenInfo, (k, v) => tokenInfo);
  30. }
  31. return token;
  32. }
  33. /// <summary>
  34. /// Get token by device id
  35. /// </summary>
  36. /// <param name="clientDeviceId"></param>
  37. /// <returns></returns>
  38. public string GetTokenByDeviceId(string clientDeviceId)
  39. {
  40. return _tokenDic.Values.FirstOrDefault(ws => ws.ClientDeviceId == clientDeviceId)?.Token;
  41. }
  42. /// <summary>
  43. /// Validate token
  44. /// </summary>
  45. /// <param name="token"></param>
  46. /// <returns></returns>
  47. public bool ValidateToken(string token)
  48. {
  49. return _tokenDic.TryGetValue(token, out _);
  50. }
  51. }
  52. }