public void LoginTest_ReturnsFault()
        {
            RESTAPIProfileController api = new RESTAPIProfileController();
            RESTAPILoginCredentials  req = new RESTAPILoginCredentials()
            {
                UserName = "",
                Password = "",
                CallerId = "",
                Platform = "",
                Locale   = ""
            };
            GetProfileResponse profileRes = new GetProfileResponse()
            {
                ErrorList = new HashSet <Fault>()
                {
                    new Fault("Profile", "", "")
                }
            };

            //customerMock.Setup(x => x.GetCustomerProfile(It.IsAny<UserAuthenticationInterchange>(), It.IsAny<bool>())).Returns(profileRes);
            hpidMock.Setup(x => x.GetCustomerProfileByTestLogin(It.IsAny <UserAuthenticationInterchange>(), It.IsAny <bool>(), It.IsAny <APIMethods>())).Returns(profileRes);

            RESTAPILoginResponse response = api.Login(req);

            Assert.IsTrue(response.ErrorList.Count == 1);
            Assert.AreEqual(response.ErrorList.First().Origin, "Profile");
        }
        public void LoginHPIDTest_ReturnsFault()
        {
            SettingRepository.SetSettingsRepositoryData(new List <AdmSettings>()
            {
                new AdmSettings {
                    ParamName = "HPIDEnabled", StringValue = "true"
                }
            });

            RESTAPIProfileController api = new RESTAPIProfileController();
            RESTAPILoginCredentials  req = new RESTAPILoginCredentials()
            {
                UserName = "",
                Password = "",
                CallerId = "",
                Platform = "",
                Locale   = ""
            };
            GetProfileResponse profileRes = new GetProfileResponse()
            {
                ErrorList = new HashSet <Fault>()
                {
                    new Fault("Profile", "", "")
                }
            };

            hpidMock.Setup(x => x.GetCustomerProfileByTestLogin(It.IsAny <UserAuthenticationInterchange>(), It.IsAny <bool>(), It.IsAny <APIMethods>())).Returns(profileRes);
            RESTAPILoginResponse response = api.Login(req);

            Assert.IsTrue(response.ErrorList.Count == 1);
            Assert.AreEqual(response.ErrorList.First().Origin, "Profile");
        }
        public void LoginTest_ReturnsValidCredentials_CallRegisterMobile()
        {
            RESTAPIProfileController api = new RESTAPIProfileController();
            RESTAPILoginCredentials  req = new RESTAPILoginCredentials()
            {
                UserName    = "",
                Password    = "",
                CallerId    = "callerId",
                Platform    = "PLATFORM",
                DeviceToken = "deviceToken"
            };
            GetProfileResponse profileRes = new GetProfileResponse()
            {
                Credentials = new AccessCredentials()
                {
                    UserID = 1000, SessionToken = "sessionToken"
                },
                CustomerProfileObject = new CustomerProfile()
                {
                    ActiveHealth = true
                }
            };

            hpidMock.Setup(x => x.GetCustomerProfileByTestLogin(It.IsAny <UserAuthenticationInterchange>(), It.IsAny <bool>(), It.IsAny <APIMethods>())).Returns(profileRes);

            //customerMock.Setup(x => x.GetCustomerProfile(It.IsAny<UserAuthenticationInterchange>(), It.IsAny<bool>())).Returns(profileRes);

            RESTAPILoginResponse response = api.Login(req);

            Assert.IsTrue(response.ErrorList.Count == 0);
        }
        public void LoginTest_SessionTimeOutResponse()
        {
            DateTime loginDate = new DateTime(2019, 11, 28, 05, 06, 00);

            RESTAPIProfileController api = new RESTAPIProfileController();
            RESTAPILoginCredentials  req = new RESTAPILoginCredentials()
            {
                UserName = "",
                Password = "",
                CallerId = "",
                Platform = "",
                Locale   = "pl-PL"
            };
            GetProfileResponse profileRes = new GetProfileResponse()
            {
                Credentials = new AccessCredentials()
                {
                    UserID = 1000, SessionToken = "sessionToken", CallerId = "callerId"
                },
                CustomerProfileObject = new CustomerProfile()
                {
                    ActiveHealth = true
                },
                LoginDate = loginDate
            };

            hpidMock.Setup(x => x.GetCustomerProfileByTestLogin(It.IsAny <UserAuthenticationInterchange>(), It.IsAny <bool>(), It.IsAny <APIMethods>())).Returns(profileRes);

            //customerMock.Setup(x => x.GetCustomerProfile(It.IsAny<UserAuthenticationInterchange>(), It.IsAny<bool>())).Returns(profileRes);

            RESTAPILoginResponse response = api.Login(req);

            Assert.IsNotNull(response.TimeOut);
            Assert.AreEqual("2019-11-28T06:06:00Z", response.TimeOut);
        }
        public void LoginTest_ReturnSsessionToken()
        {
            RESTAPIProfileController api = new RESTAPIProfileController();
            RESTAPILoginCredentials  req = new RESTAPILoginCredentials()
            {
                UserName = "",
                Password = "",
                CallerId = "",
                Platform = "",
                Locale   = "en-US"
            };
            GetProfileResponse profileRes = new GetProfileResponse()
            {
                Credentials = new AccessCredentials()
                {
                    UserID = 1000, SessionToken = "sessionToken", CallerId = "callerId"
                },
                CustomerProfileObject = new CustomerProfile()
                {
                    ActiveHealth = true
                }
            };

            hpidMock.Setup(x => x.GetCustomerProfileByTestLogin(It.IsAny <UserAuthenticationInterchange>(), It.IsAny <bool>(), It.IsAny <APIMethods>())).Returns(profileRes);

            //customerMock.Setup(x => x.GetCustomerProfile(It.IsAny<UserAuthenticationInterchange>(), It.IsAny<bool>())).Returns(profileRes);
            RESTAPILoginResponse response = api.Login(req);

            Assert.IsTrue(response.SessionToken.Equals("sessionToken"));
        }
        public void AuthenticateTest_MobileDeviceError()
        {
            GetProfileResponse response = new GetProfileResponse()
            {
                Credentials           = new Credentials.AccessCredentials(),
                CustomerProfileObject = new CustomerProfile()
            };

            authMock.Setup(x => x.GetCustomerProfileByAuthentication(It.IsAny <UserAuthenticationInterchange>(), It.IsAny <bool>(), It.IsAny <string>(), It.IsAny <string>(), It.IsAny <APIMethods>(), It.IsAny <string>())).Returns(response);

            ResponseBase res = new ResponseBase()
            {
                ErrorList = new HashSet <Fault>()
                {
                    new Fault("", "", "")
                }
            };

            RESTAPIAuthCredentials req = new RESTAPIAuthCredentials()
            {
                DeviceToken = "SDILASNP",
                Platform    = "platform"
            };
            RESTAPILoginResponse expectedResponse = acontroler.Authenticate(req);

            Assert.IsTrue(expectedResponse.ErrorList.Count == 0);

            authMock.Verify(x => x.GetCustomerProfileByAuthentication(It.IsAny <UserAuthenticationInterchange>(), It.IsAny <bool>(), It.IsAny <string>(), It.IsAny <string>(), It.IsAny <APIMethods>(), It.IsAny <string>()), Times.Once);
        }
        public void AuthenticateTest_EmptyOrNullDevicetoken()
        {
            GetProfileResponse response = new GetProfileResponse()
            {
                Credentials           = new Credentials.AccessCredentials(),
                CustomerProfileObject = new CustomerProfile()
                {
                    ActiveHealth = true
                }
            };

            authMock.Setup(x => x.GetCustomerProfileByAuthentication(It.IsAny <UserAuthenticationInterchange>(), It.IsAny <bool>(), It.IsAny <string>(), It.IsAny <string>(), It.IsAny <APIMethods>(), It.IsAny <string>())).Returns(response);

            ResponseBase res = new ResponseBase();

            RESTAPIAuthCredentials req = new RESTAPIAuthCredentials()
            {
                Platform = "ios"
            };

            RESTAPILoginResponse expectedResponse = acontroler.Authenticate(req);

            Assert.IsTrue(expectedResponse.ErrorList.Count == 1);
            Assert.IsNotNull(expectedResponse.ErrorList.Where(x => x.ReturnCode == Faults.EmptyOrNullDevicetoken.ReturnCode));
        }
