public void GetCustomerProfileTest_InvalidIsacPrifile()
        {
            bool IsNewCustomer = true;
            CustomerHPIDUtils             custUtils    = new CustomerHPIDUtils();
            TokenDetails                  sessionToken = new TokenDetails();
            UserAuthenticationInterchange hppAuthInt   = new UserAuthenticationInterchange()
            {
                ClientId = "hpsa9"
            };

            User aProfile = new User()
            {
                EmailConsent = true
            };

            List <RoleMapping> roleMappings = new List <RoleMapping>();
            RoleMapping        role         = new RoleMapping();

            role.RoleId        = 1;
            role.RoleMappingId = 1;
            role.UserId        = 1;
            role.CreatedDate   = DateTime.UtcNow;
            roleMappings.Add(role);
            aProfile.RoleMappings = roleMappings;

            sessionToken.AccessToken = "sessionToken";
            hpidUtilsMock.Setup(x => x.GetIdsAndProfile(It.IsAny <CustomerIds>(), It.IsAny <string>(), It.IsAny <GetProfileResponse>())).Returns(true);

            isacMock.Setup(x => x.FindOrInsertHPIDProfile(It.IsAny <ResponseBase>(), It.IsAny <RequestFindOrInsertHPIDProfile>(), out IsNewCustomer)).Returns(aProfile);

            GetProfileResponse response = custUtils.GetCustomerProfileforHPID(hppAuthInt, sessionToken, false, It.IsAny <APIMethods>());

            Assert.IsTrue(response.ErrorList.Count == 1);
            Assert.IsTrue(IsNewCustomer);
        }
Пример #2
0
        public void GetRefreshTokenTest_Success()
        {
            TokenDetails accessToken = new TokenDetails()
            {
                AccessToken = "dasfdasfdasfadsfasdfdasfdasfds"
            };

            UserAuthentication appAuth = new UserAuthentication()
            {
                UserId = 123456
            };

            queryUtilsMock.Setup(q => q.GetHPPToken(It.IsAny <IIdeaDatabaseDataContext>(),
                                                    It.IsAny <String>(), It.IsAny <String>())).Returns(appAuth);


            User profile = new User()
            {
                RefreshToken = "refreshToken",
                CompanyName  = "companyName",
                UserId       = 123456
            };

            queryUtilsMock.Setup(q => q.GetUser(It.IsAny <IIdeaDatabaseDataContext>(), It.IsAny <int>())).Returns(profile);

            User expectedResponse = new UserUtils().GetRefreshToken("", accessToken);

            Assert.AreEqual(expectedResponse, profile);

            queryUtilsMock.Verify(q => q.GetHPPToken(It.IsAny <IIdeaDatabaseDataContext>(),
                                                     It.IsAny <String>(), It.IsAny <String>()), Times.Once);

            queryUtilsMock.Verify(q => q.GetUser(It.IsAny <IIdeaDatabaseDataContext>(), It.IsAny <int>()), Times.Once);
        }
Пример #3
0
 public WithInvalidToken(ITestOutputHelper output) : base(output)
 {
     _returnedDummyTokenDetails = new TokenDetails("123")
     {
         Expires = Now.AddDays(1), ClientId = "123"
     };
 }
Пример #4
0
        public async Task ClientWithExistingTokenReusesItForMakingRequests()
        {
            var options = new ClientOptions
            {
                ClientId          = "test",
                Key               = "best",
                UseBinaryProtocol = false,
                NowFunc           = TestHelpers.NowFunc()
            };
            var rest  = new AblyRest(options);
            var token = new TokenDetails("123")
            {
                Expires = DateTimeOffset.UtcNow.AddHours(1)
            };

            rest.AblyAuth.CurrentToken = token;

            rest.ExecuteHttpRequest = request =>
            {
                //Assert
                request.Headers["Authorization"].Should().Contain(token.Token.ToBase64());
                return("[{}]".ToAblyResponse());
            };

            await rest.StatsAsync();

            await rest.StatsAsync();

            await rest.StatsAsync();
        }
Пример #5
0
            private AblyRest GetConfiguredRestClient(int errorCode, TokenDetails tokenDetails, bool useApiKey = true)
            {
                var client = GetRestClient(request =>
                {
                    if (request.Url.Contains("/keys"))
                    {
                        return(_returnedDummyTokenDetails.ToJson().ToAblyResponse());
                    }

                    if (_firstAttempt)
                    {
                        _firstAttempt = false;
                        throw new AblyException(new ErrorInfo("", errorCode, HttpStatusCode.Unauthorized));
                    }
                    return(AblyResponse.EmptyResponse.ToTask());
                }, opts =>
                {
                    opts.TokenDetails = tokenDetails;
                    if (useApiKey == false)
                    {
                        opts.Key = "";
                    }
                });

                return(client);
            }
