예제 #1
0
        public void InvalidTokenExceptionConstructorTest3()
        {
            string message = "Security Token is invalid.";
            InvalidTokenException target = new InvalidTokenException();

            Assert.AreEqual(target.Message, message);
        }
예제 #2
0
        public void InvalidTokenExceptionConstructorTest4()
        {
            string errorMessage          = "This is an error message.";
            InvalidTokenException target = new InvalidTokenException(errorMessage);

            Assert.AreEqual(target.Message, errorMessage);
        }
        public void DeleteImagePost_WithInvalidToken_ThrowsInvalidTokenExceptionForToken()
        {
            string expectedToken = "bad-token";

            InvalidTokenException actual = Assert.ThrowsAsync <InvalidTokenException>(() => _deleteService.DeleteImagePost(It.IsAny <EventGridEvent>(), expectedToken));
            string actualToken           = actual.Token;

            Assert.AreEqual(expectedToken, actualToken);
        }
예제 #4
0
        public void InvalidTokenExceptionConstructorTest5()
        {
            string errorMessage = "This is an error message.";

            System.Exception      innerException = new ArgumentNullException();
            InvalidTokenException target         = new InvalidTokenException(errorMessage, innerException);

            Assert.AreEqual(target.Message, errorMessage);
            Assert.ReferenceEquals(target.InnerException, innerException);
        }