Пример #8
0
        private void btnVerify_Click(object sender, EventArgs e)
        {
            WordPressConnector.InitializeWordPress(txtUsername.Text, txtPassword.Text);

            lblStatus.Text = "Verifying...";
            SetLoginControlsEnabledState(false);

            GetProfileResponse user = WordPressConnector.GetUserProfile();

            if (user != null)
            {
                MessageBox.Show("Thanks " + user.FirstName + "!" + "\nYou're ready to upload.");
                btnUpload.Enabled = true;
            }
            else
            {
                MessageBox.Show("Connection failed",
                                "Can't connect to RW Wordpress!");
                SetLoginControlsEnabledState(true);
                lblStatus.Text = "Can't connect to RW WordPress, please try again.";
                return;
            }

            if (chkSaveCredentials.Checked)
            {
                // Save credentials
                Settings.Default.CredentialsSaved = true;
                Settings.Default.Username         = txtUsername.Text;
                Settings.Default.Password         = txtPassword.Text;
                Settings.Default.Save();
            }
        }
        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);
        }
        public void IsValidTest_ValidCallerIdCustomerIdSessionToken_ShouldValidateSuccessfully()
        {
            #region Arrange
            AccessCredentials credential = new AccessCredentials();
            credential.CallerId     = "TestCallerId";
            credential.UserID       = 100;
            credential.SessionToken = "TestSessionToken";
            credential.UseCaseGroup = "SANC";
            DateTime           loginDate = DateTime.UtcNow;
            GetProfileResponse response  = new GetProfileResponse();
            #endregion Arrange

            #region Act
            queryUtilsMock.Setup(x => x.GetHPPToken(It.IsAny <IIdeaDatabaseDataContext>(),
                                                    It.IsAny <int>(), It.IsAny <string>(), It.IsAny <string>()))
            .Returns(new UserAuthentication()
            {
                Token = "ReturnedToken", CreatedDate = loginDate
            });

            bool result = credential.IsValid(response);
            #endregion Act

            #region Assert
            Assert.IsTrue(result, "The validation should not have failed as the values provided were valid");
            Assert.IsTrue(response.ErrorList.Count == 0);
            #endregion Assert
        }