Пример #6
0
            public async Task WhenErrorCodeIsTokenSpecific_ShouldAutomaticallyTryToRenewTokenIfRequestFails(int errorCode)
            {
                //Now = DateTimeOffset.Now;
                var tokenDetails = new TokenDetails("id")
                {
                    Expires = Now.AddHours(1)
                };
                //Had to inline the method otherwise the tests intermittently fail.
                bool firstAttempt = true;
                var  client       = GetRestClient(request =>
                {
                    if (request.Url.Contains("/keys"))
                    {
                        return(_returnedDummyTokenDetails.ToJson().ToAblyResponse());
                    }

                    if (firstAttempt)
                    {
                        firstAttempt = false;
                        throw new AblyException(new ErrorInfo("", errorCode, HttpStatusCode.Unauthorized));
                    }
                    return(AblyResponse.EmptyResponse.ToTask());
                }, opts => opts.TokenDetails = tokenDetails);

                await client.StatsAsync();

                client.AblyAuth.CurrentToken.Expires.Should().BeCloseTo(_returnedDummyTokenDetails.Expires);
                client.AblyAuth.CurrentToken.ClientId.Should().Be(_returnedDummyTokenDetails.ClientId);
            }
Пример #7
0
        public string GetManagementTokenValue(string refreshToken)
        {
            string       access_token = "";
            string       token        = GetAccessTokenByRefreshTokenManagement(refreshToken);
            TokenDetails tokenDetails = new TokenDetails();

            if (!string.IsNullOrEmpty(token))
            {
                if (token.ToString().ToLower() == Constants.invalidCode.ToString().ToLower())
                {
                    tokenDetails.access_token = Constants.invalidCode;
                }
                else
                {
                    tokenDetails = Newtonsoft.Json.JsonConvert.DeserializeObject <TokenDetails>(token);
                    if (tokenDetails != null)
                    {
                        access_token = tokenDetails.access_token;
                    }
                    else
                    {
                        access_token = Constants.invalidToken;
                    }
                }
            }
            else
            {
                access_token = Constants.invalidToken;
            }
            return(access_token);
        }
        public async Task <IActionResult> Authenticate([FromBody] LoginDetails model)
        {
            // Check user exist in system or not
            var user = await _userManager.FindByNameAsync(model.UserName);

            if (user == null)
            {
                return(NotFound());
            }

            // Perform login operation
            var signInResult = await _signInManager.CheckPasswordSignInAsync(user, model.Password, true);

            if (signInResult.Succeeded)
            {
                // Obtain token
                TokenDetails token = await GetJwtSecurityTokenAsync(user);

                return(Ok(token));
            }
            else
            {
                return(BadRequest(new { message = "Username or password is incorrect" }));
            }
        }
        public void GetCustomerProfileforHPIDTest_MissingRefreshToken()
        {
            CustomerHPIDUtils custUtils = new CustomerHPIDUtils();

            TokenDetails sessionToken = new TokenDetails()
            {
                AccessToken    = "accessToken",
                tokenScopeType = TokenScopeType.apiProfileGetCall
            };

            hpidUtilsMock.Setup(x => x.GetIdsAndProfile(It.IsAny <CustomerIds>(), It.IsAny <string>(), It.IsAny <GetProfileResponse>())).
            Callback((CustomerIds i, string u, GetProfileResponse r) =>
            {
                r.ErrorList.Add(Faults.HPIDInvalidToken);
            }).Returns(false);

            User isaacUser = new User()
            {
                RefreshToken = null
            };

            isacMock.Setup(x => x.GetRefreshToken(It.IsAny <string>(), It.IsAny <TokenDetails>())).Returns(isaacUser);


            GetProfileResponse response = custUtils.GetCustomerProfileforHPID(new UserAuthenticationInterchange(), sessionToken, false, It.IsAny <APIMethods>());


            customerUtilsMock.Verify(x => x.UpdateLogoutDate(It.IsAny <ResponseBase>(),
                                                             It.IsAny <int>(), It.IsAny <string>(), It.IsAny <string>()), Times.Once);
            Assert.IsTrue(response.ErrorList.Count == 1);
            Assert.IsTrue(response.ErrorList.Contains(Faults.HPIDSessionTimeout));
        }
        public dynamic checkToken(string Token)
        {
            LystenEntities _db      = new LystenEntities();
            var            chkToken = _db.AppAccessTokens.AsEnumerable().Where(top => top.AuthToken == Token).FirstOrDefault();

            if (chkToken == null)
            {
                return(false);
            }
            User_Master model = _db.User_Master.Where(x => x.Id == chkToken.UserId).FirstOrDefault();

            if (chkToken.ExpiresOn <= DateTime.Now)
            {
                //TimeSpan t = new TimeSpan(1, 0, 0, 0, 0);
                //chkToken.ExpiresOn = DateTime.Now.Add(t);
                //_db.SaveChanges();
                BaseApiController.updatetoken = true;
                TokenDetails objToken = api.Helpers.AsyncHelpers.RunSync <TokenDetails>(() => BaseApiController.generatToken(model.Email, model.Password, model.DeviceToken));
                if (String.IsNullOrEmpty(objToken.error))
                {
                    BaseApiController.Add_UpdateToken(model.Id, objToken);
                    BaseApiController.accessToken = objToken.access_token;
                }
                return(true);
            }
            BaseApiController.updatetoken = false;
            BaseApiController.accessToken = "";
            return(true);
        }
