public async Task <CurrenciesServiceResponse> GetCurrenciesAsync(CancellationToken cancellationToken)
        {
            List <object> cacheKeyList = new List <object>();

            cacheKeyList.Add("GetCurrenciesAsync");

            string cacheKey = string.Join(":", cacheKeyList);

            CurrenciesServiceResponse data = (CurrenciesServiceResponse)cache.Get(cacheKey);

            if (data == null)
            {
                await Settings.CurrenciesServiceLock.WaitAsync();

                try
                {
                    data = (CurrenciesServiceResponse)cache.Get(cacheKey);
                    if (data == null)
                    {
                        string responseString = "";

                        if (_dataPath != "" && File.Exists(_dataPath + Settings.CurrenciesServiceFileName))
                        {
                            var path = _dataPath + Settings.CurrenciesServiceFileName;
                            responseString = File.ReadAllText(path);
                        }
                        else
                        {
                            var variables = new Dictionary <string, string>();
                            variables.Add("{apiKey}", ApiKey());

                            var URL      = Settings.CurrenciesServiceURL.ReplaceFromDictionary(variables);
                            var response = await WebRequestHelper.GetAsync(URL, WebRequestHelper.ResponseAcceptType.JSON, cancellationToken);

                            responseString = response.Item1.BytesToString();

                            try
                            {
                                if (_dataPath != "")
                                {
                                    File.WriteAllText(_dataPath + Settings.CurrenciesServiceFileName, responseString);
                                }
                            }
                            catch
                            {
                            }
                        }
                        data = JsonConvert.DeserializeObject <CurrenciesServiceResponse>(responseString);

                        cacheCurrencies(data, cancellationToken);
                    }
                }
                finally
                {
                    Settings.CurrenciesServiceLock.Release();
                }
            }

            return(data);
        }
        private async Task Refresh()
        {
            try
            {
                var response = await webRequestHelper.GetAsync <GoogleGetKeysResponse>("https://www.googleapis.com/oauth2/v3/certs").ConfigureAwait(false);

                if (response.Keys == null || response.Keys.Count == 0)
                {
                    logger.LogInformation("Failed to fetch Google's JWT signing keys. No keys were returned.");
                    return;
                }

                Keys = response.Keys.Select(k => new GooglePublicKey
                {
                    JWKS = new JsonWebKey
                    {
                        Kty = k.Kty,
                        Kid = k.Kid,
                        Use = k.Use,
                        Alg = k.Alg,
                        N   = k.N,
                        E   = k.E,
                    },
                    RawKey = k
                }).ToArray();
                Ready = true;
            }
            catch (Exception ex)
            {
                logger.LogInformation("Failed to fetch Google's JWT signing keys: {0}", ex.ToString());
            }
        }
            public async static Task <ArrayList> QueryUser(string accessToken, string userID, string url = "")
            {
                string jsonString;

                if (url == "")
                {
                    var response = await WebRequestHelper.GetAsync(string.Format("https://api.instagram.com/v1/users/{0}/media/recent/?access_token={1}", userID, accessToken), WebRequestHelper.ResponseAcceptType.JSON, TaskHelper.CreateLinkedCancellationToken());

                    jsonString = response.Item1.BytesToString();
                }
                else
                {
                    var response = await WebRequestHelper.GetAsync(string.Format(url, new object[0]), WebRequestHelper.ResponseAcceptType.JSON, TaskHelper.CreateLinkedCancellationToken());

                    jsonString = response.Item1.BytesToString();
                }

                Dictionary <string, object> dictionary = jsonString.DeserializeJsonToDictionary();
                ArrayList arrayList = (ArrayList)dictionary["data"];

                if (dictionary.ContainsKey("pagination"))
                {
                    Dictionary <string, object> dictionary2 = (Dictionary <string, object>)dictionary["pagination"];
                    if (dictionary2.ContainsKey("next_url"))
                    {
                        string url2 = (string)dictionary2["next_url"];
                        arrayList.AddRange(await Instagram.User.QueryUser("", "", url2));
                    }
                }
                return(arrayList);
            }
        public async Task <BrowseGridServiceResponse> BrowseGridSearchAsync(string country, string currency, string locale, string originPlaceSkyscannerCode, string destinationPlaceSkyscannerCode, DateTime outboundPartialDate, DateTime?inboundPartialDate, CancellationToken cancellationToken)
        {
            string outboundPartialDateString = outboundPartialDate.ToString("yyyy-MM");
            string inboundPartialDateString  = "";

            if (inboundPartialDate.HasValue)
            {
                inboundPartialDateString = inboundPartialDate.Value.ToString("yyyy-MM");
            }

            List <object> cacheKeyList = new List <object>();

            cacheKeyList.Add("BrowseGridSearchAsync");
            cacheKeyList.Add(country);
            cacheKeyList.Add(currency);
            cacheKeyList.Add(locale);
            cacheKeyList.Add(originPlaceSkyscannerCode);
            cacheKeyList.Add(destinationPlaceSkyscannerCode);
            cacheKeyList.Add(outboundPartialDateString);
            cacheKeyList.Add(inboundPartialDateString);

            string cacheKey = string.Join(":", cacheKeyList);

            BrowseGridServiceResponse data = (BrowseGridServiceResponse)cache.Get(cacheKey);

            if (data == null)
            {
                var variables = new Dictionary <string, string>();
                variables.Add("{apiKey}", ApiKey());
                variables.Add("{market}", country);
                variables.Add("{currency}", currency);
                variables.Add("{locale}", locale);
                variables.Add("{originPlace}", originPlaceSkyscannerCode);
                variables.Add("{destinationPlace}", destinationPlaceSkyscannerCode);
                variables.Add("{outboundPartialDate}", outboundPartialDate.ToString("yyyy-MM"));

                if (inboundPartialDate.HasValue)
                {
                    variables.Add("{inboundPartialDate}", inboundPartialDate.Value.ToString("yyyy-MM"));
                }
                else
                {
                    variables.Add("{inboundPartialDate}", "");
                }

                var URL = Settings.PollBrowseGridURL.ReplaceFromDictionary(variables);
                Func <Exception, Boolean> exception429 = ex => ex is SimpleHttpResponseException && (((int)((SimpleHttpResponseException)ex).StatusCode) == 429);
                var response = await TaskHelper.DoAsync(() => WebRequestHelper.GetAsync(URL, WebRequestHelper.ResponseAcceptType.JSON, cancellationToken), new AsyncRetryPolicy(TimeSpan.FromSeconds(Settings.Exception429WaitTime), Settings.Exception429Retries, exception429), cancellationToken);

                data = JsonConvert.DeserializeObject <BrowseGridServiceResponse>(response.Item1.BytesToString());

                CacheItemPolicy policy = new CacheItemPolicy();
                policy.AbsoluteExpiration = new DateTimeOffset(DateTime.Now.AddMinutes(Settings.PollBrowseGridCacheExpiration));
                cache.Add(cacheKey, data, policy);
            }

            return(data);
        }
            public async static Task <ArrayList> QueryUserId(string accessToken, string userName)
            {
                var response = await WebRequestHelper.GetAsync(string.Format("https://api.instagram.com/v1/users/search?q={0}&access_token={1}", userName, accessToken), WebRequestHelper.ResponseAcceptType.JSON, TaskHelper.CreateLinkedCancellationToken());

                var jsonString = response.Item1.BytesToString();
                Dictionary <string, object> dictionary = jsonString.DeserializeJsonToDictionary();

                return((ArrayList)dictionary["data"]);
            }