Пример #11
0
        public async Task GetProfileResponse()
        {
            GetProfileResponse GetProfileResponse =
                await GetJsonAsync <GetProfileResponse>(GetProfileRequest.GetRoute());

            ValidateGetProfileResponse(GetProfileResponse);
        }
Пример #12
0
        public async Task <ActionResult <GetProfileResponse> > GetUserProfile(string meUserId)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(new GetProfileResponse()));
            }

            try
            {
                var user = await _userRetrievalByIdService.Handle(new UserRetrievalByIdQuery(meUserId));

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

                var gur = new GetProfileResponse();
                Mapper.Map(user, gur);

                return(Ok(gur));
            }
            catch (ArgumentException)
            {
                return(NotFound(new GetProfileResponse()));
            }
            catch (DocumentClientException)
            {
                return(NotFound(new GetProfileResponse()));
            }
        }
Пример #13
0
        /// <summary>
        /// プロフィール情報取得
        /// </summary>
        /// <param name="channelAccessToken">チャンネルアクセストークン</param>
        /// <param name="userId">ユーザID</param>
        /// <returns>プロフィール情報</returns>
        public static async Task <GetProfileResponse> GetProfile(string channelAccessToken, string userId)
        {
            Trace.TraceInformation("Start");

            // 引数のnullチェック
            if (channelAccessToken == null)
            {
                Trace.TraceWarning("Channel Access Token is Null");
                return(null);
            }
            if (userId == null)
            {
                Trace.TraceWarning("User Id is Null");
                return(null);
            }

            string requestUrl =
                ConfigurationManager.AppSettings["BaseUrl"] +
                ConfigurationManager.AppSettings["ProfileUrl"] +
                userId;

            GetProfileResponse response = await MessagingApiSender.SendMessagingApi <string, GetProfileResponse>(
                channelAccessToken,
                requestUrl
                ).ConfigureAwait(false);

            Trace.TraceInformation("End");

            return(response);
        }
