public async Task <TResponse> PostAsync <TResponse>(Uri requestUri, string CorrelationId = null, Dictionary <string, string> headers = null)
        {
            var header = await PrepareHeader(headers);

            var response = await _restfulClient.PostAsync <TResponse>(requestUri, CorrelationId, header);

            return(response);
        }
        public async Task <string> GetOAuthToken(string code)
        {
            var oauthParams = new {
                client_id     = CloudConfigurationManager.GetSetting("FacebookId"),
                client_secret = CloudConfigurationManager.GetSetting("FacebookSecret"),
                redirect_uri  = CloudConfigurationManager.GetSetting("HubOAuthRedirectUri"),
                code          = code
            };
            var result = await _rsc.PostAsync <object, dynamic>(GetAbsoluteUri("oauth/access_token"), oauthParams);

            return(result.access_token);
        }
Exemple #3
0
        private async void OnMessageReceived(object sender, DataEventArgs <WrappedMessage> e)
        {
            Logger.GetLogger().Info($"SlackEventManager: message '{e.Data.Text}' is received from {e.Data.UserName}");
            //The naming conventions of message property is for backwards compatibility with existing event processing logic
            var client     = (SlackClientWrapper)sender;
            var valuePairs = new List <KeyValuePair <string, string> >
            {
                new KeyValuePair <string, string>("team_id", e.Data.TeamId),
                new KeyValuePair <string, string>("team_domain", e.Data.TeamName),
                new KeyValuePair <string, string>("channel_id", e.Data.ChannelId),
                new KeyValuePair <string, string>("channel_name", e.Data.ChannelName),
                new KeyValuePair <string, string>("timestamp", e.Data.Timestamp),
                new KeyValuePair <string, string>("user_id", e.Data.UserId),
                new KeyValuePair <string, string>("user_name", e.Data.UserName),
                new KeyValuePair <string, string>("text", e.Data.Text),
                new KeyValuePair <string, string>("owner_name", client.UserName)
            };
            var encodedMessage = string.Join("&", valuePairs.Where(x => !string.IsNullOrWhiteSpace(x.Value)).Select(x => $"{x.Key}={HttpUtility.UrlEncode(x.Value)}"));

            try
            {
                await _resfultClient.PostAsync(_eventsUri, content : encodedMessage).ConfigureAwait(false);

                Logger.GetLogger().Info($"SlackEventManager: message was posted to Slack terminal for user's {client.UserName} active plans");
            }
            catch (Exception ex)
            {
                //Logger.GetLogger().Info($"Failed to post event from SlackEventMenager with following payload: {encodedMessage}", ex);
                Logger.GetLogger().Error($"SlackEventManager: failed to post event to terminal Slack llowing payload: {encodedMessage}. {ex}");
            }
        }
        /// <summary>
        /// Performs OAuth authentication after receiving verification code from Basecamp. Additionaly performs a check of whether use has access to Basecamp2 projects
        /// </summary>
        public async Task <AuthorizationTokenDTO> AuthenticateAsync(ExternalAuthenticationDTO externalState)
        {
            try
            {
                var query    = HttpUtility.ParseQueryString(externalState.RequestQueryString);
                var code     = query["code"];
                var state    = query["state"];
                var url      = $"{_tokenUrl}?type=web_server&client_id={_clientId}&redirect_uri={HttpUtility.UrlEncode(_redirectUrl)}&client_secret={_clientSecret}&code={code}";
                var response = await _restfulServiceClient.PostAsync <OAuthResponse>(new Uri(url)).ConfigureAwait(false);

                var basecampAuthorizationDTO = new BasecampAuthorizationToken
                {
                    AccessToken  = response.AccessToken,
                    RefreshToken = response.RefreshToken,
                };
                //Retrieving info about username and project
                var userInfo = await GetCurrentUserInfo(basecampAuthorizationDTO).ConfigureAwait(false);

                if (userInfo.Accounts.TrueForAll(x => x.Product != Basecamp2Product))
                {
                    Logger.GetLogger().Error($"Authorized user doesn't have access to Basecamp2. Fr8 User Id - {externalState.Fr8UserId}");
                    return(new AuthorizationTokenDTO {
                        Error = "We couldn't authorize you as your account doesn't have access to Basecamp2 product"
                    });
                }
                basecampAuthorizationDTO.ExpiresAt = userInfo.ExpiresAt;
                return(new AuthorizationTokenDTO
                {
                    ExternalAccountId = userInfo.Identity.Id.ToString(),
                    ExternalAccountName = userInfo.Identity.DisplayName,
                    ExternalStateToken = state,
                    ExpiresAt = basecampAuthorizationDTO.ExpiresAt,
                    Token = JsonConvert.SerializeObject(basecampAuthorizationDTO)
                });
            }
            catch (Exception ex)
            {
                Logger.GetLogger().Error($"Failed to authorize with Basecamp. Fr8 User Id - {externalState.Fr8UserId}, Details - {ex}");
                return(new AuthorizationTokenDTO {
                    Error = "An error occured while trying to authorize you. Please try again later"
                });
            }
        }