예제 #5
0
 public static (HttpStatusCode statusCode, ErrorCode errorCode) ParseException(this Exception exception)
 {
     return(exception switch
     {
         NotFoundException _ => (HttpStatusCode.NotFound, ErrorCode.NotFound),
         InvalidUsernameOrPasswordException _ => (HttpStatusCode.Unauthorized, ErrorCode.InvalidUsernameOrPassword),
         InvalidTokenException _ => (HttpStatusCode.Unauthorized, ErrorCode.InvalidToken),
         ExpiredRefreshTokenException _ => (HttpStatusCode.Unauthorized, ErrorCode.ExpiredRefreshToken),
         _ => (HttpStatusCode.InternalServerError, ErrorCode.General),
     });
예제 #6
0
        public void InvalidTokenExceptionConstructorTest()
        {
            string errorMessage          = "Unauthorized";
            string errorCode             = "401";
            string source                = "Intuit.Ipp.Test";
            InvalidTokenException target = new InvalidTokenException(errorMessage, errorCode, source);

            Assert.AreEqual(target.Message, errorMessage);
            Assert.AreEqual(target.ErrorCode, errorCode);
            Assert.AreEqual(target.Source, source);
        }
예제 #7
0
 private GetTokenInfo(ITokenRepository tokenRepository, IUserRepository userRepository, ITokenInfoExtractor tokenInfoExtractor,
                      string token, string appKey, string device)
 {
     _device             = device;
     _token              = token;
     _appKey             = appKey;
     _tokenRepository    = tokenRepository;
     _userRepository     = userRepository;
     _tokenInfoExtractor = tokenInfoExtractor;
     ValidateInstance();
     InvalidTokenExceptionCreator = () => InvalidTokenException.Create(_token, _appKey, _device);
 }
        public void HandleExceptionTest4()
        {
            InvalidTokenException exception = new InvalidTokenException();

            try
            {
                IdsExceptionManager.HandleException(exception);
            }
            catch (IdsException target)
            {
                Assert.ReferenceEquals(target, exception);
            }
        }
예제 #9
0
 private ChangeMyPassword(ITokenRepository tokenRepository, IUserRepository userRepository,
                          string token, string currentPassword, string newPassword, string appKey, string device)
 {
     _tokenRepository = tokenRepository;
     _userRepository  = userRepository;
     _token           = token;
     _currentPassword = currentPassword;
     _newPassword     = newPassword;
     _appKey          = appKey;
     _device          = device;
     ValidateInstance();
     InvalidTokenExceptionCreator           = () => InvalidTokenException.Create(_token, _appKey, _device);
     InvalidCurrentPasswordExceptionCreator = () => InvalidCurrentPasswordException.Create();
 }
예제 #10
0
        public void InvalidTokenExceptionConstructorTest1()
        {
            string errorMessage = "Unauthorized";
            string errorCode    = "401";
            string source       = "Intuit.Ipp.Test";

            System.Exception      innerException = new ArgumentNullException();
            InvalidTokenException target         = new InvalidTokenException(errorMessage, errorCode, source, innerException);

            Assert.AreEqual(target.Message, errorMessage);
            Assert.AreEqual(target.ErrorCode, errorCode);
            Assert.AreEqual(target.Source, source);
            Assert.ReferenceEquals(target.InnerException, innerException);
        }
예제 #11
0
        public PlaceTokenResponse Execute(PlaceTokenRequest request)
        {
            Board board = request.Board;

            System.Exception error  = null;
            IBoardStatus     status = new Incomplete();

            try
            {
                ValidateTokenType(request);
                ValidatePositionFree(request);
                ValidateBoardIncomplete(request);

                board = _boardGateway.Write(request.Board, request.Type, request.Column, request.Row);

                _boardGateway.Flush(board);
            }
            catch (IndexOutOfRangeException)
            {
                error = new OffBoardException();
            }
            catch (AlreadyPlacedException)
            {
                error = new AlreadyPlacedException();
            }
            catch (InvalidTokenException)
            {
                error = new InvalidTokenException();
            }
            catch (BoardCompleteException)
            {
                error = new BoardCompleteException();
            }

            return(new PlaceTokenResponse
            {
                Board = board,
                Error = error,
                Status = board.IsComplete() ? (IBoardStatus) new Complete() : new Incomplete(),
            });
        }
예제 #12
0
        public void Fail_Parse_InvalidToken()
        {
            // Setup
            var token = $"-{Fakes.RandomString()}";
            var args = new[]
            {
                // so that it does not get confused with ProjectPath
                $"-{nameof(BuildArguments.Configuration)}",
                Fakes.RandomString(),
                token
            };
            var testException = new InvalidTokenException(token);

            // Execute
            var exception = Record.Exception(() => Program.MainInternal(_builderMock.Object, args));

            // Assert
            Assert.NotNull(exception);
            Assert.IsType<InvalidTokenException>(exception);
            Assert.Equal(exception.Message, testException.Message, StringComparer.InvariantCultureIgnoreCase);
        }
예제 #13
0
        public void InvalidTokenExceptionConstructorTest2()
        {
            string errorMessage = "Unauthorized";
            string errorCode    = "401";
            string source       = "Intuit.Ipp.Test";

            System.Exception      innerException = new ArgumentNullException();
            InvalidTokenException target         = new InvalidTokenException(errorMessage, errorCode, source, innerException);
            InvalidTokenException newTarget      = null;

            using (Stream s = new MemoryStream())
            {
                BinaryFormatter formatter = new BinaryFormatter();
                formatter.Serialize(s, target);
                s.Position = 0; // Reset stream position
                newTarget  = (InvalidTokenException)formatter.Deserialize(s);
            }

            Assert.IsNotNull(newTarget);
            Assert.AreEqual(newTarget.Message, errorMessage);
            Assert.AreEqual(newTarget.ErrorCode, errorCode);
            Assert.AreEqual(newTarget.Source, source);
            Assert.ReferenceEquals(newTarget.InnerException, innerException);
        }
예제 #14
0
        /// <summary>
        /// Parses the Response and throws appropriate exceptions.
        /// </summary>
        /// <param name="webException">Web Exception.</param>
        /// <param name="isIps">Specifies whether the exception is generated by an IPS call.</param>
        /// <returns>Ids Exception.</returns>
        internal IdsException ParseResponseAndThrowException(WebException webException, bool isIps = false)
        {
            IdsException idsException = null;

            // Checks whether the webException is null or not.
            if (webException != null)
            {
                // If not null then check the response property of the webException object.
                if (webException.Response != null)
                {
                    // There is a response from the Ids server. Cast it to HttpWebResponse.
                    HttpWebResponse errorResponse = (HttpWebResponse)webException.Response;

                    // Get the status code description of the error response.
                    string statusCodeDescription = errorResponse.StatusCode.ToString();

                    // Get the status code of the error response.
                    int    statusCode  = (int)errorResponse.StatusCode;
                    string errorString = string.Empty;

                    ICompressor responseCompressor = CoreHelper.GetCompressor(this.context, false);
                    if (!string.IsNullOrWhiteSpace(errorResponse.ContentEncoding) && responseCompressor != null)
                    {
                        using (var responseStream = errorResponse.GetResponseStream())
                        {
                            using (var decompressedStream = responseCompressor.Decompress(responseStream))
                            {
                                // Get the response stream.
                                StreamReader reader = new StreamReader(decompressedStream);

                                // Read the Stream
                                errorString = reader.ReadToEnd();
                                // Close reader
                                reader.Close();
                            }
                        }
                    }
                    else
                    {
                        using (Stream responseStream = errorResponse.GetResponseStream())
                        {
                            // Get the response stream.
                            StreamReader reader = new StreamReader(responseStream);

                            // Read the Stream
                            errorString = reader.ReadToEnd();
                            // Close reader
                            reader.Close();
                        }
                    }

                    string response_intuit_tid_header = "";
                    //get intuit_tid header
                    for (int i = 0; i < errorResponse.Headers.Count; ++i)
                    {
                        if (errorResponse.Headers.Keys[i] == "intuit_tid")
                        {
                            response_intuit_tid_header = errorResponse.Headers[i];
                        }
                    }
                    //Log errorstring to disk
                    CoreHelper.GetRequestLogging(this.context).LogPlatformRequests(" Response Intuit_Tid header: " + response_intuit_tid_header + ", Response Payload: " + errorString, false);

                    if (isIps)
                    {
                        IdsException exception = new IdsException(errorString, statusCode.ToString(CultureInfo.InvariantCulture), webException.Source);
                        this.context.IppConfiguration.Logger.CustomLogger.Log(TraceLevel.Error, exception.ToString());
                        return(exception);
                    }

                    // Use the above idsException to set to innerException of the specific exception which will be created below.

                    // Ids will set the following error codes. Depending on that we will be throwing specific exceptions.
                    switch (errorResponse.StatusCode)
                    {
                    // Bad Request: 400
                    case HttpStatusCode.BadRequest:
                        // Parse the error response and create the aggregate exception.
                        idsException = this.ParseErrorResponseAndPrepareException(errorString);
                        idsException = new IdsException(statusCodeDescription, statusCode.ToString(CultureInfo.InvariantCulture), webException.Source, idsException);
                        break;

                    // Unauthorized: 401
                    case HttpStatusCode.Unauthorized:
                        // Create Invalid Token Exception.
                        idsException = this.ParseErrorResponseAndPrepareException(errorString);
                        InvalidTokenException invalidTokenException = new InvalidTokenException(string.Format(CultureInfo.InvariantCulture, "{0}-{1}", statusCodeDescription, statusCode), idsException);
                        idsException = invalidTokenException;
                        break;

                    // ServiceUnavailable: 503
                    case HttpStatusCode.ServiceUnavailable:
                    // InternalServerError: 500
                    case HttpStatusCode.InternalServerError:
                    // Forbidden: 403
                    case HttpStatusCode.Forbidden:
                    // NotFound: 404
                    case HttpStatusCode.NotFound:
                        idsException = new IdsException(statusCodeDescription, statusCode.ToString(CultureInfo.InvariantCulture), webException.Source, new EndpointNotFoundException());
                        break;

                    // Throttle Exceeded: 429
                    case (HttpStatusCode)429:
                        idsException = new IdsException(statusCodeDescription, statusCode.ToString(CultureInfo.InvariantCulture), webException.Source, new ThrottleExceededException());
                        break;

                    // Default. Throw generic exception i.e. IdsException.
                    default:
                        // Parse the error response and create the aggregate exception.
                        // TODO: Do we need to give error string in exception also. If so then uncomemnt the below line.
                        // idsException = new IdsException(errorString, statusCode.ToString(CultureInfo.InvariantCulture), webException.Source);
                        idsException = new IdsException(statusCodeDescription, statusCode.ToString(CultureInfo.InvariantCulture), webException.Source);
                        break;
                    }
                }
            }

            // Return the Ids Exception.
            return(idsException);
        }
예제 #15
0
        public void On_token_error_response_is_set()
        {
            // 1. Arrange
            var attr    = new ValidateTokenDataAttribute();
            var context = new HttpActionContext
            {
                ActionDescriptor = new ReflectedHttpActionDescriptor()
            };
            const string tokenString = "token";

            context.ActionArguments.Add("request", new ValidateToken
            {
                AuthToken = tokenString
            });

            var playerId = Guid.NewGuid();
            var token    = playerId.ToString();
            var mtp      = new Mock <ITokenProvider>(MockBehavior.Strict);

            mtp
            .Setup(tp => tp.Decrypt(tokenString))
            .Returns(playerId);
            attr.TokenProvider = mtp.Object;

            var errorMessage = Guid.NewGuid().ToString();
            var exception    = new InvalidTokenException(errorMessage);

            var mtvp = new Mock <ITokenValidationProvider>(MockBehavior.Strict);

            mtvp
            .Setup(tvp => tvp.ValidateToken(token))
            .Throws(exception);     // error
            attr.TokenValidation = mtvp.Object;

            // ReSharper disable once RedundantAssignment
            string description = errorMessage;
            var    mErr        = new Mock <IErrorManager>(MockBehavior.Strict);

            mErr
            .Setup(em => em.GetErrorCodeByException(exception, out description))
            .Returns(GameApiErrorCode.SystemError);
            attr.ErrorManager = mErr.Object;

            var mLog = new Mock <IGameProviderLog>(MockBehavior.Strict);

            mLog
            .Setup(l => l.LogError(It.IsAny <string>(), exception));
            attr.Log = mLog.Object;

            var mJson = new Mock <IJsonSerializationProvider>(MockBehavior.Strict);

            mJson
            .Setup(j => j.SerializeToString(It.IsAny <GameApiResponseBase>()))
            .Returns <GameApiResponseBase>(o => o.ErrorDescription);
            attr.Json = mJson.Object;

            // 2. Act
            attr.OnActionExecuting(context);

            // 3. Assert
            Assert.That(context.Response.Content.ReadAsStringAsync().Result, Is.StringContaining(errorMessage));
            mtp.Verify(tp => tp.Decrypt(tokenString), Times.Once());
            mtvp.Verify(tvp => tvp.ValidateToken(token), Times.Once());
        }