Пример #14
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);
        }
Пример #15
0
        public async Task <GetProfileResponse> GetProfileAsync() =>
        await Task.Run(async() => {
            if (!CrossConnectivity.Current.IsConnected)
            {
                throw new InvalidOperationException(AppConsts.ERROR_INTERNET_CONNECTION);
            }

            GetProfileRequest getProfileRequest = new GetProfileRequest {
                Url         = GlobalSettings.Instance.Endpoints.ProfileEndpoints.GetProfileEndPoints,
                AccessToken = GlobalSettings.Instance.UserProfile.AccesToken
            };

            GetProfileResponse getProfileResponse = null;

            try {
                getProfileResponse =
                    await _requestProvider.GetAsync <GetProfileRequest, GetProfileResponse>(getProfileRequest);
            }
            catch (ServiceAuthenticationException exc) {
                _identityUtilService.RefreshToken();

                throw exc;
            }
            catch (Exception ex) {
                Crashes.TrackError(ex);

                Debug.WriteLine($"ERROR:{ex.Message}");
                Debugger.Break();
                throw new Exception(ex.Message);
            }

            return(getProfileResponse);
        });
Пример #16
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));
        }
Пример #17
0
        public void IsValidTest_BlankCalledId_ShouldReturnFaultWithSpecificErrorDetails()
        {
            #region Arrange
            LoginCredentials credential = new LoginCredentials();
            credential.UserName = "******";
            credential.Password = "******";
            credential.CallerId = string.Empty;
            GetProfileResponse response = new GetProfileResponse();
            #endregion Arrange

            #region Act
            bool result = credential.IsValid(response);
            #endregion Act

            #region Assert
            Assert.IsTrue(response.ErrorList.Count == 1);
            Assert.IsTrue(!result, "The validation should have failed due to invalid CallerId");

            // Fault object type check
            Fault fault = response.ErrorList.First();
            Assert.IsInstanceOfType(fault, typeof(ValidationFault), "Wrong fault object type returned");

            // Fault properties check
            Assert.IsTrue(string.Equals(fault.Origin, "InnovationPortal"), "Wrong fault origin returned");
            Assert.IsTrue(string.Equals(fault.ReturnCode, "FieldValidationError"), "Wrong fault return code returned");
            Assert.IsTrue(string.Equals(fault.DebugStatusText, "Field has wrong length"), "Wrong fault status text returned");

            // ValidationFault properties check
            Assert.IsTrue(string.Equals((fault as ValidationFault).ErrorType, "Length"), "Wrong validation error type returned");
            Assert.IsTrue(string.Equals((fault as ValidationFault).FieldName, "CallerId"), "Wrong validation field name returned");
            #endregion Assert
        }
Пример #18
0
        public async Task <ActionResult <MainResponse> > GetProfileData(GetProfileDataRequest request)
        {
            User user = await _context.Users.FirstOrDefaultAsync(p => p.Alias == request.UserAlias || p.Login == request.UserAlias);

            if (user == null)
            {
                return(MainResponse.GetError(Enums.RequestError.UserNotFound));
            }

            GetProfileResponse response = new GetProfileResponse()
            {
                UserData    = (ExtUser)user,
                UserProfile = user.UserProfile,
                Images      = new List <ExtFileData>()
            };

            response.UserData.Img?.SetPath(_serverConfig.General.ServerPath + _serverConfig.FileRoutes.UserImages.Route);

            FileData[] files = user.Files.Where(p => p.Type == Enums.FileType.Image).OrderByDescending(p => p.UploadDate).Take(_serverConfig.Users.PartsSize.PreviewImagesPartSize).ToArray();

            for (int i = 0; i < files.Length; i++)
            {
                response.Images.Add((ExtFileData)files[i]);
                response.Images[i].SetPath(_serverConfig.General.ServerPath + _serverConfig.FileRoutes.UserImages.Route);
            }
            return(MainResponse.GetSuccess(response));
        }
        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));
        }