Exemple #6
0
        /// <summary>
        /// Sends a browse request to the webservice.
        /// </summary>
        /// <typeparam name="T">Any type derived from <see cref="Entity"/>.</typeparam>
        /// <param name="entity">The name of the XML entity to browse.</param>
        /// <param name="relatedEntity"></param>
        /// <param name="relatedEntityId"></param>
        /// <param name="limit">The number of items to return (default = 25).</param>
        /// <param name="offset">The offset to the items list (enables paging, default = 0).</param>
        /// <param name="inc">A list of entities to include (subqueries).</param>
        /// <returns></returns>
        protected async static Task <T> BrowseAsync <T>(string entity, string relatedEntity, string relatedEntityId, int limit, int offset, params string[] inc) where T : Entity
        {
            if (string.IsNullOrEmpty(entity))
            {
                throw new ArgumentException(string.Format(Resources.Messages.MissingParameter, "entity"));
            }

            return(await WebRequestHelper.GetAsync <T>(WebRequestHelper.CreateBrowseTemplate(entity,
                                                                                             relatedEntity, relatedEntityId, limit, offset, CreateIncludeQuery(inc)), withoutMetadata : false));
        }
Exemple #7
0
        /// <summary>
        /// Sends a lookup request to the webservice.
        /// </summary>
        /// <typeparam name="T">Any type derived from <see cref="Entity"/>.</typeparam>
        /// <param name="entity">The name of the XML entity to lookup.</param>
        /// <param name="id">The MusicBrainz id of the entity.</param>
        /// <param name="inc">A list of entities to include (subqueries).</param>
        /// <returns></returns>
        protected async static Task <T> GetAsync <T>(string entity, string id, params string[] inc) where T : Entity
        {
            if (string.IsNullOrEmpty(entity))
            {
                throw new ArgumentException(string.Format(Resources.Messages.MissingParameter, "entity"));
            }

            if (string.IsNullOrEmpty(id))
            {
                throw new ArgumentException(string.Format(Resources.Messages.MissingParameter, "id"));
            }

            return(await WebRequestHelper.GetAsync <T>(WebRequestHelper.CreateLookupUrl(entity, id, CreateIncludeQuery(inc))));
        }