Пример #11
0
        public GetProfileResponse GetCustomerProfileByTestLogin(UserAuthenticationInterchange UserAuthInterchange, bool RetainOldValues, APIMethods apiRetainOldValues)
        {
            GetProfileResponse response = new GetProfileResponse();

            UserAuthInterchange.UserName = "******";
            UserAuthInterchange.Password = "******";
            //UserAuthInterchange.UserName = UserAuthInterchange.UserName;
            //UserAuthInterchange.Password = UserAuthInterchange.Password;
            //UserAuthInterchange.UserId = UserAuthInterchange.UserId;

            if (string.IsNullOrEmpty(UserAuthInterchange.UserName) || string.IsNullOrEmpty(UserAuthInterchange.Password))
            {
                response.ErrorList.Add(Responses.Faults.InvalidCredentials);
                return(response);
            }

            TokenDetails sessionToken = null;

            response = GetCustomerProfileforHPIDTEST(UserAuthInterchange, sessionToken, RetainOldValues, apiRetainOldValues);
            foreach (var fault in response.ErrorList)
            {
                var error = string.Format("origin={0},Return code={1},status Text={2}", fault.Origin, fault.ReturnCode, fault.DebugStatusText);
                log.Debug(string.Format($"ProfileByLogin: Caller={UserAuthInterchange.CallerId},Exception={error}"));
            }
            return(response);
        }
Пример #12
0
        public void ShouldExcludeClientIdWhenNull()
        {
            var details = new TokenDetails("123");
            var json    = JsonHelper.Serialize(details);

            json.Should().NotContain("clientId");
        }
Пример #13
0
        public void ClientWithExistingTokenReusesItForMakingRequests()
        {
            var options = new AblyOptions
            {
                ClientId          = "test",
                Key               = "best",
                UseBinaryProtocol = false
            };
            var rest  = new RestClient(options);
            var token = new TokenDetails("123")
            {
                Expires = DateTimeOffset.UtcNow.AddHours(1)
            };

            rest.CurrentToken = token;

            rest.ExecuteHttpRequest = request =>
            {
                //Assert
                request.Headers["Authorization"].Should().Contain(token.Token.ToBase64());
                return(new AblyResponse()
                {
                    TextResponse = "[{}]"
                });
            };

            rest.Stats();
            rest.Stats();
            rest.Stats();
        }
Пример #14
0
        public GetProfileResponse GetCustomerProfileforHPID(UserAuthenticationInterchange UserAuthInterchange, TokenDetails sessionTokenDetails, bool RetainOldValues, APIMethods apiRetainOldValues)
        {
            logger.Info($"GetCustomerProfileforHPID={sessionTokenDetails.AccessToken}");
            GetProfileResponse response     = new GetProfileResponse();
            TokenDetails       sessionToken = sessionTokenDetails;


            // try to get HPID profile with existing session token
            CustomerIds idS = new CustomerIds();

            if (GetProfileBySessionToken(response, sessionToken, idS))
            {
                return(GetCustomerProfileFromHPIDAndDatabase(response, UserAuthInterchange, sessionToken, idS, RetainOldValues, apiRetainOldValues));
            }

            // if get profile failed not by expired token, but because of other errors, then do not use refresh token
            if (!response.ErrorList.Contains(Responses.Faults.HPIDInvalidToken))
            {
                return(response);
            }

            // if profile it recognized by access token, then do not use refresh token
            if (sessionToken.tokenScopeType == TokenScopeType.apiProfileGetByTokenCall)
            {
                response.ErrorList.Clear();
                response.ErrorList.Add(Responses.Faults.InvalidCredentials);
                return(response);
            }


            // try to get HPID profile with refresh token
            return(GetProfileByRefreshToken(response, sessionToken, UserAuthInterchange.UserId, UserAuthInterchange.CallerId));
        }