Пример #20
0
        public void IsValidTest_NullUserName_ShouldReturnFaultWithSpecificErrorDetails()
        {
            #region Arrange
            LoginCredentials credential = new LoginCredentials();
            credential.UserName = null;
            credential.Password = "******";
            credential.CallerId = "TestCallerId";
            GetProfileResponse response = new GetProfileResponse();
            #endregion Arrange

            #region Act
            bool result = credential.IsValid(response);
            #endregion Act

            #region Assert
            Assert.IsTrue(response.ErrorList.Count == 1);
            Fault fault = response.ErrorList.First();

            // Fault object type check
            Assert.IsInstanceOfType(fault, typeof(ValidationFault), "Wrong fault object type returned");

            // Fault properties check
            Assert.IsTrue(string.Equals(fault.Origin, "InnovationPortal"), "Wrong fault origin returned");
            Assert.IsTrue(string.Equals(fault.ReturnCode, "FieldValidationError"), "Wrong fault return code returned");
            Assert.IsTrue(string.Equals(fault.DebugStatusText, "Required field is missing"), "Wrong fault status text returned");

            // ValidationFault properties check
            Assert.IsTrue(string.Equals((fault as ValidationFault).ErrorType, "Required"), "Wrong validation error type returned");
            Assert.IsTrue(string.Equals((fault as ValidationFault).FieldName, "UserName"), "Wrong validation field name returned");
            #endregion Assert
        }
        public void AuthenticateTest()
        {
            GetProfileResponse response = new GetProfileResponse()
            {
                Credentials           = new Credentials.AccessCredentials(),
                CustomerProfileObject = new CustomerProfile()
                {
                    ActiveHealth = true
                }
            };

            authMock.Setup(x => x.GetCustomerProfileByAuthentication(It.IsAny <UserAuthenticationInterchange>(), It.IsAny <bool>(), It.IsAny <string>(), It.IsAny <string>(), It.IsAny <APIMethods>(), It.IsAny <string>())).Returns(response);

            ResponseBase res = new ResponseBase();

            RESTAPIAuthCredentials req = new RESTAPIAuthCredentials()
            {
                DeviceToken = "SDILASNP",
                Platform    = "platform"
            };

            Assert.IsNotNull(acontroler.Authenticate(req));

            authMock.Verify(x => x.GetCustomerProfileByAuthentication(It.IsAny <UserAuthenticationInterchange>(), It.IsAny <bool>(), It.IsAny <string>(), It.IsAny <string>(), It.IsAny <APIMethods>(), It.IsAny <string>()), Times.Once);
        }
Пример #22
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);
        }