Exemple #8
0
        /// <summary>
        /// Sends a search request to the webservice.
        /// </summary>
        /// <typeparam name="T">Any type derived from <see cref="Entity"/>.</typeparam>
        /// <param name="entity">The name of the XML entity to search for.</param>
        /// <param name="query">The query string.</param>
        /// <param name="limit">The number of items to return (default = 25).</param>
        /// <param name="offset">The offset to the items list (enables paging, default = 0).</param>
        /// <returns></returns>
        protected async static Task <T> SearchAsync <T>(string entity, string query, int limit = 25, int offset = 0) where T : MetadataWrapper
        {
            if (string.IsNullOrEmpty(entity))
            {
                throw new ArgumentException(string.Format(Resources.Messages.MissingParameter, "entity"));
            }

            if (string.IsNullOrEmpty(query))
            {
                throw new ArgumentException(string.Format(Resources.Messages.MissingParameter, "query"));
            }

            return(await WebRequestHelper.GetAsync <T>(WebRequestHelper.CreateSearchTemplate(entity,
                                                                                             query, limit, offset), withoutMetadata : false));
        }
        public async Task <Place> GetLocationByIDAsync(string country, string currency, string locale, string id, CancellationToken cancellationToken)
        {
            List <object> cacheKeyList = new List <object>();

            cacheKeyList.Add("GetLocationByIDAsync");
            cacheKeyList.Add(country);
            cacheKeyList.Add(currency);
            cacheKeyList.Add(locale);
            cacheKeyList.Add(id);

            string cacheKey = string.Join(":", cacheKeyList);

            Place data = (Place)cache.Get(cacheKey);

            if (data == null && !cache.Contains(cacheKey))
            {
                var variables = new Dictionary <string, string>();
                variables.Add("{apiKey}", "");
                variables.Add("{market}", country);
                variables.Add("{currency}", currency);
                variables.Add("{locale}", locale);
                variables.Add("{id}", id);

                var URL      = Settings.LocationAutoSuggestByIDURL.ReplaceFromDictionary(variables);
                var response = await WebRequestHelper.GetAsync(URL, WebRequestHelper.ResponseAcceptType.JSON, cancellationToken);

                var responseString = response.Item1.BytesToString();
                var returnData     = JsonConvert.DeserializeObject <LocationServiceResponse>(responseString);
                data = returnData.Places.FirstOrDefault();

                CacheItemPolicy policy = new CacheItemPolicy();
                policy.AbsoluteExpiration = new DateTimeOffset(DateTime.Now.AddMinutes(Settings.LocationAutoSuggestByIDCacheExpiration));
                cache.Add(cacheKey, data, policy);
            }

            return(data);
        }
