Beispiel #1
0
 /// <summary>
 /// Store the specified userID and credential.
 /// </summary>
 /// <param name="userID">User identifier.</param>
 /// <param name="ssoGroupKey">SSO Group Key.</param>
 /// <param name="credential">Credential.</param>
 abstract public void Store(string userID, string ssoGroupKey, Credential credential);
        /// <summary>
        /// Executes the request asynchronously without any parsing.
        /// </summary>
        /// <returns> The async task with Http response. </returns>
        public async Task <HttpResponseMessage> ExecuteUnparsedAsync()
        {
            var httClient = InitializeRestClient();
            var request   = BuildRestRequest();

            RequestAuth.Authenticate(request);
            Logger.Log(request);
            var response = await httClient.SendAsync(request).ConfigureAwait(false);

            Logger.Log(response);
            var contentType = response.Headers
                              .Where(x => x.Key.ToLower().Equals("content-type"))
                              .Select(x => x.Value)
                              .FirstOrDefault()?
                              .FirstOrDefault();

            if (contentType != null && !contentType.Contains("application/json"))
            {
                var kinveyException = new KinveyException(
                    EnumErrorCategory.ERROR_REQUIREMENT,
                    EnumErrorCode.ERROR_REQUIREMENT_CONTENT_TYPE_HEADER,
                    contentType
                    )
                {
                    RequestID = HelperMethods.getRequestID(response)
                };
                throw kinveyException;
            }

            lastResponseCode    = response.StatusCode;
            lastResponseMessage = response.StatusCode.ToString();
            lastResponseHeaders = new List <KeyValuePair <string, IEnumerable <string> > >();

            foreach (var header in response.Headers)
            {
                lastResponseHeaders.Add(header);
            }

            if ((int)response.StatusCode == 401)
            {
                ServerError error = null;
                try
                {
                    var json = await response.Content.ReadAsStringAsync().ConfigureAwait(false);

                    error = JsonConvert.DeserializeObject <ServerError>(json);
                }
                catch (Exception)
                {
                }

                if (error != null && !error.Error.Equals(Constants.STR_ERROR_BACKEND_INSUFFICIENT_CREDENTIALS))
                {
                    // Attempt to get the refresh token
                    Credential cred         = Client.Store.Load(Client.ActiveUser.Id, Client.SSOGroupKey);
                    string     refreshToken = null;
                    string     redirectUri  = null;
                    string     micClientId  = null;

                    if (cred != null)
                    {
                        refreshToken = cred.RefreshToken;
                        redirectUri  = cred.RedirectUri;
                        micClientId  = cred.MICClientID;

                        if (!string.IsNullOrEmpty(refreshToken) && !refreshToken.ToLower().Equals("null"))
                        {
                            if (!hasRetried)
                            {
                                // Attempting retry - set flag to prevent additional attempts
                                hasRetried = true;

                                //use the refresh token for a new access token
                                JObject result = await Client.ActiveUser.UseRefreshToken(refreshToken, redirectUri, micClientId).ExecuteAsync().ConfigureAwait(false);

                                // log out the current user without removing the user record from the credential store
                                Client.ActiveUser.LogoutSoft();

                                //login with the access token
                                Provider provider = new Provider();
                                provider.kinveyAuth = new MICCredential(result["access_token"].ToString());
                                User u = await User.LoginAsync(new ThirdPartyIdentity(provider), Client).ConfigureAwait(false);

                                //store the new refresh token
                                Credential currentCred = Client.Store.Load(Client.ActiveUser.Id, Client.SSOGroupKey);
                                currentCred.AccessToken  = result["access_token"].ToString();
                                currentCred.RefreshToken = result.GetValidValue("refresh_token");
                                currentCred.RedirectUri  = redirectUri;
                                Client.Store.Store(Client.ActiveUser.Id, Client.SSOGroupKey, currentCred);

                                // Retry the original request
                                RequestAuth = new KinveyAuthenticator(currentCred.AuthToken);
                                var retryResponse = await ExecuteUnparsedAsync().ConfigureAwait(false);

                                return(retryResponse);
                            }
                            else
                            {
                                Client.ActiveUser.Logout();
                            }
                        }
                        else
                        {
                            //logout the current user
                            Client.ActiveUser.Logout();
                        }
                    }
                    else
                    {
                        Client.ActiveUser.Logout();
                    }
                }
            }

            try
            {
                response.EnsureSuccessStatusCode();
            }
            catch (Exception ex)
            {
                throw new KinveyException(
                          EnumErrorCategory.ERROR_BACKEND,
                          EnumErrorCode.ERROR_JSON_RESPONSE,
                          response,
                          ex
                          );
            }


            return(response);
        }