Пример #23
0
        public ProfileDTO BuildProfileDTO(GetProfileResponse data)
        {
            ProfileDTO result = new ProfileDTO()
            {
                About            = data.About,
                MySports         = data.MySports,
                Children         = data.Children,
                Id               = data.Id,
                Type             = data.Type,
                FirstName        = data.FirstName,
                LastName         = data.LastName,
                DisplayName      = data.DisplayName,
                ShortId          = data.ShortId,
                DateOfBirth      = data.DateOfBirth,
                Availability     = data.Availability,
                LastSeen         = data.LastSeen,
                ParentId         = data.ParentId,
                ChildUserName    = data.ChildUserName,
                ChildPassword    = data.ChildPassword,
                Contact          = data.Contact,
                Address          = data.Address,
                BackgroundImage  = data.BackgroundImage,
                Avatar           = data.Avatar,
                BrandImage       = data.BrandImage,
                Media            = data.Media,
                IsEmailConfirmed = data.IsEmailConfirmed
            };

            return(result);
        }
        public RESTAPILoginResponse Login(RESTAPILoginCredentials req)
        {
            GetProfileResponse            response           = new GetProfileResponse();
            UserAuthenticationInterchange hppAuthInterchange = new UserAuthenticationInterchange()
            {
                UserName          = req.UserName,
                Password          = req.Password,
                CallerId          = req.CallerId,
                Token             = null,
                LanguageCode      = req.LanguageCode,
                CountryCode       = req.CountryCode,
                UseCaseGroup      = req.ClientViewer,
                Platform          = req.Platform,
                ClientApplication = UserAuthenticationInterchange.MapPlatformToClientApplication(req.Platform)
            };

            if (SettingRepository.Get <bool>("TESTLoginEnabled", true))
            {
                response = HPIDUtils.GetCustomerProfileByTestLogin(hppAuthInterchange, false, APIMethods.None);
            }
            else
            {
                if (SettingRepository.Get <bool>("HPIDEnabled", true))
                {
                    response = HPIDUtils.GetCustomerProfileByLogin(hppAuthInterchange, false, APIMethods.None);
                }
                //else
                //{
                //    response = customerUtils.GetCustomerProfile(hppAuthInterchange, false);
                //}
            }

            RESTAPILoginResponse loginResponse = new RESTAPILoginResponse();

            if (response.ErrorList.Count == 0)
            {
                loginResponse.UserID       = response.Credentials.UserID;
                loginResponse.SessionToken = response.Credentials.SessionToken;
                loginResponse.CallerId     = response.Credentials.CallerId;

                loginResponse.Roles        = response.Credentials.Roles;
                loginResponse.Locale       = response.CustomerProfileObject.Locale;
                loginResponse.FirstName    = response.CustomerProfileObject.FirstName;
                loginResponse.LastName     = response.CustomerProfileObject.LastName;
                loginResponse.Emailaddress = response.CustomerProfileObject.EmailAddress;

                if (response.LoginDate.HasValue)
                {
                    //loginResponse.TimeOut = DateTimeFormatUtils.GetIso8601String(response.LoginDate.Value.AddMinutes(SettingRepository.Get<int>("MaxSessionTimeMinutes", 2)));
                }
                loginResponse.Status = Enum.GetName(typeof(ResponseStatusType), ResponseStatusType.Success);
            }
            else
            {
                loginResponse.ErrorList = response.ErrorList;
                loginResponse.Status    = Enum.GetName(typeof(ResponseStatusType), ResponseStatusType.Failure);
            }
            return(loginResponse);
        }
Пример #25
0
        public Task ImpersonateLoginAsync(long targetId, CancellationTokenSource cancellationTokenSource) =>
        Task.Run(async() => {
            if (!CrossConnectivity.Current.IsConnected)
            {
                throw new InvalidOperationException(AppConsts.ERROR_INTERNET_CONNECTION);
            }

            ImpersonateLogInRequest impersonateLogInRequest = new ImpersonateLogInRequest()
            {
                AccessToken = GlobalSettings.Instance.UserProfile.AccesToken,
                Url         = GlobalSettings.Instance.Endpoints.AuthenticationEndpoints.ImpersonateLogIn,
                Data        = new ImpersonateLogInDataModel()
                {
                    ChildProfileId = targetId
                }
            };

            try {
                ImpersonateLogInResponse impersonateLogInResponse = await _requestProvider.PostAsync <ImpersonateLogInRequest, ImpersonateLogInResponse>(impersonateLogInRequest);

                if (impersonateLogInResponse == null)
                {
                    throw new InvalidOperationException(_IMPERSONATE_LOGIN_COMMON_ERROR_MESSAGE);
                }
                else
                {
                    GetProfileResponse getProfileResponse = await GetProfileAsync(impersonateLogInResponse.AccessToken, cancellationTokenSource);

                    if (getProfileResponse == null)
                    {
                        throw new InvalidOperationException(_IMPERSONATE_LOGIN_COMMON_ERROR_MESSAGE);
                    }
                    else
                    {
                        _navigationService.DisposeStack();

                        await _identityUtilService.ChargeImpersonateUserProfileAsync(impersonateLogInResponse.AccessToken, getProfileResponse);

                        Device.BeginInvokeOnMainThread(() => {
                            _navigationService.Initialize(true);
                        });
                    }
                }
            }
            catch (ServiceAuthenticationException exc) {
                _identityUtilService.RefreshToken();

                throw exc;
            }
            catch (HttpRequestExceptionEx exc) {
                throw exc;
            }
            catch (Exception exc) {
                Crashes.TrackError(exc);

                throw exc;
            }
        }, cancellationTokenSource.Token);
        public void GetCustomerProfileByAuthenticationTest_InvalidCredentials()
        {
            CustomerHPIDUtils custUtils = new CustomerHPIDUtils();

            GetProfileResponse response = custUtils.GetCustomerProfileByAuthentication(null, It.IsAny <bool>(), null, null, It.IsAny <APIMethods>());

            Assert.IsTrue(response.ErrorList.Count == 1);
            Assert.IsTrue(response.ErrorList.Contains(Faults.InvalidCredentials));
        }
        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));
        }