Exemple #10
0
        public async override Task <IPipelineMessage> Execute(IPipelineMessage input)
        {
            IEnumerable <Product> products;

            if (!_cache.TryGetValue(ApiHelper.ProductCacheKey, out products))
            {
                var response = await WebRequestHelper.GetAsync($"{ApiHelper.GetUrl()}");

                products = JsonConvert.DeserializeObject <IEnumerable <Product> >(response);

                var cacheEntryOptions = new MemoryCacheEntryOptions()
                                        .SetSlidingExpiration(TimeSpan.FromHours(24));

                // Save data in cache.
                _cache.Set(ApiHelper.ProductCacheKey, products, cacheEntryOptions);
            }

            if (products != null)
            {
                input.AddContent(products);
            }

            return(input);
        }
 private async void Button_Click(object sender, RoutedEventArgs e)
 {
     if (PinTextBox.Text.Length > 2)
     {
         LoadingPanel.Visibility   = Visibility.Visible;
         ErrorLabel.Visibility     = Visibility.Hidden;
         PinBorder.BorderBrush     = (Brush)FindResource("grayBrush");
         PinBorder.BorderThickness = new Thickness(1);
         try
         {
             var userName = JsonConvert.DeserializeObject <User>(await WebRequestHelper.PostAsync(ConfigurationManager.AppSettings["ApiUri"] + "/user/login", $"{{ \"pin\": {PinTextBox.Text}}}", "application/json"));
             var docTypes = JsonConvert.DeserializeObject <ObservableCollection <DocType> >(await WebRequestHelper.GetAsync(ConfigurationManager.AppSettings["ApiUri"] + "/document/types"));
             new MainWindow(userName, docTypes).Show();
             Close();
         }
         catch (Exception ex)
         {
             LoadingPanel.Visibility = Visibility.Hidden;
             if (ex.Message.Contains("Not Found"))
             {
                 ErrorLabel.Content        = "Błędny PIN";
                 PinBorder.BorderBrush     = Brushes.Red;
                 PinBorder.BorderThickness = new Thickness(2);
                 ErrorLabel.Visibility     = Visibility.Visible;
             }
             else
             {
                 ErrorLabel.Content        = "Błąd połączenia. Spróbuj ponownie później.";
                 PinBorder.BorderBrush     = Brushes.Red;
                 PinBorder.BorderThickness = new Thickness(2);
                 ErrorLabel.Visibility     = Visibility.Visible;
                 Console.WriteLine(ex.Message);
             }
             PinTextBox.Focus();
         }
     }
 }
        public async Task <LivePricesServiceResponse> PollLivePriceSearchAsync(string pollURL, string cacheKey, bool untilComplete, int adults, int children, int infants, int?maxStopsFilter, CancellationToken cancellationToken)
        {
            string responseString = "";

            try
            {
                LivePricesServiceResponse data = (LivePricesServiceResponse)cache.Get(cacheKey);
                if (data == null)
                {
                    var variables = new Dictionary <string,
                                                    string>();
                    variables.Add("apikey", DefaultApiKey());
                    variables.Add("adults", adults.ToString());
                    variables.Add("children", children.ToString());
                    variables.Add("infants", infants.ToString());

                    //can we change passengers and stops when polling?

                    //Return Schema
                    variables.Add("locationschema", "Iata"); //Iata, GeoNameCode, GeoNameId, Rnid*, Sky, Latlong

                    if (maxStopsFilter.HasValue)
                    {
                        //maxStops is actually stops filter
                        variables.Add("stops", maxStopsFilter.ToString());
                    }

                    //carrier, duration, outboundarrivetime, outbounddeparttime, inboundarrivetime, inbounddeparttime, price*
                    //variables.Add("sorttype", "price");
                    //asc, desc
                    //variables.Add("sortorder", "desc");
                    variables.Add("includeQuery", "true");

                    //variables.Add("includecarriers", "");
                    //variables.Add("excludecarriers", "");

                    var newPollURL = pollURL + variables.ToQueryString();

                    var complete = false;
                    while (!complete)
                    {
                        Func <Exception, Boolean> exception304 = ex => ex is SimpleHttpResponseException && (((int)((SimpleHttpResponseException)ex).StatusCode) == 304);
                        Func <Exception, Boolean> exception429 = ex => ex is SimpleHttpResponseException && (((int)((SimpleHttpResponseException)ex).StatusCode) == 429);
                        var response = await TaskHelper.DoAsync(() => TaskHelper.DoAsync(() => WebRequestHelper.GetAsync(newPollURL, WebRequestHelper.ResponseAcceptType.JSON, cancellationToken), new AsyncRetryPolicy(TimeSpan.FromSeconds(Settings.Exception304WaitTime), Settings.Exception304Retries, exception304), cancellationToken), new AsyncRetryPolicy(TimeSpan.FromSeconds(Settings.Exception429WaitTime), Settings.Exception429Retries, exception429), cancellationToken);

                        responseString = response.Item1.BytesToString();
                        data           = JsonConvert.DeserializeObject <LivePricesServiceResponse>(responseString);

                        if (data != null && ((data.Status == "UpdatesComplete") || (data.Status == "UpdatesPending" && !untilComplete)))
                        {
                            complete = true;
                        }
                    }

                    if (data.Places == null)
                    {
                        data.Places = new List <Place>();
                    }

                    if (data.Currencies == null)
                    {
                        data.Currencies = new List <Currency>();
                    }

                    CacheItemPolicy policy = new CacheItemPolicy();
                    policy.AbsoluteExpiration = new DateTimeOffset(DateTime.Now.AddMinutes(Settings.PollLivePricesCacheExpiration));
                    cache.Add(cacheKey, data, policy);
                }

                return(data);
            }
            catch (Newtonsoft.Json.JsonReaderException)
            {
                throw;
            }
            catch
            {
                throw;
            }
        }
