public void SetUpBase()
        {
            var credentials = new UserCredentials(new Uri(Credentials.AUTH_ENDPOINT), Credentials.USERNAME,Credentials.API_KEY);
            var request = new GetAuthentication(credentials);
            var cfrequest = new CloudFilesRequest((HttpWebRequest) WebRequest.Create(request.CreateUri()));
            request.Apply(cfrequest);
            var response =
                new ResponseFactory().Create(cfrequest);

            storageUrl = response.Headers[Constants.XStorageUrl];
            authToken = response.Headers[Constants.XAuthToken];
            connection = new Connection(credentials);

            if (!connection.HasCDN()) Assert.Ignore("Provider does not support CDN Management");

            SetUp();
        }
        public void SetUpBase()
        {
            var uri = new Uri(Constants.AUTH_URL);

            var request =
                new GetAuthentication(
                    new UserCredentials(
                        uri,
                        Constants.CREDENTIALS_USER_NAME,
                        Constants.CREDENTIALS_PASSWORD,
                        Constants.CREDENTIALS_CLOUD_VERSION,
                        Constants.CREDENTIALS_ACCOUNT_NAME));

            var response = new GenerateRequestByType().Submit(request, authToken);
                ;

            storageUrl = response.Headers[CloudFiles.Utils.Constants.X_STORAGE_URL];
            authToken = response.Headers[CloudFiles.Utils.Constants.X_AUTH_TOKEN];
            Assert.That(authToken.Length, Is.EqualTo(32));
            SetUp();
        }
 public void setup()
 {
     var userCredentials = new UserCredentials("username", "apikey");
     getAuthentication = new GetAuthentication(userCredentials);
     _mockrequest = new Mock<ICloudFilesRequest>();
 }
 public void setup()
 {
     var userCredentials = new UserCredentials(new Uri("http://authurl"), "username", "apikey", "cloudversion", "cloudaccountname");
     getAuthentication = new GetAuthentication(userCredentials);
     _mockrequest = new Mock<ICloudFilesRequest>();
 }
 public void Should_replace_plus_sign_with_percent_20_on_account_name_username_and_password()
 {
     UserCredentials userCreds = new UserCredentials(new Uri("http://tempuri"), "user name", "pass word", "v 1", "account name");
     GetAuthentication getAuthentication = new GetAuthentication(userCreds);
     var _mockrequest = new Mock<ICloudFilesRequest>();
     var headers = new WebHeaderCollection();
     _mockrequest.SetupGet(x => x.Headers).Returns(headers);
     getAuthentication.Apply(_mockrequest.Object);
     Assert.That(getAuthentication.CreateUri().AbsoluteUri, Is.EqualTo("http://tempuri//v%201/account%20name/auth"));
     Assert.That(headers[CloudFiles.Utils.Constants.X_AUTH_USER], Is.EqualTo("user%20name"));
     Assert.That(headers[CloudFiles.Utils.Constants.X_AUTH_KEY], Is.EqualTo("pass%20word"));
 }
        private void _reInitAuthSequence(bool isRetry)
        {
            if (!isRetry)
            {
                // note: if authentication fails and a Retry is queued, the retry attempt
                // maintains ownership of the AuthenticationPending variable.
                if (Interlocked.CompareExchange(ref _authenticationPending, 1, 0) != 0)
                {
                    // a re-authencation attempt is already pending
                    return;
                }

                if ((this.AuthenticationTime.HasValue) && (this.AuthenticationTime.Value.Add(_authenticationTimeout) < DateTime.UtcNow))
                {
                    Log.Info
                    (
                        this,
                        String.Format
                        (
                            "Connection is being re-authenticated though the authentication token isn't set to expire until {0}",
                            this.AuthenticationTime.Value.Add(_authenticationTimeout).ToString()
                        )
                    );
                }
            }

            bool receivedResponse = false;
            bool errorWas401 = false;
            WebException requestError = null;
            bool success = false;

            try
            {
                var getAuthentication = new GetAuthentication(_usercreds, _authRequestTimeout);

                var getAuthenticationResponse = _requestfactory.Submit(getAuthentication);
                // var getAuthenticationResponse = getAuthentication.Apply(request);

                receivedResponse = true;
                errorWas401 = (getAuthenticationResponse.Status == HttpStatusCode.Unauthorized);

                if (getAuthenticationResponse.Status == HttpStatusCode.OK ||
                    getAuthenticationResponse.Status == HttpStatusCode.Created ||
                    getAuthenticationResponse.Status == HttpStatusCode.Accepted ||
                    getAuthenticationResponse.Status == HttpStatusCode.NonAuthoritativeInformation ||
                    getAuthenticationResponse.Status == HttpStatusCode.NoContent ||
                    getAuthenticationResponse.Status == HttpStatusCode.ResetContent ||
                    getAuthenticationResponse.Status == HttpStatusCode.PartialContent)
                {
                    string storageUrl = getAuthenticationResponse.Headers[Constants.X_STORAGE_URL]; ;
                    if (_useServiceNet)
                    {
                        storageUrl = storageUrl.MakeServiceNet();
                    }

                    string authToken = getAuthenticationResponse.Headers[Constants.X_AUTH_TOKEN];
                    string cdnManagementUrl = getAuthenticationResponse.Headers[Constants.X_CDN_MANAGEMENT_URL];
                    DateTime authTime = DateTime.UtcNow;

                    StorageUrl = storageUrl;
                    AuthToken = authToken;
                    CdnManagementUrl = cdnManagementUrl;
                    AuthenticationTime = authTime;

                    success = true;
                }
                else if (!isRetry)
                {
                    Log.Warn(this, String.Format("Unepxected HttpStatusCode Returned: {0}", getAuthenticationResponse.Status.ToString()));
                }
            }
            catch (WebException ex)
            {
                Log.Error(this, "Failed to Re-Authentication Connection: {0}", ex);
            }

            if (success)
            {
                Interlocked.Exchange(ref _authenticationPending, 0);
                Log.Debug(this, "Successfully Re-Authenticated the Connection");
                return;
            }

            if (errorWas401)
            {
                if (isRetry)
                {
                    // Enable the timer, but disable the disable the "periodi behavior" of the timer
                    // meaning, it will fire once, and then need to be re-enabled before it will fire
                    // again.
                    Interlocked.Exchange(ref _authenticationPending, 0);
                    _reAuthenticateTimer.Change(_reAuthenticationInterval, TimeSpan.Zero);
                }
                else
                {
                    Log.Error(this, "Authentication Attempt Failed: Unauthorized");
                    ThreadPool.QueueUserWorkItem(f => { _reInitAuthSequence(true); });
                }
            }
            else
            {
                if (!isRetry)
                {
                    ThreadPool.QueueUserWorkItem
                    (
                        f =>
                        {
                            _reInitAuthSequence(true);
                        }
                    );
                }
                else
                {
                    Interlocked.Exchange(ref _authenticationPending, 0);

                    // Enable the timer, but disable the disable the "periodi behavior" of the timer
                    // meaning, it will fire once, and then need to be re-enabled before it will fire
                    // again.
                    _reAuthenticateTimer.Change(_reAuthenticationInterval, TimeSpan.Zero);
                }
            }

            return;
        }
        private void AuthenticateSequence(bool retry)
        {
            var getAuthentication = new GetAuthentication(_usercreds);

            bool responseReceived = false;
            bool error401Received = false;
            WebException requestError = null;
            bool success = false;

            try
            {
                var getAuthenticationResponse = _requestfactory.Submit(getAuthentication);
                // var getAuthenticationResponse = getAuthentication.Apply(request);

                responseReceived = true;
                error401Received = getAuthenticationResponse.Status == HttpStatusCode.Unauthorized;

                if (getAuthenticationResponse.Status == HttpStatusCode.OK ||
                    getAuthenticationResponse.Status == HttpStatusCode.Created ||
                    getAuthenticationResponse.Status == HttpStatusCode.Accepted ||
                    getAuthenticationResponse.Status == HttpStatusCode.NonAuthoritativeInformation ||
                    getAuthenticationResponse.Status == HttpStatusCode.NoContent ||
                    getAuthenticationResponse.Status == HttpStatusCode.ResetContent ||
                    getAuthenticationResponse.Status == HttpStatusCode.PartialContent)
                {
                    StorageUrl = getAuthenticationResponse.Headers[Constants.X_STORAGE_URL];
                    if (_useServiceNet)
                        StorageUrl = StorageUrl.MakeServiceNet();

                    AuthToken = getAuthenticationResponse.Headers[Constants.X_AUTH_TOKEN];
                    CdnManagementUrl = getAuthenticationResponse.Headers[Constants.X_CDN_MANAGEMENT_URL];

                    AuthenticationTime = DateTime.UtcNow;
                    success = true;
                }
            }
            catch (WebException ex)
            {
                if ((ex.Status == WebExceptionStatus.ConnectFailure)   ||
                    (ex.Status == WebExceptionStatus.ConnectionClosed) ||
                    (ex.Status == WebExceptionStatus.KeepAliveFailure) ||
                    (ex.Status == WebExceptionStatus.SendFailure)      ||
                    (ex.Status == WebExceptionStatus.Timeout)          ||
                    (ex.Status == WebExceptionStatus.UnknownError))
                {
                    // we can retry after one of these failures.
                    requestError = ex;
                }
                else
                {
                    throw;
                }
            }

            if (success)
            {
                return;
            }

            if (responseReceived)
            {
                if (!retry)
                {
                    Authenticate(true);
                    return;
                }

                if (error401Received)
                {
                    throw new UnauthorizedAccessException();
                }
                else
                {
                    throw new AuthenticationFailedException("Unexpected HttpStatusCode returned");
                }
            }
            else if (retry)
            {
                // we've already retried once - throw the web exception.
                throw requestError;
            }
            else
            {
                // try again
                Authenticate(true);
                return;
            }
        }
        private void AuthenticateSequence()
        {
            var getAuthentication = new GetAuthentication(_usercreds);
            var getAuthenticationResponse = _requestfactory.Submit(getAuthentication);
            // var getAuthenticationResponse = getAuthentication.Apply(request);

            if (getAuthenticationResponse.Status == HttpStatusCode.NoContent)
            {
                StorageUrl = getAuthenticationResponse.Headers[Constants.X_STORAGE_URL];
                if (_useServiceNet)
                    StorageUrl = StorageUrl.MakeServiceNet();

                AuthToken = getAuthenticationResponse.Headers[Constants.X_AUTH_TOKEN];
                CdnManagementUrl = getAuthenticationResponse.Headers[Constants.X_CDN_MANAGEMENT_URL];
                return;
            }

            if (!_retry && getAuthenticationResponse.Status == HttpStatusCode.Unauthorized)
            {
                _retry = true;
                Authenticate();
                return;
            }
        }