Exemple #5
0
        public async Task <OAuthToken> RefreshOAuthTokenAsync(OAuthToken token)
        {
            var url = _parameters.AsanaOAuthTokenUrl;

            var contentDic = new Dictionary <string, string>()
            {
                { "grant_type", "refresh_token" },
                { "client_id", _parameters.AsanaClientId },
                { "client_secret", _parameters.AsanaClientSecret },
                { "refresh_token", this.OAuthToken.RefreshToken }
            };

            var content = new FormUrlEncodedContent(contentDic);

            var jsonObj = await _restfulClient.PostAsync <JObject>(new Uri(url), content).ConfigureAwait(false);

            var refreshedToken = JsonConvert.DeserializeObject <OAuthToken>(jsonObj.ToString());

            // calculate when it ends
            refreshedToken.ExpirationDate = this.CalculateExpirationTime(refreshedToken.ExpiresIn);

            return(refreshedToken);
        }
        public async Task Subscribe()
        {
            var parameters = new List <KeyValuePair <string, string> >();

            parameters.Add(new KeyValuePair <string, string>("client_id", clientId));
            parameters.Add(new KeyValuePair <string, string>("client_secret", clientSecret));
            parameters.Add(new KeyValuePair <string, string>("object", "user"));
            parameters.Add(new KeyValuePair <string, string>("aspect", "media"));
            parameters.Add(new KeyValuePair <string, string>("verify_token", "fr8instagrameventverification"));
            parameters.Add(new KeyValuePair <string, string>("callback_url", callback_url));
            var formContent = new FormUrlEncodedContent(parameters);

            var url          = new Uri("https://api.instagram.com/v1/subscriptions");
            var subscription = await _client.PostAsync <JObject>(url, formContent);
        }
        public async Task <string> GetOAuthToken(string code)
        {
            var parameters = new List <KeyValuePair <string, string> >();

            parameters.Add(new KeyValuePair <string, string>("client_id", clientId));
            parameters.Add(new KeyValuePair <string, string>("client_secret", clientSecret));
            parameters.Add(new KeyValuePair <string, string>("grant_type", "authorization_code"));
            parameters.Add(new KeyValuePair <string, string>("redirect_uri", redirectUri));
            parameters.Add(new KeyValuePair <string, string>("code", code));
            var formContent = new FormUrlEncodedContent(parameters);

            var url     = new Uri("https://api.instagram.com/oauth/access_token");
            var jsonObj = await _client.PostAsync <JObject>(url, formContent);

            return(jsonObj.Value <string>("access_token"));
        }
        private static async Task <PollingDataDTO> RequestPolling(PollingDataDTO pollingData, string terminalToken, IRestfulServiceClient _client)
        {
            try
            {
                var terminalService = ObjectFactory.GetInstance <ITerminal>();

                using (var uow = ObjectFactory.GetInstance <IUnitOfWork>())
                {
                    var terminal = uow.TerminalRepository.GetQuery().FirstOrDefault(a => a.Secret == terminalToken);
                    var url      = terminal.Endpoint + "/terminals/" + terminal.Name + "/polling_notifications";
                    Logger.Info($"Polling: executing request for {pollingData?.ExternalAccountId} from {Server.ServerUrl} to a terminal {terminal?.Name} at {terminal?.Endpoint}");

                    using (var client = new HttpClient())
                    {
                        foreach (var header in terminalService.GetRequestHeaders(terminal, pollingData?.Fr8AccountId))
                        {
                            client.DefaultRequestHeaders.Add(header.Key, header.Value);
                        }

                        try
                        {
                            var response = await _client.PostAsync <PollingDataDTO, PollingDataDTO>(new Uri(url), pollingData);

                            return(response);
                        }
                        catch (Exception exception)
                        {
                            Logger.Info($"Polling: problem with terminal polling request for {pollingData?.ExternalAccountId} from {Server.ServerUrl} to a terminal {terminal?.Name}. Exception: {exception.Message}");
                            return(null);
                        }
                    }
                }
            }
            catch (Exception exception)
            {
                Logger.Info($"Polling: problem with terminal polling request for {pollingData?.ExternalAccountId} from {Server.ServerUrl} to a terminal. Exception: {exception.Message}");
                return(null);
            }
        }
        public async Task <bool> PostMessageToChat(string oauthToken, string channelId, string message)
        {
            var url = CloudConfigurationManager.GetSetting("SlackChatPostMessageUrl");



            var content = new FormUrlEncodedContent(
                new[] {
                new KeyValuePair <string, string>("token", oauthToken),
                new KeyValuePair <string, string>("channel", channelId),
                new KeyValuePair <string, string>("text", message)
            }
                );

            var responseJson = await _client.PostAsync <JObject>(new Uri(url), (HttpContent)content);

            bool isOk;

            try
            {
                isOk = responseJson.Value <bool>("ok");
            }
            catch (Exception ex)
            {
                return(false);
            }

            if (!isOk)
            {
                string reason = responseJson.Value <string>("error");
                if (reason.IndexOf("token") > -1)
                {
                    throw new AuthorizationTokenExpiredOrInvalidException();
                }
            }
            return(isOk);
        }
 public async Task <IHttpActionResult> GetManifestPageUrl(string manifestName)
 {
     return(Ok(await _restfulServiceClient.PostAsync <string, string>(
                   new Uri($"{CloudConfigurationManager.GetSetting("PlanDirectoryUrl")}/api/v1/page_generation/generate_manifest_page"),
                   manifestName)));
 }