Exemple #13
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="context"></param>
        /// <param name="next"></param>
        /// <returns></returns>
        public override async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next)
        {
            IConfiguration configuration = (IConfiguration)context.HttpContext.RequestServices.GetService(typeof(IConfiguration));

            if (configuration == null)
            {
                context.HttpContext.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
                context.Result = new JsonResult(
                    BusinessResult <VoidResult> .Create(
                        "Project settings not found for authentication filter (OAuth2).".ToMessageResult("internalservererror", MessageType.Error)
                        ));
                return;
            }

            string authValidadeUrl = configuration.GetSection("JWTAuthorize:ValidateUrl")?.Value;
            string authByPass      = configuration.GetSection("JWTAuthorize:ByPass")?.Value;

            if (authByPass?.ToLower() == "true" || string.IsNullOrEmpty(authValidadeUrl))
            {
                await next();

                return;
            }

            bool isAuthorized = true;

            string authKey = context.HttpContext.Request
                             .Headers["Authorization"].SingleOrDefault();

            if (string.IsNullOrWhiteSpace(authKey))
            {
                authKey = "Bearer " + context.HttpContext.Request.Query["Token"].FirstOrDefault();
            }

            if (string.IsNullOrWhiteSpace(authKey))
            {
                isAuthorized = false;
            }

            if (isAuthorized)
            {
                Hashtable header = new Hashtable();
                header.Add("Authorization", authKey);

                var response = await WebRequestHelper.GetAsync($"{authValidadeUrl}", header);

                if (!string.IsNullOrEmpty(response))
                {
                    try
                    {
                        var result = JsonConvert.DeserializeObject <LoginResult>(response);

                        if (isAuthorized && string.IsNullOrEmpty(result.UserName))
                        {
                            isAuthorized = false;
                        }
                        else
                        {
                            var claims = new List <Claim>();
                            foreach (var role in result.Claims ?? new List <ClaimResult>())
                            {
                                claims.Add(new Claim(role.Type, role.Value));
                            }
                            ClaimsIdentity  identity  = new ClaimsIdentity(claims);
                            ClaimsPrincipal principal = new ClaimsPrincipal(identity);
                            Thread.CurrentPrincipal = principal;
                        }
                    }
                    catch (Exception)
                    {
                        isAuthorized = false;
                    }
                }
                else
                {
                    isAuthorized = false;
                }
            }

            if (isAuthorized)
            {
                await next();
            }
            else
            {
                context.HttpContext.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
                context.Result = new JsonResult(
                    BusinessResult <VoidResult> .Create(
                        "Provide a valid access token (OAuth2).".ToMessageResult("unauthorized", MessageType.Error)
                        ));
            }
        }
        private async void TextBox_KeyUp(object sender, System.Windows.Input.KeyEventArgs e)
        {
            var student = (sender as TextBox).Text;

            if (student.Length > 2)
            {
                try
                {
                    twainVM.Students = JsonConvert.DeserializeObject <ObservableCollection <Student> >(await WebRequestHelper.GetAsync(ConfigurationManager.AppSettings["ApiUri"] + $"/student/find?q={HttpUtility.UrlEncode(student)}"));
                }
                catch { }
            }
        }
        //Markets!
        public async Task <CountriesServiceResponse> GetCountriesByLocaleAsync(string locale, CancellationToken cancellationToken)
        {
            List <object> cacheKeyList = new List <object>();

            cacheKeyList.Add("GetCountriesByLocaleAsync");
            cacheKeyList.Add(locale);

            string cacheKey = string.Join(":", cacheKeyList);

            CountriesServiceResponse data = (CountriesServiceResponse)cache.Get(cacheKey);

            if (data == null && !cache.Contains(cacheKey))
            {
                if (!Settings.CountriesServiceLock.ContainsKey(locale))
                {
                    Settings.CountriesServiceLock.TryAdd(locale, new SemaphoreSlim(1, 1));
                }

                await Settings.CountriesServiceLock[locale].WaitAsync();
                try
                {
                    data = (CountriesServiceResponse)cache.Get(cacheKey);
                    if (data == null && !cache.Contains(cacheKey))
                    {
                        string responseString = "";

                        var variablesPath = new Dictionary <string, string>();
                        variablesPath.Add("{locale}", locale);

                        if (_dataPath != "" && File.Exists(_dataPath + Settings.CountriesServiceFileName.ReplaceFromDictionary(variablesPath)))
                        {
                            var path = _dataPath + Settings.CountriesServiceFileName.ReplaceFromDictionary(variablesPath);
                            responseString = File.ReadAllText(path);
                        }
                        else
                        {
                            var variables = new Dictionary <string, string>();
                            variables.Add("{apiKey}", ApiKey());
                            variables.Add("{locale}", locale);

                            var URL      = Settings.CountriesServiceURL.ReplaceFromDictionary(variables);
                            var response = await WebRequestHelper.GetAsync(URL, WebRequestHelper.ResponseAcceptType.JSON, cancellationToken);

                            responseString = response.Item1.BytesToString();

                            try
                            {
                                if (_dataPath != "")
                                {
                                    File.WriteAllText(_dataPath + Settings.CountriesServiceFileName.ReplaceFromDictionary(variablesPath), responseString);
                                }
                            }
                            catch
                            {
                            }
                        }

                        data = JsonConvert.DeserializeObject <CountriesServiceResponse>(responseString);

                        for (int i = 0; i < data.Countries.Count(); i++)
                        {
                            var country    = data.Countries[i];
                            var geoCountry = await GetCountryByIDAsync(country.Code, cancellationToken);

                            if (geoCountry != null)
                            {
                                country.CurrencyId = geoCountry.CurrencyId;
                            }
                            else
                            {
                            }
                        }

                        CacheItemPolicy policy = new CacheItemPolicy();
                        policy.AbsoluteExpiration = new DateTimeOffset(DateTime.Now.AddMinutes(Settings.CountriesServiceCacheExpiration));
                        cache.Add(cacheKey, data, policy);
                    }
                }
                finally
                {
                    Settings.CountriesServiceLock[locale].Release();
                }
            }

            return(data);
        }
        public async Task <BrowseRoutesServiceResponse> BrowseRoutesSearchAsync(string country, string currency, string locale, string originPlaceSkyscannerCode, string destinationPlaceSkyscannerCode, DateTime?outboundPartialDate, DateTime?inboundPartialDate, CancellationToken cancellationToken)
        {
            string outboundPartialDateString = "";

            if (outboundPartialDate.HasValue)
            {
                outboundPartialDateString = outboundPartialDate.Value.ToString("yyyy-MM-dd");
            }
            string inboundPartialDateString = "";

            if (inboundPartialDate.HasValue)
            {
                inboundPartialDateString = inboundPartialDate.Value.ToString("yyyy-MM-dd");
            }

            List <object> cacheKeyList = new List <object>();

            cacheKeyList.Add("BrowseRoutesSearchAsync");
            cacheKeyList.Add(country);
            cacheKeyList.Add(currency);
            cacheKeyList.Add(locale);
            cacheKeyList.Add(originPlaceSkyscannerCode);
            cacheKeyList.Add(destinationPlaceSkyscannerCode);
            cacheKeyList.Add(outboundPartialDateString);
            cacheKeyList.Add(inboundPartialDateString);

            string cacheKey = string.Join(":", cacheKeyList);

            BrowseRoutesServiceResponse data = (BrowseRoutesServiceResponse)cache.Get(cacheKey);

            if (data == null)
            {
                var variables = new Dictionary <string,
                                                string>();
                variables.Add("{apiKey}", ApiKey());
                variables.Add("{market}", country);
                variables.Add("{currency}", currency);
                variables.Add("{locale}", locale);
                // If you exceed the rate limit, it will reset after 60 seconds.
                //Sessions expire after 30 minutes.
                //https://github.com/Skyscanner/api-documentation/blob/master/live_flights_pricing/README.md
                //37.678,-122.452-latlong
                //188.39.95.93-ip
                variables.Add("{originPlace}", originPlaceSkyscannerCode);
                variables.Add("{destinationPlace}", destinationPlaceSkyscannerCode);
                if (outboundPartialDate.HasValue)
                {
                    variables.Add("{outboundPartialDate}", outboundPartialDate.Value.ToString("yyyy-MM-dd"));
                }
                else
                {
                    variables.Add("{outboundPartialDate}", "anytime");
                }

                if (inboundPartialDate.HasValue)
                {
                    variables.Add("{inboundPartialDate}", inboundPartialDate.Value.ToString("yyyy-MM-dd"));
                }
                else
                {
                    variables.Add("{inboundPartialDate}", "");
                }

                var URL = Settings.PollBrowseRoutesURL.ReplaceFromDictionary(variables);
                Func <Exception, Boolean> exception429 = ex => ex is SimpleHttpResponseException && (((int)((SimpleHttpResponseException)ex).StatusCode) == 429);
                var response = await TaskHelper.DoAsync(() => WebRequestHelper.GetAsync(URL, WebRequestHelper.ResponseAcceptType.JSON, cancellationToken), new AsyncRetryPolicy(TimeSpan.FromSeconds(Settings.Exception429WaitTime), Settings.Exception429Retries, exception429), cancellationToken);

                data = JsonConvert.DeserializeObject <BrowseRoutesServiceResponse>(response.Item1.BytesToString());

                CacheItemPolicy policy = new CacheItemPolicy();
                policy.AbsoluteExpiration = new DateTimeOffset(DateTime.Now.AddMinutes(Settings.PollBrowseRoutesCacheExpiration));
                cache.Add(cacheKey, data, policy);
            }

            return(data);
        }
