예제 #1
0
        /// <summary>
        /// A 401 error mostly indicates access-token is expired. (Only exception is login which 401 shows incorrect username/password)
        /// We must refresh the access-token using refresh-token and retry the original request with new access-token
        /// If on refreshing access-token we get another 401, it indicates refresh-token is expired, too
        /// On that case, if current user is guest we must login with stored username-pass and if not we must force the user to login
        /// </summary>
        /// <typeparam name="T">type of response body</typeparam>
        /// <param name="response">raw response containing error 401</param>
        /// <returns></returns>
        private static IRestResponse <T> Handle401StatusCode <T>(IRestResponse <T> response) where T : class, new()
        {
            // in response of login request (no access token yet!) return the original response
            if (response.Request.Resource.Contains("login"))
            {
                return(response);
            }
            // getting new access-token
            var tokenResponse = RestClient.Execute <BacktoryUser.LoginResponse>(NewAccessTokenRequest());

            if (tokenResponse.ErrorException != null || !response.IsSuccessful())
            {
                // failed to get new token
                if ((int)tokenResponse.StatusCode == (int)BacktoryHttpStatusCode.Unauthorized)
                {
                    // refresh token itself is expired
                    if (BacktoryUser.GetCurrentUser().Guest)
                    {
                        // if guest, first login with stored username/pass and the retry the request
                        // new token is stored and after this we can simply call original request again which uses new token
                        BacktoryUser.Login(BacktoryUser.GetCurrentUser().Username, BacktoryUser.getGuestPassword());
                    }

                    // normal user must login again
                    // TODO: clean way for forcing user to login. How to keep his/her progress? How to retry original request?
                    else
                    {
                        BacktoryUser.ClearBacktoryStoredData();

                        // On this case return value is not important
                        // TODO: may be changing the response error message
                        BacktoryManager.Instance.GlobalEventListener.OnEvent(BacktorySDKEvent.LogoutEvent());
                    }
                }

                // successfully gotten new token
            }
            return(RestClient.Execute <T>(response.Request));
        }