Пример #28
0
        public RESTAPILoginResponse Authenticate(RESTAPIAuthCredentials req)
        {
            UserAuthenticationInterchange hppAuthInterchange = new UserAuthenticationInterchange()
            {
                CallerId     = req.CallerId,
                LanguageCode = req.LanguageCode,
                CountryCode  = req.CountryCode,
                Platform     = req.Platform,
                ClientId     = req.ClientId,
                UserId       = req.UserId
            };

            SetClientAppInfo(req.Platform, hppAuthInterchange);

            GetProfileResponse response = new GetProfileResponse();

            if (SettingRepository.Get <bool>("TESTLoginEnabled", true))
            {
                //response = HPIDUtils.GetCustomerProfileByTestLogin(hppAuthInterchange, false, APIMethods.None);
                response = HPIDUtils.GetCustomerProfileByDefaultUserLogin(response, hppAuthInterchange, false, APIMethods.None);
            }
            else
            {
                response = AuthUtils.GetCustomerProfileByAuthentication(hppAuthInterchange, false, req.AccessCode, req.RedirectUrl, APIMethods.POSTAuthenticate, req.ClientId);
            }

            RESTAPILoginResponse loginResponse = new RESTAPILoginResponse();

            if (response.ErrorList.Count == 0)
            {
                loginResponse.UserID       = response.Credentials.UserID;
                loginResponse.SessionToken = response.Credentials.SessionToken;
                loginResponse.CallerId     = response.Credentials.CallerId;
                loginResponse.Roles        = response.Credentials.Roles;
                loginResponse.Locale       = response.CustomerProfileObject.Locale;
                loginResponse.FirstName    = response.CustomerProfileObject.FirstName;
                loginResponse.LastName     = response.CustomerProfileObject.LastName;
                loginResponse.Emailaddress = response.CustomerProfileObject.EmailAddress;
                loginResponse.Status       = Enum.GetName(typeof(ResponseStatusType), ResponseStatusType.Success);

                //if (string.IsNullOrEmpty(req.DeviceToken))
                //{
                //    loginResponse.ErrorList.Add(Faults.EmptyOrNullDevicetoken);
                //}
                if (response.LoginDate.HasValue)
                {
                    //loginResponse.TimeOut = DateTimeFormatUtils.GetIso8601String(response.LoginDate.Value.AddMinutes(SettingRepository.Get<int>("MaxSessionTimeMinutes", 60)));
                }
            }
            else
            {
                loginResponse.Status    = Enum.GetName(typeof(ResponseStatusType), ResponseStatusType.Failure);
                loginResponse.ErrorList = response.ErrorList;
            }

            return(loginResponse);
        }
Пример #29
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());
        }