public void WhenIGetTokensAsyncIReceiveDeserializedTokens()
        {
            var uriOauth = OAuthRequestHandler.OAuthRequestUri;
            var factory = new TestWebRequestFactory();
            factory.RegisterResultForUri(uriOauth.AbsoluteUri, "{\"access_token\": \"<<token>>\"}");

            var service = new OAuthService(_configuration, factory);

            OAuthTokens received = service.GetTokensAsync("code").Result;

            Assert.IsNotNull(received);
            Assert.AreEqual("<<token>>", received.AccessToken);

        }
        public void WhenIRenewTokensDelegateIReceiveDeserializedTokens()
        {
            var uriOauth = OAuthRequestHandler.OAuthRequestUri;
            var factory = new TestWebRequestFactory();
            factory.RegisterResultForUri(uriOauth.AbsoluteUri, "{\"access_token\": \"<<token>>\"}");

            var service = new OAuthService(_configuration, factory);

            OAuthTokens received = null;
            service.RenewTokens(new OAuthTokens(), (code, tokens) => { received = tokens; }, (uri, exception) => { Assert.Fail(); });

            Assert.IsNotNull(received);
            Assert.AreEqual("<<token>>", received.AccessToken);

        }
Exemplo n.º 3
0
        public AuthorizationService()
        {
            _pelicanContext = PelicanContext.CreateFromApplicationSettings();

            var cloudStorageAccount = new CloudStorageAccount(new StorageCredentials(_pelicanContext.StorageAccount,
                                                                                     _pelicanContext.StorageAccountKey),
                                                              true);

            var configuration = new ApiConfiguration(_pelicanContext.ClientKey,
                                                     _pelicanContext.ClientSecret,
                                                     _pelicanContext.RedirectUrl);

            _oauthService = new OAuthService(configuration);

            _authorizedUserAndFileTable = new AuthorizedUserAndFileTable(cloudStorageAccount,
                                                                         "PelicanConfiguration");

            _authorizedUserAndCompanyFile = _authorizedUserAndFileTable.RetrieveInstanceByRowKey("John Azariah");
        }
        public ActionResult OAuthCallback()
        {
            var requestUri = HttpContextFactory.Current.Request.Url;
            var queries = HttpUtility.ParseQueryString(requestUri.Query);
            var code = queries["code"];

            var service = new OAuthService(APIConfiguration);
            var oauthToken = service.GetTokens(code);
            KeyService = new SimpleOAuthKeyService() {OAuthResponse = oauthToken};

            if (OAuthInformation.Token == null)
                OAuthInformation.Token = new OAuthToken();
            OAuthInformation.Token.AccessToken = KeyService.OAuthResponse.AccessToken;
            OAuthInformation.Token.RefreshToken = KeyService.OAuthResponse.RefreshToken;
            OAuthInformation.Token.ExpiresIn = KeyService.OAuthResponse.ExpiresIn;
            //OAuthInformation.RequestAccessToken();

            return RedirectToAction("Index", "CommandCentre");
        }
        /// <summary>
        /// Event that is called when the form loads
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        /// <remarks></remarks>
        private void CompanyFilesLoad(object sender, EventArgs e)
        {
            try
            {
                ShowSpinner();

                //If developer key  enable (see above) and set useCVloud to true the following section manages OAuth token and accessing cloud service
                if (UseCloud)
                {
                    _configurationCloud = new ApiConfiguration(DeveloperKey, DeveloperSecret, "http://desktop");
                    _oAuthKeyService = new OAuthKeyService();

                    //Get tokens if not stored
                    if (_oAuthKeyService.OAuthResponse == null)
                    {
                        var oauthService = new OAuthService(_configurationCloud);
                        _oAuthKeyService.OAuthResponse =
                            oauthService.GetTokens(OAuthLogin.GetAuthorizationCode(_configurationCloud));
                    }

                    // Load all files from cloud and local simultaneously
                    var cfsCloud = new CompanyFileService(_configurationCloud, null, _oAuthKeyService);
                    cfsCloud.GetRange(OnComplete, OnError);
                }

                _configurationLocal = new ApiConfiguration(LocalApiUrl);
                var cfsLocal = new CompanyFileService(_configurationLocal);
                cfsLocal.GetRange(OnComplete, OnError);

                //' The following two lines can be called to run synchronously rather than async
                //_companyFiles = cfs.GetRange()
                //dgvCompanyFiles.DataSource = _companyFiles
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        public void ServiceWillUseDefaultFactoryIfNotSupplied()
        {
            // arrange
            // act
            var service = new OAuthService(_configuration);

            // assert
            Assert.IsInstanceOf<WebRequestFactory>(service.Factory);
        }
        public void RenewTokensCorrectlyHandlesWebExceptionErrors()
        {
            // arrange
            var apiUri = ApiRequestHandler.ApiRequestUri;

            var factory = new TestWebRequestFactory();
            factory.RegisterExceptionForUri<WebException>(OAuthRequestHandler.OAuthRequestUri.AbsoluteUri);

            var service = new OAuthService(_configuration, factory);

            // act
            var ex = Assert.Throws<ApiCommunicationException>(() => service.RenewTokens(new OAuthTokens()));

            // assert
            Assert.AreEqual(OAuthRequestHandler.OAuthRequestUri, ex.URI);
        }
        void OAuthLogin_Navigated(object sender, System.Windows.Navigation.NavigationEventArgs e)
        {
            Debug.WriteLine(e.Uri);
            if (!string.Equals(e.Uri.ToString(), _authorizeUri.ToString(), StringComparison.InvariantCultureIgnoreCase))
            {
                OAuthLogin.InvokeScript("eval",
                    "var msViewportStyle = document.createElement(\"style\");" +
                    "msViewportStyle.appendChild(document.createTextNode(\"@-ms-viewport{width:auto!important}\"));" +
                    "document.getElementsByTagName(\"head\")[0].appendChild(msViewportStyle);");
                if (string.Equals(e.Uri.ToString(), _loginUri.ToString(), StringComparison.InvariantCultureIgnoreCase))
                {
                    OAuthLogin.Navigate(_authorizeUri);
                }
                return;
            }

            var content = OAuthLogin.SaveToString();
            var regex = new Regex(@"\<title\>(.+?)=(.+?)\</title\>");
            var match = regex.Match(content);
            if (!match.Success || match.Groups.Count != 3) return;

            switch (match.Groups[1].Value.ToLowerInvariant())
            {
                case "code": // we have a code
                    var code = match.Groups[2].Value;
                    var config = new ApiConfiguration();
                    var service = new OAuthService(config, new WebRequestFactory(config));
                    service.GetTokens(code, (statusCode, tokens) =>
                        {
                            OAuthResponse = tokens;
                            Dispatcher.BeginInvoke(() => _viewModel.FetchCompanyFies(ShowError));
                        }, (uri, exception) => ShowError(exception));
                    break;

                case "error": // user probably said "no thanks"
                    OAuthLogin.Navigate(_logoffUri);
                    break;
            }
        }