Пример #15
0
        public async Task <TokenDetails> GetTokenByRefreshToken()
        {
            //TODO : It returns badRequest. Need to fix it
            var content = new FormUrlEncodedContent(new[]
            {
                new KeyValuePair <string, string>("client_id", config.Value.ClientId)
                , new KeyValuePair <string, string>("client_secret", config.Value.ClientSecret)
                , new KeyValuePair <string, string>("grant_type", "refresh_token")
                , new KeyValuePair <string, string>("refresh_token", tokenStorage.Get <TokenDetails>(config.Value.TokenKey).RefreshToken)
            });


            var client   = httpHelpers.GetClient(config.Value.OAuthServerUrl);
            var response = await client.PostAsync("/connect/token", content);

            if (response.IsSuccessStatusCode)
            {
                dynamic result             = JsonConvert.DeserializeObject <dynamic>(await response.Content.ReadAsStringAsync());
                var     jwtSecurityHandler = new JwtSecurityTokenHandler();
                var     user = (JwtSecurityToken)jwtSecurityHandler.ReadJwtToken(result.access_token.ToString());

                var tokens = new TokenDetails
                {
                    AccessToken  = result.access_token,
                    RefreshToken = result.refresh_token,
                    ExpiryDate   = FromUnixTime(user.Claims.Where(x => x.Type == "exp").FirstOrDefault().Value)
                };

                tokenStorage.Clear();
                tokenStorage.Store(tokens, config.Value.TokenKey);
                return(tokens);
            }
            return(new TokenDetails());
        }
Пример #16
0
        public static async Task <TokenDetails> generatToken(string Email, string Password, string deviceid)
        {
            var request         = HttpContext.Current.Request;
            var tokenServiceUrl = request.Url.GetLeftPart(UriPartial.Authority) + request.ApplicationPath + "/oauth/Token";

            using (var client = new HttpClient())
            {
                var requestParams = new List <KeyValuePair <string, string> >
                {
                    new KeyValuePair <string, string>("grant_type", "password"),
                    new KeyValuePair <string, string>("username", Email),
                    new KeyValuePair <string, string>("password", Password),
                    new KeyValuePair <string, string>("deviceid", deviceid)
                };
                var requestParamsFormUrlEncoded = new FormUrlEncodedContent(requestParams);
                var tokenServiceResponse        = client.PostAsync(tokenServiceUrl, requestParamsFormUrlEncoded).Result;
                var responseString = await tokenServiceResponse.Content.ReadAsStringAsync();

                var responseCode = tokenServiceResponse.StatusCode;
                JavaScriptSerializer jsonSerializer = new JavaScriptSerializer();
                TokenDetails         objToken       = jsonSerializer.Deserialize <TokenDetails>(responseString.ToString());
                //detocken(objToken.access_token);
                return(objToken);
            }
        }
