public async Task <bool> CacheSessionKeysAsync(string tokenId, string userId, string sessionId)
        {
            string key  = CacheKeyFactories.GenerateSessionKeyCache(userId, tokenId);
            var    data = await cacheDb.StringGetAsync(new RedisKey(key));

            var cacheModel = new SessionCacheKeyModel()
            {
                SessionId = sessionId,
                UserId    = userId
            };

            string json = JsonConvert.SerializeObject(cacheModel);

            if (data.HasValue)
            {
                await cacheDb.KeyDeleteAsync(new RedisKey(key));

                await cacheDb.StringSetAsync(new RedisKey(key), new RedisValue(json), TimeSpan.FromMinutes(authOptions.Value.AccessTokenLifeTime));

                return(true);
            }

            await cacheDb.StringSetAsync(new RedisKey(key), new RedisValue(json), TimeSpan.FromMinutes(authOptions.Value.AccessTokenLifeTime));

            return(true);
        }
Exemplo n.º 2
0
        public async Task <string> GetOrSetAesKeyAsync(string userId)
        {
            logger.LogInformation($"try to get {userId} cacheKey");
            string cacheKey = CacheKeyFactories.GenerateAesKeyCache(userId);
            var    result   = await CacheGetString(cacheKey);

            if (result != null)
            {
                return(result.Aes);
            }

            var strongKey = await strongKeyProvider.GetStrongKeyAsync(userId);

            if (strongKey == null)
            {
                logger.LogInformation($"Key was not exist. User id: {userId}");
                throw new ApiError(new ServerException("Internal server error"));
            }
            var cacheModel = new CryptCacheModel()
            {
                Aes = strongKey.Secret.ToUrlSafeBase64()
            };

            await CacheSetString(cacheKey, cacheModel, TimeSpan.FromMinutes(5));

            return(cacheModel.Aes);
        }
        public async Task <bool> AddSessionAsync(Session value, string tokenId)
        {
            var sessionCacheKey = await GetSessionCacheKeyAsync(value.UserId, tokenId);

            if (sessionCacheKey == null)
            {
                throw new ApiError(new ServerException("INVALID SESSION CACHE KEY!!!!"));
            }

            var session = await sessionProvider.GetModelBySearchPredicate(x => x.UserId == value.UserId &&
                                                                          x.SessionId == sessionCacheKey.SessionId);

            if (session == null)
            {
                throw new ApiError(new ServerException("Invalid sessions!!!"));
            }

            string cacheKey = CacheKeyFactories.GenerateSessionCacheKey(value.UserId, tokenId, EntityKey);

            var cacheModel = new SessionCacheModel()
            {
                ClientPublicKey  = session.ClientPublicKey,
                ServerPrivateKey = session.ServerPrivateKey,
                ServerPublicKey  = session.ServerPublicKey,
                UserId           = session.UserId,
                SessionId        = session.SessionId
            };

            string json = JsonConvert.SerializeObject(cacheModel);
            await cacheDb.StringSetAsync(cacheKey, json);

            return(true);
        }
        public async Task <SessionCacheKeyModel> GetSessionCacheKeyAsync(string userId, string tokenId)
        {
            try
            {
                string key    = CacheKeyFactories.GenerateSessionKeyCache(userId, tokenId);
                var    result = await cacheDb.StringGetAsync(new RedisKey(key));

                return(JsonConvert.DeserializeObject <SessionCacheKeyModel>(result));
            }
            catch (Exception ex)
            {
                Logger.ErrorLog(ex);
                return(null);
            }
        }
