Task <Song> GenerateCacheEntry(ICacheEntry cacheEntry, uint songID, CancellationToken cancellation)
        {
            lock (cacheEntry) {
                if (cacheEntry.Value is Task <Song> generating)
                {
                    return(generating);
                }
                else
                {
                    cacheEntry.SetSlidingExpiration(TimeSpan.FromHours(24));
                    Task <Song> result = this.FetchOrGenerateSong(songID, cancellation);
                    cacheEntry.SetAbsoluteExpiration(TimeSpan.FromDays(7));
                    cacheEntry.Value = result;
                    cacheEntry.Dispose();
                    result.ContinueWith(songTask => {
                        if (!songTask.IsCompletedSuccessfully)
                        {
                            return;
                        }

                        Song song = songTask.Result;
                        cacheEntry.SetSize(
                            song.Title?.Length + song.Lyrics?.Length +
                            song.GeneratorError?.Length ?? 64);
                    });
                    return(result);
                }
            }
        }
Esempio n. 2
0
        public async Task Login(string request_token)
        {
            string tokenExchangeEndpoint = $"{this._configuration.GetValue<string>("kiteApiBaseUrl")}{this._configuration.GetValue<string>("kiteAccessTokenUrl")}";
            KiteAccessTokenResponseRoot kiteAccessTokenResponseRoot = null;
            bool cacheFetchResult = this._cache.TryGetValue <KiteAccessTokenResponseRoot>("kite_access_token", out kiteAccessTokenResponseRoot);

            if (!cacheFetchResult)
            {
                try
                {
                    string accessTokenRequest     = $"{this._configuration.GetValue<string>("kiteApiKey")}{request_token}{this._configuration.GetValue<string>("kiteApiSecret")}";
                    string accessTokenRequestHash = CommonFunctions.ComputeSha256Hash(accessTokenRequest);
                    var    param = new Dictionary <string, dynamic>
                    {
                        { "api_key", this._configuration.GetValue <string>("kiteApiKey") },
                        { "request_token", request_token },
                        { "checksum", accessTokenRequestHash }
                    };

                    string      paramString = String.Join("&", param.Select(x => CommonFunctions.BuildParam(x.Key, x.Value)));
                    HttpContent accessTokenRequestContent = new StringContent(paramString, Encoding.UTF8, "application/x-www-form-urlencoded");
                    accessTokenRequestContent.Headers.Add("X-Kite-Version", "3");
                    HttpResponseMessage access_token_response = await this._httpClient.PostAsync(tokenExchangeEndpoint, accessTokenRequestContent);

                    if (access_token_response.IsSuccessStatusCode)
                    {
                        Stream responseStream = await access_token_response.Content.ReadAsStreamAsync();

                        var respose = new StreamReader(responseStream).ReadToEnd();
                        kiteAccessTokenResponseRoot = JsonSerializer.Deserialize <KiteAccessTokenResponseRoot>(respose);
                        MemoryCacheEntryOptions cacheOptions = new MemoryCacheEntryOptions();
                        cacheOptions.AbsoluteExpiration = new DateTimeOffset(DateTime.Now.AddHours(8));
                        cacheOptions.Priority           = CacheItemPriority.NeverRemove;
                        cacheOptions.RegisterPostEvictionCallback(new PostEvictionDelegate(this.CacheEvictionCallback));
                        cacheOptions.SetSize(CommonFunctions.GetObjectSize(kiteAccessTokenResponseRoot));

                        using (ICacheEntry cacheEntry = this._cache.CreateEntry((object)"kite_access_token"))
                        {
                            cacheEntry.SetSize(CommonFunctions.GetObjectSize(kiteAccessTokenResponseRoot));
                            cacheEntry.SetOptions(cacheOptions);
                            cacheEntry.SetValue(kiteAccessTokenResponseRoot);
                        }
                    }
                    else
                    {
                        this._logger.LogError(access_token_response.ReasonPhrase);
                    }
                }
                catch (Exception ex)
                {
                    this._logger.LogError(ex.Message);
                    throw new IntelliTradeException("An error occurred while trying to get access token from Kite.", ex);
                }
            }
        }
        private async Task <ClaimsPrincipal> GetUser(JsonWebToken jwt, ICacheEntry cacheEntry)
        {
            this.logger?.LogDebug("User Principal is '{0}' (issued by '{1}')", jwt.Subject, jwt.Issuer);

            if (this.options.ValidateTokenSignature)
            {
                if (!this.cachedValidationParameters.TryGetValue(jwt.Kid, out TokenValidationParameters validationParameters))
                {
                    var uri = string.Format(ALBPublicKeyUrlFormatString, this.region, jwt.Kid);
                    this.logger?.LogInformation("Retrieving ALB public key from '{0}'", uri);
                    var publicRsa = await InternalHttpClient.GetStringAsync(uri);

                    validationParameters = new TokenValidationParameters
                    {
                        RequireExpirationTime    = true,
                        RequireSignedTokens      = true,
                        ValidateIssuerSigningKey = true,
                        IssuerSigningKey         = ConvertPemToSecurityKey(publicRsa),
                        ValidateAudience         = false,
                        ValidateIssuer           = false,
                        ValidateLifetime         = this.options.ValidateTokenLifetime,
                        ClockSkew = TimeSpan.FromMinutes(2)
                    };

                    this.cachedValidationParameters.TryAdd(jwt.Kid, validationParameters);
                }

                var validationResult = this.tokenHandler.ValidateToken(jwt.EncodedToken, validationParameters);
                this.logger?.LogDebug("Token Validation result: {0}", validationResult.IsValid);

                if (!validationResult.IsValid)
                {
                    throw validationResult.Exception;
                }
            }

            if (cacheEntry != null)
            {
                cacheEntry.SetSize(jwt.EncodedPayload.Length)
                .SetAbsoluteExpiration(this.cacheDuration);
            }

            var identity = new ClaimsIdentity(jwt.Claims, AuthenticationType, NameClaimType, this.options.RoleClaimType);

            return(new ClaimsPrincipal(identity));
        }