Пример #17
0
        /// <summary>
        ///  Description : Get login details from code
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        public string GetRefreshTokenValue(string code)
        {
            string refresh_token = "";
            string token         = GetAccessToken(code);

            if (!string.IsNullOrEmpty(token))
            {
                if (token.ToString().ToLower() == Constants.invalidCode.ToString().ToLower())
                {
                    refresh_token = Constants.invalidCode;
                }
                else
                {
                    TokenDetails tokenDetails = Newtonsoft.Json.JsonConvert.DeserializeObject <TokenDetails>(token);
                    if (tokenDetails != null)
                    {
                        refresh_token = tokenDetails.refresh_token;
                    }
                    else
                    {
                        refresh_token = Constants.invalidToken;
                    }
                }
            }
            else
            {
                refresh_token = Constants.invalidToken;
            }
            return(refresh_token);
        }
        public async Task RunAsync()
        {
            //string startdate = GeneralHelper.ResetTimeToStartOfDay(new DateTime(2017, 01, 25)).ToString("MM/dd/yyyy HH:mm:ss");
            //string enddate = GeneralHelper.ResetTimeToStartOfDay(new DateTime(2017, 01, 26)).ToString("MM/dd/yyyy HH:mm:ss");

            try
            {
                TokenDetails    objTokenDetails    = new TokenDetails();
                MerchantDetails objMerchantDetails = new MerchantDetails();
                Orders          objOrders          = new Orders();
                MenuItems       objMenuItems       = new MenuItems();
                EmployeeDetails objEmployeeDetails = new EmployeeDetails();

                AuthenticationMethodResultModel result = await objTokenDetails.GetTalechAPI_Token();

                LogHelper.Log("Access token:" + result.access_token + " Expires in:" + result.expires_in + " token_type:" + result.token_type);

                Token.securityToken = result.access_token;

                List <MerchantIdentification_StoreName> lstAllMerchantStoreInformation = await objMerchantDetails.GetAllMerchantStoreDetails();

                LogHelper.Log("Merchant Store Count: " + lstAllMerchantStoreInformation.Count() + " Time: " + DateTime.Now);

                await objMenuItems.GetMenuItemsByCriteria(lstAllMerchantStoreInformation);

                //await objMenuItems.GetMenuUpdatesByCriteria(lstAllMerchantStoreInformation);
                //LogHelper.Log("Menu Item and Category method completed. Count: " + lstAllMenuResultModel.Count() + " Time: " + DateTime.Now);

                List <MerchantIdentification_StoreName> lstAllMerchantStoreInformationawait = await objEmployeeDetails.GetEmployeeByCriteria(lstAllMerchantStoreInformation);

                LogHelper.Log("Get Employee list method completed. Time: " + DateTime.Now);

                //tustin
                //irvine
                //euclid
                //huntington beach
                //cypress,fountain valley,alhambra,artesia,chino hills,westminster,tustin,irvine,euclid,huntington beach,costa mesa
                lstAllMerchantStoreInformation = lstAllMerchantStoreInformation.
                                                 Where(s => s.merchantStoreName.ToLower() == "tustin").ToList();

                string startdate = GeneralHelper.ResetTimeToStartOfDay(new DateTime(2018, 01, 25)).ToString("MM/dd/yyyy HH:mm:ss");
                string enddate   = GeneralHelper.ResetTimeToStartOfDay(new DateTime(2018, 01, 26)).ToString("MM/dd/yyyy HH:mm:ss");
                await objOrders.GetOrderHistoryByCriteriaTestNew(lstAllMerchantStoreInformation, startdate, enddate);

                //await GetOrderHistoryByCriteriaTest(lstAllMerchantStoreInformation, startdate, enddate);
                //await GetOrderHistoryByCriteria(lstAllMerchantStoreInformation, startdate, enddate);
                LogHelper.Log("GetOrderHistoryByCriteriaTestNew method completed for Start Date: " + startdate + " End Date: " + enddate + " Time: " + DateTime.Now);

                //await GetOrderDetailsByOrderID(lstAllMerchantStoreInformation);
                //await LogOff(lstAllMerchantStoreInformation);
                //await DownloadStoreRevenueReport(lstAllMerchantStoreInformation,startdate,enddate);
                //LogHelper.Log("DownloadStoreRevenueReport method completed for Start Date: " + startdate + " End Date: " + enddate + " Time: " + DateTime.Now);

                // Console.WriteLine("File saved successfully");
            }
            catch (Exception ex)
            {
                LogHelper.Log("Erro in Run Async method. Error: " + ex.Message);
            }
        }
Пример #19
0
        public async Task WithTokenErrorAndTokenRenewalFails_ShouldRaiseErrorAndTransitionToFailed()
        {
            var tokenDetails = new TokenDetails("id")
            {
                Expires = Now.AddHours(1)
            };
            var client = GetClientWithFakeTransport(opts =>
            {
                opts.TokenDetails      = tokenDetails;
                opts.UseBinaryProtocol = false;
            }, request =>
            {
                if (request.Url.Contains("/keys"))
                {
                    throw new AblyException(new ErrorInfo()
                    {
                        Code = 123
                    });
                }

                return(AblyResponse.EmptyResponse.ToTask());
            });

            await client.FakeProtocolMessageReceived(new ProtocolMessage(ProtocolMessage.MessageAction.Error) { Error = new ErrorInfo("Unauthorised", _tokenErrorCode, HttpStatusCode.Unauthorized) });

            client.Connection.State.Should().Be(ConnectionState.Failed);
            client.Connection.ErrorReason.Should().NotBeNull();
            client.Connection.ErrorReason.Code.Should().Be(123);
        }
Пример #20
0
        public static TokenDetails ValidateSecurityToken(string encryptedToken)
        {
            var tokenDetails = new TokenDetails();

            try
            {
                //Validate data
                if (string.IsNullOrEmpty(encryptedToken))
                {
                    tokenDetails.TokenStatus = TokenStatus.NotProvided;
                }
                else
                {
                    var decrytedToken = Cryptology.DecryptString(encryptedToken.Trim());
                    //Check if the token was decrypted successfully
                    if (string.IsNullOrEmpty(decrytedToken))
                    {
                        tokenDetails.TokenStatus = TokenStatus.Invalid;
                    }
                    else
                    {
                        var tokenData = decrytedToken.Split(new[] { "##" }, StringSplitOptions.None);
                        tokenDetails.UserId      = Convert.ToInt32(tokenData[1]);
                        tokenDetails.TokenStatus = (Convert.ToDateTime(tokenData[2]) > DateTime.UtcNow) ? TokenStatus.Valid : TokenStatus.Expired;
                    }
                }
            }
            catch (Exception ex)
            {
                //Log exception
                tokenDetails.TokenStatus = TokenStatus.Invalid;
                //SystemLogger.WriteError("Exception occured in ValidateSecurityToken method\n" + ex.Message);
            }
            return(tokenDetails);
        }