Exemplo n.º 5
0
        public async Task SetAllSubscribersAsync()
        {
            var cacheDb     = baseRedisProvider.GetDatabase();
            var subscribers = baseRedisProvider.GetSubscribers();
            var resultTypes = new List <Type>();

            foreach (var type in Assembly.GetAssembly(typeof(Subscriber)).GetTypes())
            {
            }

            using var scope = serviceProvider.GetService <IServiceScopeFactory>().CreateScope();

            foreach (var type in resultTypes)
            {
                var cacheService = scope.ServiceProvider.GetRequiredService(type);

                string entityName          = type.GetPropertyValue <string>("EntityName");
                bool   isEnabledSubscriber = type.GetPropertyValue <bool>("IsEnabledSubscriber");

                if (isEnabledSubscriber)
                {
                    await subscribers.SubscribeAsync(new RedisChannel(entityName, PatternMode.Literal), async (chanel, message) =>
                    {
                        string strMessage = (string)message;
                        logger.LogInformation(strMessage);

                        var baseCache = await strMessage.FromJson <BaseCacheModel>();
                        var key       = CacheKeyFactories.GenerateDynamicCacheKey(baseCache);

                        var savedElement = await cacheDb.StringGetAsync(new RedisKey(key));
                        if (string.IsNullOrEmpty(savedElement))
                        {
                            await cacheDb.StringSetAsync(new RedisKey(key), new RedisValue(message));
                        }
                        else
                        {
                            await cacheDb.KeyDeleteAsync(new RedisKey(key));
                            await cacheDb.StringSetAsync(new RedisKey(key), new RedisValue(message));
                        }
                    });
                }
            }
        }
        public async Task RemoveUserConnectionAsync(string userId, string connectionId)
        {
            var savedItem = await connectionProvider.GetModelBySearchPredicate(x => x.ConnectionId == connectionId);

            if (savedItem != null)
            {
                await connectionProvider.RemoveAsync(savedItem);
            }

            string cacheKey   = CacheKeyFactories.GenerateConnectionCacheKey(userId, EntityKey);
            var    cacheValue = await CacheGetString(cacheKey);

            if (cacheValue != null)
            {
                var connection = cacheValue.Connections.Where(x => x.Key == connectionId).FirstOrDefault();
                if (connection.Key != null)
                {
                    cacheValue.Connections.Remove(connection.Key);
                }

                await CacheUpdateString(cacheKey, cacheValue, TimeSpan.FromMinutes(tokenOptions.Value.AccessTokenLifeTime));
            }
        }
        public async Task <SessionCacheModel> GetSessionsFromCacheAsync(string userId, string tokenId)
        {
            var sessionCacheKey = await GetSessionCacheKeyAsync(userId, tokenId);

            if (sessionCacheKey == null)
            {
                throw new ApiError(new ServerException("Invalid session cache key!!!"));
            }

            string cacheKey = CacheKeyFactories.GenerateSessionCacheKey(userId, tokenId, EntityKey);

            var dataFromCache = await cacheDb.StringGetAsync(new RedisKey(cacheKey));

            if (dataFromCache.HasValue)
            {
                var result = JsonConvert.DeserializeObject <SessionCacheModel>(dataFromCache);
                return(result);
            }

            var sessionFromDb = await sessionProvider.GetModelBySearchPredicate(x => x.UserId == userId && x.SessionId == sessionCacheKey.SessionId);

            if (sessionFromDb == null)
            {
                return(null);
            }

            await CacheSetString(cacheKey, sessionFromDb, TimeSpan.FromMinutes(authOptions.Value.AccessTokenLifeTime));

            return(new SessionCacheModel()
            {
                ClientPublicKey = sessionFromDb.ClientPublicKey,
                ServerPrivateKey = sessionFromDb.ServerPrivateKey,
                ServerPublicKey = sessionFromDb.ServerPublicKey,
                SessionId = sessionFromDb.SessionId,
                UserId = sessionFromDb.UserId
            });
        }
        public async Task AddUserConnectionAsync(string userId, string connectionId, string sessionId)
        {
            string cacheKey = CacheKeyFactories.GenerateConnectionCacheKey(userId, EntityKey);

            ConnectionCacheModel model = new ConnectionCacheModel()
            {
                Connections = new Dictionary <string, string>()
                {
                    { connectionId, sessionId }
                },
                UserId = userId
            };

            var connections = await connectionProvider.GetModelsBySearchPredicate(x => x.UserId == userId);

            if (connections.IsListNotNull())
            {
                var connectionIdenteficators = new List <string>();

                foreach (var connection in connections)
                {
                    model.Connections.Add(connection.ConnectionId, connection.SessionId);
                }

                await CacheRemove(cacheKey);
            }

            await connectionProvider.CreateOrUpdateAsync(new Connection()
            {
                UserId       = userId,
                Created      = DateTime.Now,
                ConnectionId = connectionId,
                SessionId    = sessionId
            });

            await CacheSetString(cacheKey, model, TimeSpan.FromMinutes(tokenOptions.Value.AccessTokenLifeTime));
        }
        public async Task <Dictionary <string, string> > GetUserConnectionsAsync(string userId)
        {
            string cacheKey             = CacheKeyFactories.GenerateConnectionCacheKey(userId, EntityKey);
            int    countConnectionsInDb = await connectionProvider.CountConnectionsAsync(userId);

            var dataFromCache = await CacheGetString(cacheKey);

            if (countConnectionsInDb == 0 && dataFromCache == null || (dataFromCache == null || dataFromCache.Connections.Keys.Count == 0))
            {
                return(null);
            }

            if (dataFromCache.Connections.Keys.Count > 0 && dataFromCache.Connections.Count == countConnectionsInDb)
            {
                return(dataFromCache.Connections);
            }

            var connectionsFromDb = await connectionProvider.GetModelsBySearchPredicate(x => x.UserId == userId);

            var connectionsIdentefier = new Dictionary <string, string>();

            foreach (var connection in connectionsFromDb)
            {
                connectionsIdentefier.Add(connection.ConnectionId, connection.SessionId);
            }

            var cacheValue = new ConnectionCacheModel()
            {
                UserId      = userId,
                Connections = connectionsIdentefier
            };

            await CacheUpdateString(cacheKey, cacheValue, TimeSpan.FromMinutes(tokenOptions.Value.AccessTokenLifeTime));

            return(cacheValue.Connections);
        }