Exemple #17
0
        public async Task <TokenMetadata> GetMetadataForToken(string token, AuthType authType)
        {
            if (authType == AuthType.Unknown)
            {
                return(null);
            }

            if (authType == AuthType.Apple)
            {
                var tokenHandler = new JwtSecurityTokenHandler();

                try
                {
                    var unverifiedToken = tokenHandler.ReadJwtToken(token);
                    if (unverifiedToken == null || unverifiedToken.Header == null || unverifiedToken.Header.Kid == null)
                    {
                        return(null);
                    }

                    var expectedKid = unverifiedToken.Header.Kid;

                    var publicKey = Array.Find(appleJWTKeyRefresher.Keys, k => k.RawKey.Kid.Equals(expectedKid, StringComparison.Ordinal));
                    if (publicKey == null)
                    {
                        return(null);
                    }

                    tokenHandler.ValidateToken(token, new TokenValidationParameters
                    {
                        ValidateIssuerSigningKey = true,
                        ValidateIssuer           = true,
                        ValidateAudience         = true,
                        ValidIssuer      = "https://appleid.apple.com",
                        ValidAudience    = "io.meshtech.pubcrawl",
                        IssuerSigningKey = publicKey.JWKS
                    }, out SecurityToken validatedToken);

                    if (!(validatedToken is JwtSecurityToken))
                    {
                        return(null);
                    }

                    var actualToken = (JwtSecurityToken)validatedToken;

                    if (DateTime.UtcNow.CompareTo(actualToken.ValidTo) >= 0)
                    {
                        return(null);
                    }

                    if (string.IsNullOrWhiteSpace(actualToken.Subject))
                    {
                        return(null);
                    }

                    return(new TokenMetadata
                    {
                        Expiry = DateTime.MaxValue,
                        AuthIdentifier = actualToken.Subject
                    });
                }
                catch
                {
                    return(null);
                }
            }

            if (authType == AuthType.Facebook)
            {
                var facebookAddress = settings.Auth.FacebookAuthVerifyAddress;
                var url             = string.Format(CultureInfo.InvariantCulture, facebookAddress, token);

                try
                {
                    var result = await webRequestHelper.GetAsync <FacebookVerificationResponse>(url).ConfigureAwait(false);

                    if (result == null || string.IsNullOrWhiteSpace(result.Id))
                    {
                        return(null);
                    }

                    return(new TokenMetadata
                    {
                        Expiry = DateTime.MaxValue,
                        AuthIdentifier = result.Id
                    });
                }
                catch (Exception)
                {
                    return(null);
                }
            }
            if (authType == AuthType.Google)
            {
                var tokenHandler = new JwtSecurityTokenHandler();

                try
                {
                    var unverifiedToken = tokenHandler.ReadJwtToken(token);
                    if (unverifiedToken == null || unverifiedToken.Header == null || unverifiedToken.Header.Kid == null)
                    {
                        return(null);
                    }

                    var expectedKid = unverifiedToken.Header.Kid;

                    var publicKey = Array.Find(googleJWTKeyRefresher.Keys, k => k.RawKey.Kid.Equals(expectedKid, StringComparison.Ordinal));
                    if (publicKey == null)
                    {
                        return(null);
                    }

                    tokenHandler.ValidateToken(token, new TokenValidationParameters
                    {
                        ValidateIssuerSigningKey = true,
                        ValidateIssuer           = true,
                        ValidateAudience         = true,
                        ValidIssuer      = "https://accounts.google.com",
                        ValidAudience    = "762910246304-t499hbjbsqnjfvul0fdr1n2h0sdt9md2.apps.googleusercontent.com",
                        IssuerSigningKey = publicKey.JWKS
                    }, out SecurityToken validatedToken);

                    if (!(validatedToken is JwtSecurityToken))
                    {
                        return(null);
                    }

                    var actualToken = (JwtSecurityToken)validatedToken;

                    if (DateTime.UtcNow.CompareTo(actualToken.ValidTo) >= 0)
                    {
                        return(null);
                    }

                    if (string.IsNullOrWhiteSpace(actualToken.Subject))
                    {
                        return(null);
                    }

                    return(new TokenMetadata
                    {
                        Expiry = DateTime.MaxValue,
                        AuthIdentifier = actualToken.Subject
                    });
                }
                catch
                {
                    return(null);
                }
            }

            return(null);
        }