Пример #21
0
        public GetProfileResponse GetCustomerProfileByAuthentication(UserAuthenticationInterchange UserAuthInterchange, bool RetainOldValues, string AccessCode, string RedirectUrl, APIMethods apiRetainOldValues, string ClientId = null)
        {
            GetProfileResponse response = new GetProfileResponse();

            if (string.IsNullOrEmpty(AccessCode) || string.IsNullOrEmpty(RedirectUrl))
            {
                response.ErrorList.Add(Responses.Faults.InvalidCredentials);
                return(response);
            }

            TokenDetails sessionToken = hpidUtils.GetHPIDSessionToken((int)TokenScopeType.userAuthenticate, AccessCode, RedirectUrl, response, ClientId);

            if (response.ErrorList.Count > 0)
            {
                return(response);
            }

            response = GetCustomerProfileforHPID(UserAuthInterchange, sessionToken, RetainOldValues, apiRetainOldValues);
            if (response.ErrorList.Count > 0)
            {
                foreach (var fault in response.ErrorList)
                {
                    var error = string.Format("origin={0},Return code={1},status Text={2}", fault.Origin, fault.ReturnCode, fault.DebugStatusText);
                    log.Debug(string.Format($"ProfileByAuth: Accesscode={AccessCode}, RedirectURL={RedirectUrl}, Exception={error}"));
                }
            }

            return(response);
        }
Пример #22
0
        public async Task WithTokenErrorAndNonRenewableToken_ShouldRaiseErrorAndTransitionToFailed()
        {
            var tokenDetails = new TokenDetails("id")
            {
                Expires = Now.AddHours(1)
            };
            bool renewTokenCalled = false;
            var  client           = GetClientWithFakeTransport(opts =>
            {
                opts.Key               = "";
                opts.TokenDetails      = tokenDetails;
                opts.UseBinaryProtocol = false;
            }, request =>
            {
                if (request.Url.Contains("/keys"))
                {
                    renewTokenCalled = true;
                    return(_returnedDummyTokenDetails.ToJson().ToAblyResponse());
                }

                return(AblyResponse.EmptyResponse.ToTask());
            });

            await client.FakeProtocolMessageReceived(new ProtocolMessage(ProtocolMessage.MessageAction.Error) { Error = new ErrorInfo("Unauthorised", _tokenErrorCode, HttpStatusCode.Unauthorized) });

            renewTokenCalled.Should().BeFalse();
            client.Connection.State.Should().Be(ConnectionState.Failed);
            client.Connection.ErrorReason.Should().NotBeNull();
            client.Connection.ErrorReason.Code.Should().Be(_tokenErrorCode);
        }
        public void CreateCustomerProfileTest_MissingSessionToken()
        {
            CustomerHPIDUtils custUtils    = new CustomerHPIDUtils();
            TokenDetails      sessionToken = new TokenDetails();

            GetProfileResponse response = custUtils.GetCustomerProfileforHPID(null, sessionToken, false, It.IsAny <APIMethods>());

            Assert.IsTrue(response.ErrorList.Contains(Faults.InvalidCredentials));
        }
Пример #24
0
        public async Task WithTokenErrorAndRenewableToken_ShouldRenewTokenAutomaticallyWithoutEmittingError()
        {
            var tokenDetails = new TokenDetails("id")
            {
                Expires = Now.AddHours(1)
            };
            bool renewTokenCalled = false;
            var  client           = GetClientWithFakeTransport(
                opts =>
            {
                opts.TokenDetails      = tokenDetails;
                opts.UseBinaryProtocol = false;
                opts.AutoConnect       = false;
            }, request =>
            {
                if (request.Url.Contains("/keys"))
                {
                    if (renewTokenCalled == false)
                    {
                        renewTokenCalled = true;
                    }

                    return(_returnedDummyTokenDetails.ToJson().ToAblyResponse());
                }

                return(AblyResponse.EmptyResponse.ToTask());
            });

            client.Connect();
            List <ErrorInfo> raisedErrors = new List <ErrorInfo>();

            client.Connection.On((args) =>
            {
                if (args.HasError)
                {
                    raisedErrors.Add(args.Reason);
                }
            });

            await client.WaitForState(ConnectionState.Connecting);

            client.FakeProtocolMessageReceived(new ProtocolMessage(ProtocolMessage.MessageAction.Error)
            {
                Error = new ErrorInfo("Unauthorised", ErrorCodes.TokenError, HttpStatusCode.Unauthorized)
            });

            await client.ProcessCommands();

            renewTokenCalled.Should().BeTrue();
            var currentToken = client.RestClient.AblyAuth.CurrentToken;

            currentToken.Token.Should().Be(_returnedDummyTokenDetails.Token);
            currentToken.ClientId.Should().Be(_returnedDummyTokenDetails.ClientId);
            currentToken.Expires.Should().BeCloseTo(_returnedDummyTokenDetails.Expires, TimeSpan.FromMilliseconds(20));
            raisedErrors.Should().BeEmpty("No errors should be raised!");
        }