Esempio n. 4
0
        private void CacheEvictionCallback(object key, object value, EvictionReason reason, object state)
        {
            if (EvictionReason.Expired == reason)
            {
                KiteAccessTokenResponseRoot kiteAccessTokenResponseRoot = (KiteAccessTokenResponseRoot)value;
                MemoryCacheEntryOptions     cacheOptions = new MemoryCacheEntryOptions();
                cacheOptions.AbsoluteExpiration = new DateTimeOffset(DateTime.Now.AddHours(8));
                cacheOptions.Priority           = CacheItemPriority.NeverRemove;
                cacheOptions.RegisterPostEvictionCallback(new PostEvictionDelegate(this.CacheEvictionCallback));
                cacheOptions.SetSize(CommonFunctions.GetObjectSize(kiteAccessTokenResponseRoot));

                using (ICacheEntry cacheEntry = this._cache.CreateEntry((object)"kite_access_token"))
                {
                    cacheEntry.SetSize(CommonFunctions.GetObjectSize(kiteAccessTokenResponseRoot));
                    cacheEntry.SetOptions(cacheOptions);
                    cacheEntry.SetValue(kiteAccessTokenResponseRoot);
                }
            }
        }
Esempio n. 5
0
        public async Task <IBitmap> GetImageAsync(Uri uri, CancellationToken cancellationToken = default)
        {
            if (this.memoryCache.TryGetValue(uri, out IBitmap image))
            {
                return(image);
            }

            HttpResponseMessage response = await this.httpClient.GetAsync(uri, cancellationToken).ConfigureAwait(false);

            if (response.IsSuccessStatusCode)
            {
                var responseStream = await response.Content.ReadAsStreamAsync(cancellationToken).ConfigureAwait(false);

                image = this.bitmapFactory.Create(responseStream);

                using ICacheEntry cacheEntry = this.memoryCache.CreateEntry(uri);
                cacheEntry.SetValue(image);
                cacheEntry.SetSize(responseStream.Length);
            }

            return(image);
        }
Esempio n. 6
0
        /// <summary>
        /// Adds an object to distributed cache
        /// </summary>
        /// <param name="key">Cache Key</param>
        /// <param name="value">Cache object</param>
        /// <param name="options">Distributed cache options. <see cref="ExtendedDistributedCacheEntryOptions"/></param>
        public void Set(string key, byte[] value, ExtendedDistributedCacheEntryOptions options)
        {
            if (key == null)
            {
                throw new ArgumentNullException(nameof(key));
            }

            if (value == null)
            {
                throw new ArgumentNullException(nameof(value));
            }

            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }

            using (ICacheEntry cacheEntry = CreateEntry(key))
            {
                var memoryCacheEntryOptions = GetMemoryCacheEntryOptions(options, value.LongLength);
                cacheEntry.SetOptions(memoryCacheEntryOptions);
                if (memoryCacheEntryOptions.AbsoluteExpiration != null)
                {
                    cacheEntry.SetAbsoluteExpiration(memoryCacheEntryOptions.AbsoluteExpiration.Value);
                }
                if (memoryCacheEntryOptions.AbsoluteExpirationRelativeToNow != null)
                {
                    cacheEntry.SetAbsoluteExpiration(memoryCacheEntryOptions.AbsoluteExpirationRelativeToNow.Value);
                }
                if (memoryCacheEntryOptions.SlidingExpiration != null)
                {
                    cacheEntry.SetSlidingExpiration(memoryCacheEntryOptions.SlidingExpiration.Value);
                }
                cacheEntry.SetPriority(memoryCacheEntryOptions.Priority);
                cacheEntry.SetSize(value.LongLength);
                cacheEntry.SetValue(value);
            }
        }
Esempio n. 7
0
 void SetupCacheEntry(ICacheEntry cacheEntry)
 {
     cacheEntry.SetSize(_cacheSize);
     cacheEntry.SetSlidingExpiration(_slidingExpirationTime);
     cacheEntry.SetAbsoluteExpiration(_absoluteExpirationTime);
 }