Exemple #11
0
 public async Task CreateAlarm(AlarmDTO alarmDTO)
 {
     var hubAlarmsUrl = $"{GetHubUrlWithApiVersion()}/alarms";
     var uri          = new Uri(hubAlarmsUrl);
     await _restfulServiceClient.PostAsync(uri, alarmDTO, null, await GetHMACHeader(uri, alarmDTO));
 }
Exemple #12
0
        /// <summary>
        /// Returns Client Id for provided client name and phone number.
        /// Send verification code to user StatX mobile app for authorization
        /// </summary>
        /// <param name="clientName"></param>
        /// <param name="phoneNumber"></param>
        /// <returns></returns>
        public async Task <StatXAuthResponseDTO> Login(string clientName, string phoneNumber)
        {
            try
            {
                phoneNumber = GeneralisePhoneNumber(phoneNumber);
                var statXAuthLoginDTO = new StatXAuthLoginDTO()
                {
                    PhoneNumber = phoneNumber,
                    ClientName  = "Fr8"
                };

                var uri      = new Uri(StatXBaseApiUrl + AuthLoginRelativeUrl);
                var response = await _restfulServiceClient.PostAsync <StatXAuthLoginDTO>(
                    uri, statXAuthLoginDTO);

                var jObject = JObject.Parse(response);

                var statXAuthResponse = new StatXAuthResponseDTO();

                JToken errorsToken;
                if (jObject.TryGetValue("errors", out errorsToken))
                {
                    if ((errorsToken is JArray))
                    {
                        var firstError = (JArray)errorsToken.First;

                        if (!string.IsNullOrEmpty(firstError["message"]?.ToString()))
                        {
                            statXAuthResponse.Error = firstError["message"].ToString();
                        }
                    }
                }

                //return response
                statXAuthResponse.PhoneNumber = jObject["phoneNumber"]?.ToString();
                statXAuthResponse.ClientName  = clientName;
                statXAuthResponse.ClientId    = jObject["clientId"]?.ToString();

                if (string.IsNullOrEmpty(statXAuthResponse.ClientId))
                {
                    throw new ApplicationException("StatX internal login failed. Please try again!");
                }

                return(statXAuthResponse);
            }
            catch (RestfulServiceException exception)
            {
                //extract the error
                var jObject = JObject.Parse(exception.ResponseMessage);

                var statXAuthResponse = new StatXAuthResponseDTO();

                JToken errorsToken;
                if (!jObject.TryGetValue("errors", out errorsToken))
                {
                    return(statXAuthResponse);
                }
                if ((!(errorsToken is JArray)))
                {
                    return(statXAuthResponse);
                }
                var firstError = (JObject)errorsToken.First;

                if (!string.IsNullOrEmpty(firstError["message"]?.ToString()))
                {
                    statXAuthResponse.Error = $"StatX request error: {firstError["message"].ToString()}";
                }

                return(statXAuthResponse);
            }
        }
        /**********************************************************************************/

        private async Task RequestDiscoveryTask(string hubUrl)
        {
            Exception lastException = null;

            try
            {
                Logger.Info($"Terminal {_activityStore.Terminal.Name} is requesting discovery for endpoint '{_activityStore.Terminal.Endpoint}' from Hub at '{hubUrl}' ");

                var response = await _hubDiscoveryRetryPolicy.Do(() => _restfulServiceClient.PostAsync <TerminalDTO, ResponseMessageDTO>(new Uri(string.Concat(hubUrl, _apiSuffix, "/terminals/forceDiscover")), _activityStore.Terminal, (string)null));

                if (!string.IsNullOrWhiteSpace(response?.ErrorCode))
                {
                    lastException = new Exception(response.Message);
                }
            }
            catch (Exception ex)
            {
                lastException = ex;
            }

            if (lastException != null)
            {
                lock (_hubSecrets)
                {
                    TaskCompletionSource <string> setSecretTask;

                    if (_hubSecrets.TryGetValue(hubUrl, out setSecretTask))
                    {
                        Logger.Error($"Terminal {_activityStore.Terminal.Name}({_activityStore.Terminal.Version}): Hub at '{hubUrl}' refused to call terminal discovery endpoint: {lastException.Message}");
                        setSecretTask.TrySetException(new Exception($"Failed to request discovery from the Hub at : {hubUrl}", lastException));
                    }
                }

                UnsubscribeFromHub(hubUrl);
            }
            else
            {
#pragma warning disable 4014
                Task.Run(async() =>
                {
                    bool shouldUnubscribe = false;

                    await Task.Delay(5000);

                    lock (_hubSecrets)
                    {
                        TaskCompletionSource <string> setSecretTask;

                        if (_hubSecrets.TryGetValue(hubUrl, out setSecretTask))
                        {
                            shouldUnubscribe = setSecretTask.TrySetException(new Exception($"Terminal { _activityStore.Terminal.Name }({ _activityStore.Terminal.Version}): Hub '{hubUrl}' failed to respond with discovery request within a given period of time."));
                        }
                    }

                    if (shouldUnubscribe)
                    {
                        Logger.Error($"Terminal { _activityStore.Terminal.Name }({ _activityStore.Terminal.Version}): Hub at '{hubUrl}'failed to respond with discovery request within a given period of time");
                        UnsubscribeFromHub(hubUrl);
                    }
                });
#pragma warning restore 4014
            }
        }