Пример #25
0
        private bool GetProfileBySessionToken(GetProfileResponse response, TokenDetails sessionToken, CustomerIds idS)
        {
            if (sessionToken == null || string.IsNullOrEmpty(sessionToken.AccessToken))
            {
                response.ErrorList.Add(Responses.Faults.InvalidCredentials);
                return(false);
            }

            return(hpidUtils.GetIdsAndProfile(idS, sessionToken.AccessToken, response));
        }
        public void GetCustomerProfileforHPIDTest_Success()
        {
            CustomerHPIDUtils custUtils = new CustomerHPIDUtils();

            User isaacUser = new User()
            {
                UserId           = 120034,
                RefreshToken     = "refreshToken",
                RefreshTokenType = 1,
                ActiveHealth     = true,
                EmailConsent     = true,
                PrimaryUse       = PrimaryUseType.Item003.ToString()
            };

            isacMock.Setup(x => x.GetRefreshToken(It.IsAny <string>(), It.IsAny <TokenDetails>())).Returns(isaacUser);


            TokenDetails sessionToken = new TokenDetails()
            {
                AccessToken    = "expiredAccessToken",
                tokenScopeType = TokenScopeType.apiProfileGetCall
            };

            hpidUtilsMock.Setup(x => x.GetIdsAndProfile(It.IsAny <CustomerIds>(), It.IsAny <string>(), It.IsAny <GetProfileResponse>())).
            Callback((CustomerIds i, string u, GetProfileResponse r) =>
            {
                r.ErrorList.Add(Faults.HPIDInvalidToken);
            }).Returns(false);

            queryUtilsMock.Setup(x => x.GetHPPToken(It.IsAny <IIdeaDatabaseDataContext>(), It.IsAny <int>(), It.IsAny <string>())).
            Returns(new UserAuthentication()
            {
                UserId = 123, ClientId = "Test"
            });

            TokenDetails refreshToken = new TokenDetails()
            {
                AccessToken = "newAccessToken"
            };

            hpidUtilsMock.Setup(x => x.GetHPIDSessionToken(It.IsAny <int>(), It.IsAny <string>(), It.IsAny <string>(), It.IsAny <ResponseBase>(), It.IsAny <string>(), It.IsAny <int>()))
            .Returns(refreshToken);
            hpidUtilsMock.Setup(x => x.GetIdsAndProfile(It.IsAny <CustomerIds>(), It.IsIn <string>(refreshToken.AccessToken), It.IsAny <GetProfileResponse>())).
            Callback((CustomerIds i, string u, GetProfileResponse r) =>
            {
                r.CustomerProfileObject = new CustomerProfile();
            }).Returns(true);

            GetProfileResponse response = custUtils.GetCustomerProfileforHPID(new UserAuthenticationInterchange(), sessionToken, It.IsAny <bool>(), It.IsAny <APIMethods>());

            hpidUtilsMock.Verify(x => x.GetHPIDSessionToken(It.IsAny <int>(), It.IsAny <string>(), It.IsAny <string>(), It.IsAny <ResponseBase>(), It.Is <string>(y => y == "Test"), It.IsAny <int>()), Times.Once);
            Assert.IsTrue(response.ErrorList.Count == 0);
            Assert.IsTrue(response.CustomerProfileObject.ActiveHealth == isaacUser.ActiveHealth);
            Assert.IsTrue(response.CustomerProfileObject.EmailConsent == EmailConsentType.Y.ToString());
        }
