1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556 |
- using System;
- using System.Collections.Concurrent;
- using System.Linq;
- namespace WingNotificationModule.Channel.WebSocket
- {
- public class ApplyWSToken : IApplyToken
- {
- private ConcurrentDictionary<string, WSTokenInfo> _tokenDic = new();
- /// <summary>
- /// Generate token
- /// </summary>
- /// <param name="clientIpAndPort"></param>
- /// <param name="clientDeviceId"></param>
- /// <param name="clientSource"></param>
- /// <returns>token</returns>
- public string GenerateToken(string clientIpAndPort, string clientDeviceId, string clientSource)
- {
- string token = GetTokenByDeviceId(clientDeviceId);
- if (string.IsNullOrWhiteSpace(token))
- {
- token = Guid.NewGuid().ToString("N");
- var tokenInfo = new WSTokenInfo
- {
- Token = token,
- ClientSource = clientSource,
- ClientDeviceId = clientDeviceId,
- ClientIpAndPort = clientIpAndPort
- };
- _tokenDic.AddOrUpdate(token, tokenInfo, (k, v) => tokenInfo);
- }
- return token;
- }
- /// <summary>
- /// Get token by device id
- /// </summary>
- /// <param name="clientDeviceId"></param>
- /// <returns></returns>
- public string GetTokenByDeviceId(string clientDeviceId)
- {
- return _tokenDic.Values.FirstOrDefault(ws => ws.ClientDeviceId == clientDeviceId)?.Token;
- }
- /// <summary>
- /// Validate token
- /// </summary>
- /// <param name="token"></param>
- /// <returns></returns>
- public bool ValidateToken(string token)
- {
- return _tokenDic.TryGetValue(token, out _);
- }
- }
- }
|