Пример #27
0
        public async Task WithTokenErrorTwice_ShouldNotRenewAndRaiseErrorAndTransitionToDisconnected()
        {
            var tokenDetails = new TokenDetails("id")
            {
                Expires = Now.AddHours(1)
            };
            var renewCount = 0;
            var client     = GetClientWithFakeTransport(
                opts =>
            {
                opts.TokenDetails      = tokenDetails;
                opts.UseBinaryProtocol = false;
                opts.AutoConnect       = false;
            }, request =>
            {
                if (request.Url.Contains("/keys"))
                {
                    renewCount++;
                    return(_returnedDummyTokenDetails.ToJson().ToAblyResponse());
                }

                return(AblyResponse.EmptyResponse.ToTask());
            });

            bool disconnected = false;

            client.Connection.On(ConnectionEvent.Disconnected, (_) =>
            {
                disconnected = true;
            });
            client.Connect();

            await client.WaitForState(ConnectionState.Connecting);

            client.FakeProtocolMessageReceived(new ProtocolMessage(ProtocolMessage.MessageAction.Error)
            {
                Error = new ErrorInfo("Unauthorised", ErrorCodes.TokenError, HttpStatusCode.Unauthorized)
            });

            await client.ProcessCommands();

            client.FakeProtocolMessageReceived(new ProtocolMessage(ProtocolMessage.MessageAction.Error)
            {
                Error = new ErrorInfo("Unauthorised", ErrorCodes.TokenError, HttpStatusCode.Unauthorized)
            });

            await client.ProcessCommands();

            await client.WaitForState(ConnectionState.Disconnected);

            renewCount.Should().Be(1);
            disconnected.Should().BeTrue();
            client.Connection.ErrorReason.Should().NotBeNull();
        }
        public void GetHPIDSessionTokenTest_InvalidLoginCredentials()
        {
            HPIDUtils hpu = new HPIDUtils();

            ResponseBase response = new ResponseBase();

            sessionToken = hpu.GetHPIDSessionToken(0, null, null, response, null);

            Assert.IsNull(sessionToken);
            Assert.IsTrue(response.ErrorList.Where(x => x.ReturnCode.Equals("InvalidCredentials")).Count() == 1);
        }
Пример #29
0
        public static TokenDetails ReturnTokenCache(string key)
        {
            TokenDetails finalresult = new TokenDetails();
            var          cache       = RedisConnectorHelper.Connection.GetDatabase();
            var          value       = cache.StringGet(key);
            string       result      = value.ToString();
            dynamic      obj         = JsonConvert.DeserializeObject(result);

            finalresult.expirydate = Convert.ToInt32(obj.expirydate);
            finalresult.token      = Convert.ToString(obj.token);
            return(finalresult);
        }
Пример #30
0
        public static void Add_UpdateToken(int userId, TokenDetails _token, int forceupdate = 0, string deviceType = null)
        {
            try
            {
                LystenEntities db       = new LystenEntities();
                var            chkToken = db.AppAccessTokens.Where(x => x.UserId == userId).FirstOrDefault();
                if (chkToken != null)
                {
                    if (chkToken.ExpiresOn <= DateTime.Now)
                    {
                        db.Entry(chkToken).State = EntityState.Modified;

                        TimeSpan t = TimeSpan.FromMinutes(Convert.ToInt16(ConfigurationManager.AppSettings["TokenExpireHour"].ToString()));
                        chkToken.AuthToken = _token.access_token;
                        chkToken.ExpiresOn = DateTime.Now.Add(t);
                        chkToken.IssuedOn  = DateTime.Now;

                        db.SaveChanges();
                    }
                    else
                    {
                        if (forceupdate > 0)
                        {
                            db.Entry(chkToken).State = EntityState.Modified;

                            TimeSpan t = TimeSpan.FromMinutes(Convert.ToInt16(ConfigurationManager.AppSettings["TokenExpireHour"].ToString()));
                            chkToken.AuthToken  = _token.access_token;
                            chkToken.ExpiresOn  = DateTime.Now.Add(t);
                            chkToken.IssuedOn   = DateTime.Now;
                            chkToken.DeviceType = deviceType;
                            db.SaveChanges();
                        }
                    }
                }
                else
                {
                    AppAccessToken _tokenDetails = new AppAccessToken();
                    _tokenDetails.UserId   = userId;
                    _tokenDetails.IssuedOn = DateTime.Now;
                    TimeSpan t = TimeSpan.FromMinutes(Convert.ToInt16(ConfigurationManager.AppSettings["TokenExpireHour"].ToString()));
                    _tokenDetails.ExpiresOn  = DateTime.Now.Add(t);
                    _tokenDetails.AuthToken  = _token.access_token;
                    _tokenDetails.DeviceType = deviceType;
                    db.AppAccessTokens.Add(_tokenDetails);
                    db.SaveChanges();
                }
                db.Dispose();
            }
            catch (Exception ex)
            {
            }
        }