private void SetupTest(ContactModel contactModelToDo, CultureInfo culture, string actionStr)
        {
            LanguageEnum languageEnum = (culture.TwoLetterISOLanguageName == "fr" ? LanguageEnum.fr : LanguageEnum.en);

            if (contactModelToDo == null)
            {
                user = null;
            }
            else
            {
                user = new GenericPrincipal(new GenericIdentity(contactModelToDo.LoginEmail, "Forms"), null);
            }
            routeData = new RouteData();
            routeData.Values.Add("culture", culture);
            routeData.Values.Add("controller", "MikeScenario");
            routeData.Values.Add("action", actionStr);

            stubHttpContext            = new StubHttpContextBase();
            stubHttpRequestBase        = new StubHttpRequestBase();
            stubHttpContext.RequestGet = () => stubHttpRequestBase;
            requestContext             = new RequestContext(stubHttpContext, routeData);
            controller     = new MikeScenarioController();
            controller.Url = new UrlHelper(requestContext);
            controller.ControllerContext = new ControllerContext(stubHttpContext, routeData, controller);
            stubHttpContext.UserGet      = () => user;
            randomService  = new RandomService(languageEnum, user);
            mapInfoService = new MapInfoService(languageEnum, user);
            tvItemService  = new TVItemService(languageEnum, user);
            mikeBoundaryConditionService = new MikeBoundaryConditionService(languageEnum, user);
            appTaskService            = new AppTaskService(languageEnum, user);
            mikeScenarioService       = new MikeScenarioService(languageEnum, user);
            tvFileService             = new TVFileService(languageEnum, user);
            mikeSourceService         = new MikeSourceService(languageEnum, user);
            mikeSourceStartEndService = new MikeSourceStartEndService(languageEnum, user);

            controller.SetRequestContext(requestContext);

            // Assert
            Assert.IsNotNull(controller);
            Assert.AreEqual(2, controller.CultureListAllowable.Count);
            Assert.AreEqual("en-CA", controller.CultureListAllowable[0]);
            Assert.AreEqual("fr-CA", controller.CultureListAllowable[1]);
            Assert.IsNotNull(controller._ContactService);
            Assert.IsNotNull(controller._RequestContext);
            Assert.IsNotNull(controller._MikeScenarioService);
            Assert.IsNotNull(culture.Name, controller._RequestContext.RouteData.Values["culture"].ToString());
            Assert.IsNotNull("MikeScenario", controller._RequestContext.RouteData.Values["controller"].ToString());
            Assert.IsNotNull(actionStr, controller._RequestContext.RouteData.Values["action"].ToString());
            Assert.AreEqual((culture.TwoLetterISOLanguageName == "fr" ? LanguageEnum.fr : LanguageEnum.en), controller.LanguageRequest);
            Assert.AreEqual((culture.TwoLetterISOLanguageName == "fr" ? LanguageEnum.fr : LanguageEnum.en), controller.ViewBag.Language);
            Assert.AreEqual(culture.Name, controller.CultureRequest);
            Assert.AreEqual(culture.Name, controller.ViewBag.Culture);
            if (contactModelToDo != null)
            {
                Assert.AreEqual(contactModelToDo.IsAdmin, controller.IsAdmin);
                Assert.AreEqual(contactModelToDo.IsAdmin, controller.ViewBag.IsAdmin);
            }
            Assert.AreEqual(true, controller.Debug);
            Assert.AreEqual(true, controller.ViewBag.Debug);
        }
        public void TestChangePassword()
        {
            string testUserName = "******";
            string testOldPassword = "******";
            string testNewPassword = "******";

            var changePasswordModel = new ChangePasswordModel
            {
                OldPassword = testOldPassword,
                NewPassword = testNewPassword
            };

            var accountController = new AccountController();

            //Stub HttpContext
            var stubHttpContext = new StubHttpContextBase();
            //Setup ControllerContext so AccountController will use our stubHttpContext
            accountController.ControllerContext = new ControllerContext(stubHttpContext,
                new RouteData(), accountController);

            //Stub IPrincipal
            var principal = new StubIPrincipal();
            principal.IdentityGet = () =>
            {
                var identity = new StubIIdentity { NameGet = () => testUserName };
                return identity;
            };
            stubHttpContext.UserGet = () => principal;

            RedirectToRouteResult redirectToRouteResult;
            //Scope the detours we're creating
            using (ShimsContext.Create())
            {
                ShimMembership.GetUserStringBoolean = (identityName, userIsOnline) =>
                {
                    Assert.AreEqual(testUserName, identityName);
                    Assert.AreEqual(true, userIsOnline);

                    var memberShipUser = new ShimMembershipUser();
                    //Sets up a detour for MemberShipUser.ChangePassword to our mocked implementation
                    memberShipUser.ChangePasswordStringString = (oldPassword, newPassword) =>
                    {
                        Assert.AreEqual(testOldPassword, oldPassword);
                        Assert.AreEqual(testNewPassword, newPassword);
                        return true;
                    };
                    return memberShipUser;
                };

                var actionResult = accountController.ChangePassword(changePasswordModel);
                Assert.IsInstanceOf(typeof(RedirectToRouteResult), actionResult);
                redirectToRouteResult = actionResult as RedirectToRouteResult;
            }
            Assert.NotNull(redirectToRouteResult);
            Assert.AreEqual("ChangePasswordSuccess", redirectToRouteResult.RouteValues["Action"]);
        }
Ejemplo n.º 3
0
        public void Index_Not_Authenticated()
        {
            // Arrange:
            using (ShimsContext.Create())
            {
                using (HomeController controller = new HomeController())
                {
                    StubHttpContextBase stubHttpContext = new StubHttpContextBase();

                    controller.ControllerContext = new ControllerContext(stubHttpContext, new RouteData(), controller);

                    // Shim the HttpContext.Current
                    var httpRequest      = new HttpRequest("", "http://localhost", "");
                    var httpContext      = new HttpContext(httpRequest, new HttpResponse(new StringWriter()));
                    var applicationState = httpContext.Application;
                    ShimHttpContext.CurrentGet = () => httpContext;

                    // Stub the Current.User
                    StubIPrincipal principal = new StubIPrincipal();
                    principal.IdentityGet = () =>
                    {
                        return(new StubIIdentity
                        {
                            NameGet = () => "antonio",
                            IsAuthenticatedGet = () => false
                        });
                    };
                    stubHttpContext.UserGet = () => principal;

                    // Act:
                    ActionResult result = controller.Index();

                    // Assert:
                    Assert.IsNotNull(result);
                }
            }
        }
Ejemplo n.º 4
0
        public void An_error_is_received_if_a_user_tries_to_associate_his_corp_id_with_an_unknown_SIMPL_username()
        {
            using (ShimsContext.Create())
            {
                //Setup
                var calledSetCurrentUser = false;
                ShimCurrentUser.SetInstanceString = delegate { calledSetCurrentUser = true; };

                var calledSetAuthCookie = false;
                ShimFormsAuthentication.SetAuthCookieStringBooleanString = delegate { calledSetAuthCookie = true; };
                ShimErrorLoggingService.AllInstances.LogErrorException = (method, myException) =>
                {
                    // Not returning anything, just redirecting the call
                };
                // Given a user
                const string corpUserName = "******";
                const string corpPassword = "******";
                const string simplUserName = "******";
                const string simplPassword = "******";
                var requestStub = new StubHttpRequestBase();
                var contextStub = new StubHttpContextBase {RequestGet = () => requestStub};
                var userAssociationModel = new AssociationViewModel();

                // And has known corp credentials
                userAssociationModel.UserName = corpUserName;
                userAssociationModel.Password = corpPassword;

                // And has unknown SIMPL credentials
                userAssociationModel.SIMPLUserName = simplUserName;
                userAssociationModel.SIMPLPassword = simplPassword;

                var wasAttemptToLogUserInCalledForCorp = false;
                var wasAttemptToLogUserInCalledForSIMPL = false;
                ShimLoginModel.AllInstances.AttemptToLogUserInStringString = (loginModel, userName, password) =>
                {
                    if (userName == corpUserName && password == corpPassword)
                    {
                        wasAttemptToLogUserInCalledForCorp = true;
                        return new LoginModel()
                        {
                            Message = SIMPL.Models.Code.Constants.Areas.Common.LoginModel.AuthenticationResultMessages.NoUserRoles
                        };
                    }
                    if (userName == simplUserName && password == simplPassword)
                    {
                        wasAttemptToLogUserInCalledForSIMPL = true;
                        return new LoginModel()
                        {
                            Errors = true,
                            Message = SIMPL.Models.Code.Constants.Areas.Common.LoginModel.AuthenticationResultMessages.BadOrIncorrectUsernameOrPassword
                        };
                    }
                    return new LoginModel()
                    {
                        Errors = true,
                        Message = SIMPL.Models.Code.Constants.Areas.Common.LoginModel.AuthenticationResultMessages.UnknownResult
                    };
                };

                // And corp username doesn’t match SIMPL username
                // When submitting association form
                LoginControllerForTests.ControllerContext = new ControllerContext {HttpContext = contextStub};
                var userAssociationResult = LoginControllerForTests.UserNameAssociation(userAssociationModel);

                // Then association fails
                Assert.IsNotNull(userAssociationResult);
                #pragma warning disable 183
                // ReSharper generates a warning on the next line, but having this check will guarantee that the return type is checked before the other asserts
                Assert.IsTrue(userAssociationResult is ActionResult,
                    "The return from the UserLogin action method was not a ActionResult");
                #pragma warning restore 183
                Assert.IsTrue(userAssociationResult is ViewResult,
                    "The return from the UserLogin action method was not a ViewResult");

                // And user is not logged in
                Assert.IsFalse(calledSetCurrentUser, "The set CurrentUser was called");
                Assert.IsFalse(calledSetAuthCookie, "The set Authorization cookie was called");

                //And a message is displayed stating “Username association failed, please check your SIMPL credentials and try again”
                Assert.IsTrue(wasAttemptToLogUserInCalledForCorp, "Corp credentials were not Authorized");
                Assert.IsTrue(wasAttemptToLogUserInCalledForSIMPL, "SIMPL credentials were not Authorized");

                var result = userAssociationResult as ViewResult;
                var resultModel = result.Model as AssociationViewModel;
                Assert.IsNotNull(resultModel, "The model was null");
                Assert.IsNotNull(resultModel.Message, "The error message was missing.");
                const string expectedMessage =
                    "SIMPL login credentials are incorrect, please check your credentials and try again.";
                Assert.AreEqual(expectedMessage, resultModel.Message,
                    string.Format("The error message was {0}, it should have been {1}", resultModel.Message,
                        expectedMessage));
            }
        }
Ejemplo n.º 5
0
        public void A_user_logs_in_when_Single_Concurrent_Login_Feature_is_enabled_but_error_occurs_when_saving_the_username_and_session_data()
        {
            using (ShimsContext.Create())
            {
                // Given a known user that is not logged in yet
                const string userName = "******";
                const string password = "******";
                const string returnUrl = "doesNotMatter";

                var requestStub = new StubHttpRequestBase();
                var contextStub = new StubHttpContextBase { RequestGet = () => requestStub };

                LoginControllerForTests.ControllerContext = new ControllerContext()
                {
                    HttpContext = contextStub
                };

                #endregion LoginModel class, AttemptToLogUserIn method

                // And the Single Concurrent Login Feature is enabled

                // As there are unit tests for IsCheckEnabledActor, I am mocking the reference to IsCheckEnabled
                var wasIsCheckEnabledCalled = false;
                ShimSingleConcurrentLoginRules.AllInstances.IsCheckEnabled = (resultValue) =>
                {
                    wasIsCheckEnabledCalled = true;
                    return true;
                };

                // When that user is trying to log in

                #region LoginModel class, AttemptToLogUserIn method

                var wasASPPAuthenticateCalled = false;
                ShimUserManagement.AllInstances.AuthenticateStringString = (userNameValue, passwordValue, results) =>
                {
                    wasASPPAuthenticateCalled = true;
                    return UserManagement.AuthenticationResults.Success;
                };

                var wasASPPGetUserDetailsCalled = false;
                ShimUserManagement.AllInstances.GetUserDetailsString = (userNameValue, results) =>
                {
                    wasASPPGetUserDetailsCalled = true;
                    return new ASPP_Users();
                };

                var wasASPPGetUserGroupsCalled = false;
                ShimUserManagement.AllInstances.GetUserGroupsString = (userNameValue, results) =>
                {
                    wasASPPGetUserGroupsCalled = true;

                    // need to add at least one group - doing just enough to get beyond the guard in LoginModel.cs
                    var myASPP_Group = new ASPP_Groups
                    {
                        Group_ID = 1
                    };

                    return new List<ASPP_Groups>
                    {
                        myASPP_Group
                    };
                };

                // Then the data is not saved correctly

                // Note: the CreateSIMPLLoginTrackerRecord method should be called

                // When the CreateSIMPLLoginTrackerRecord method is called,
                // the SIMPLLoginTrackers.Add line will throw an exception because
                // it cannot find SIMPLEntities connection string in the config;
                // this is fine for our purposes as it throws as exception.

                // And the data is not added to the cache

                // Note: the AddSIMPLLoginTrackerRecordToCache method should not be called
                var wasAddSIMPLLoginTrackerRecordToCacheCalled = false;
                ShimSIMPLSessionEntitiesCache.AddSIMPLLoginTrackerRecordToCacheStringSIMPLLoginTracker = (userNameValue, myLoginTrackerValue) =>
                {
                    wasAddSIMPLLoginTrackerRecordToCacheCalled = true;
                    return true;
                };

                // And the user is not logged in

                #region back in the LoginViewModel class, AttemptToLogUserIn method

                var session = new ShimHttpSessionState { SessionIDGet = () => "doesNotMatter"};
                var context = new ShimHttpContext();
                var applicationShim = new ShimHttpApplicationState();
                context.ApplicationGet = () => applicationShim;
                ShimHttpContext.CurrentGet = () => context;
                ShimHttpContext.AllInstances.SessionGet = (o) => session;

                // Note: the CurrentUser.SetInstance method should not be called
                var wasCurrentUserSetInstanceStringCalled = false;
                var currentUserSetInstanceCount = 0;
                ShimCurrentUser.SetInstanceString = (uniqueId) =>
                {
                    wasCurrentUserSetInstanceStringCalled = true;
                    currentUserSetInstanceCount++;
                };

                // Note: the CurrentUser.SessionInstance method should not be called
                var wasCurrentUserSessionInstanceGetCalled = false;
                ShimCurrentUser.SessionInstanceGet = () =>
                {
                    wasCurrentUserSessionInstanceGetCalled = true;
                    return new ShimCurrentUser();
                };

                // Note: the SyncWithOrImportDataFromASPP method should not be called
                var wasLoginModelSyncWithOrImportDataFromASPPCalled = false;
                ShimLoginModel.AllInstances.SyncWithOrImportDataFromASPPIErrorLoggingServiceString = (loginModel, errorLoggingServiceValue, userNameSentToLoginModelValue) =>
                {
                    wasLoginModelSyncWithOrImportDataFromASPPCalled = true;
                };

                // Note: the CurrentUser.Clear method should not be called
                var wasCurrentUserClearCalled = false;
                ShimCurrentUser.Clear = () =>
                {
                    wasCurrentUserClearCalled = true;
                };

                // Note: the UserEvents.InitializeSession method should not be called
                var wasUserEventsInitializeSessionCalled = false;
                ShimUserEvents.AllInstances.InitializeSessionStringString = (userEvents, uniqueIdValue, userHostAddressValue) =>
                {
                    wasUserEventsInitializeSessionCalled = true;
                };

                // Note: the FormsAuthentication.SetAuthCookie method should not be called
                var wasFormsAuthenticationSetAuthCookieCalled = false;
                ShimFormsAuthentication.SetAuthCookieStringBoolean = (userNameValue, createPersistentCookieValue) =>
                {
                    wasFormsAuthenticationSetAuthCookieCalled = true;
                };

                ShimErrorLoggingService.AllInstances.LogErrorException = (method, myException) =>
                {
                    // Not returning anything, just redirecting the call
                };

                #endregion back in the LoginViewModel class, AttemptToLogUserIn method

                var result = LoginControllerForTests.UserLogin(userName, password, returnUrl);
                Assert.IsNotNull(result, "LoginController returned null");
                Assert.IsTrue(result is ViewResult, "LoginController didn't return a ViewResult");

                var resultViewResult = result as ViewResult;
                Assert.IsNotNull(resultViewResult.Model, "resultViewResult.Model is null");
                Assert.IsTrue(resultViewResult.Model is LoginViewModel, "resultViewResult.Model is not LoginViewModel");

                var resultLoginViewModel = resultViewResult.Model as LoginViewModel;
                Assert.AreEqual("Unable to save the Login Record, please contact support (Single Concurrent Login Enabled)", resultLoginViewModel.Message, "resultLoginViewModel.Message did not have the expected value");

                Assert.IsTrue(wasASPPAuthenticateCalled, "wasASPPAuthenticateCalled is false");
                Assert.IsTrue(wasASPPGetUserDetailsCalled, "wasASPPGetUserDetailsCalled is false");
                Assert.IsTrue(wasASPPGetUserGroupsCalled, "wasASPPGetUserDetailsCalled is false");
                Assert.IsTrue(wasIsCheckEnabledCalled, "wasIsCheckEnabledCalled is false");

                // Not able to check if the CreateSIMPLLoginTrackerRecord method was called because
                // we are not using a Shim for that (as we are calling the live method)

                // These are negative checks to make sure that the other code was not called
                Assert.IsFalse(wasAddSIMPLLoginTrackerRecordToCacheCalled, "wasAddSIMPLLoginTrackerRecordToCacheCalled is true");
                Assert.IsFalse(wasCurrentUserSetInstanceStringCalled, "wasCurrentUserSetInstanceStringCalled is true");
                Assert.AreEqual(0, currentUserSetInstanceCount, "currentUserSetInstanceCount did not match expected value");
                Assert.IsFalse(wasCurrentUserSessionInstanceGetCalled, "wasCurrentUserSessionInstanceGetCalled is true");
                Assert.IsFalse(wasCurrentUserClearCalled, "wasCurrentUserClearCalled is true");
                Assert.IsFalse(wasLoginModelSyncWithOrImportDataFromASPPCalled, "wasLoginModelSyncWithOrImportDataFromASPPCalled is true");
                Assert.IsFalse(wasUserEventsInitializeSessionCalled, "wasUserEventsInitializeSessionCalled is true");
                Assert.IsFalse(wasFormsAuthenticationSetAuthCookieCalled, "wasFormsAuthenticationSetAuthCookieCalled is true");
            }
        }
Ejemplo n.º 6
0
        public void A_user_logs_in_when_Single_Concurrent_Login_Feature_is_enabled_and_is_able_to_successfully_log_in()
        {
            using (ShimsContext.Create())
            {
                // Given a known user that is not logged in yet
                const string userName = "******";
                const string password = "******";
                const string returnUrl = "doesNotMatter";

                var requestStub = new StubHttpRequestBase();
                var contextStub = new StubHttpContextBase { RequestGet = () => requestStub };

                LoginControllerForTests.ControllerContext = new ControllerContext()
                {
                    HttpContext = contextStub
                };

                #endregion LoginModel class, AttemptToLogUserIn method

                // And the Single Concurrent Login Feature is enabled

                // As there are unit tests for IsCheckEnabledActor, I am mocking the reference to IsCheckEnabled
                var wasIsCheckEnabledCalled = false;
                ShimSingleConcurrentLoginRules.AllInstances.IsCheckEnabled = (resultValue) =>
                {
                    wasIsCheckEnabledCalled = true;
                    return true;
                };

                // When that user is trying to log in

                #region LoginModel class, AttemptToLogUserIn method

                var wasASPPAuthenticateCalled = false;
                ShimUserManagement.AllInstances.AuthenticateStringString = (userNameValue, passwordValue, results) =>
                {
                    wasASPPAuthenticateCalled = true;
                    return UserManagement.AuthenticationResults.Success;
                };

                var wasASPPGetUserDetailsCalled = false;
                ShimUserManagement.AllInstances.GetUserDetailsString = (userNameValue, results) =>
                {
                    wasASPPGetUserDetailsCalled = true;
                    return new ASPP_Users();
                };

                var wasASPPGetUserGroupsCalled = false;
                ShimUserManagement.AllInstances.GetUserGroupsString = (userNameValue, results) =>
                {
                    wasASPPGetUserGroupsCalled = true;

                    // need to add at least one group - doing just enough to get beyond the guard in LoginModel.cs
                    var myASPP_Group = new ASPP_Groups
                    {
                        Group_ID = 1
                    };

                    return new List<ASPP_Groups>
                    {
                        myASPP_Group
                    };
                };

                // Then the data is saved correctly

                var wasCreateSIMPLLoginTrackerRecordCalled = false;
                ShimSIMPLSessionEntitiesRepository.AllInstances.CreateSIMPLLoginTrackerRecordStringString = (method, userNameValue, aspNetSessionIdValue) =>
                {
                    wasCreateSIMPLLoginTrackerRecordCalled = true;
                    return new SIMPLLoginTracker { SIMPLUsername = "******", ASPNETSessionId = "doesNotMatter", SIMPLLoginTrackerId = 1, SIMPLLoginTimeUtc = DateTime.UtcNow };
                };

                // And the data is added to the cache correctly

                var wasAddSIMPLLoginTrackerRecordToCacheCalled = false;
                ShimSIMPLSessionEntitiesCache.AddSIMPLLoginTrackerRecordToCacheStringSIMPLLoginTracker = (userNameValue, myLoginTrackerValue) =>
                {
                    wasAddSIMPLLoginTrackerRecordToCacheCalled = true;
                    return true;
                };

                // And the user is logged in successfully

                #region back in the LoginViewModel class, AttemptToLogUserIn method

                var session = new ShimHttpSessionState { SessionIDGet = () => "doesNotMatter"};
                var context = new ShimHttpContext();
                var applicationShim = new ShimHttpApplicationState();
                context.ApplicationGet = () => applicationShim;
                ShimHttpContext.CurrentGet = () => context;
                ShimHttpContext.AllInstances.SessionGet = (o) => session;

                var wasCurrentUserSetInstanceStringCalled = false;
                var currentUserSetInstanceCount = 0;
                ShimCurrentUser.SetInstanceString = (uniqueId) =>
                {
                    wasCurrentUserSetInstanceStringCalled = true;
                    currentUserSetInstanceCount++;
                };

                var wasCurrentUserSessionInstanceGetCalled = false;
                ShimCurrentUser.SessionInstanceGet = () =>
                {
                    wasCurrentUserSessionInstanceGetCalled = true;
                    return new ShimCurrentUser();
                };

                var wasLoginModelSyncWithOrImportDataFromASPPCalled = false;
                ShimLoginModel.AllInstances.SyncWithOrImportDataFromASPPIErrorLoggingServiceString = (loginModel, errorLoggingServiceValue, userNameSentToLoginModelValue) =>
                {
                    wasLoginModelSyncWithOrImportDataFromASPPCalled = true;
                };

                var wasCurrentUserClearCalled = false;
                ShimCurrentUser.Clear = () =>
                {
                    wasCurrentUserClearCalled = true;
                };

                var wasUserEventsInitializeSessionCalled = false;
                ShimUserEvents.AllInstances.InitializeSessionStringString = (userEvents, uniqueIdValue, userHostAddressValue) =>
                {
                    wasUserEventsInitializeSessionCalled = true;
                };

                var wasFormsAuthenticationSetAuthCookieCalled = false;
                ShimFormsAuthentication.SetAuthCookieStringBoolean = (userNameValue, createPersistentCookieValue) =>
                {
                    wasFormsAuthenticationSetAuthCookieCalled = true;
                };

                #endregion back in the LoginViewModel class, AttemptToLogUserIn method

                var result = LoginControllerForTests.UserLogin(userName, password, returnUrl);
                Assert.IsNotNull(result, "LoginController returned null");
                Assert.IsTrue(result is RedirectResult, "LoginController didn't return a RedirectResult");

                var resultRedirectResult = result as RedirectResult;
                Assert.AreEqual(returnUrl, resultRedirectResult.Url, "URL did not match expected value");

                Assert.IsTrue(wasIsCheckEnabledCalled, "wasIsCheckEnabledCalled is false");
                Assert.IsTrue(wasCreateSIMPLLoginTrackerRecordCalled, "wasCreateSIMPLLoginTrackerRecordCalled is false");
                Assert.IsTrue(wasAddSIMPLLoginTrackerRecordToCacheCalled, "wasAddSIMPLLoginTrackerRecordToCacheCalled is false");

                Assert.IsTrue(wasASPPAuthenticateCalled, "wasASPPAuthenticateCalled is false");
                Assert.IsTrue(wasASPPGetUserDetailsCalled, "wasASPPGetUserDetailsCalled is false");
                Assert.IsTrue(wasASPPGetUserGroupsCalled, "wasASPPGetUserDetailsCalled is false");
                Assert.IsTrue(wasCurrentUserSetInstanceStringCalled, "wasCurrentUserSetInstanceStringCalled is false");
                Assert.AreEqual(2, currentUserSetInstanceCount, "currentUserSetInstanceCount did not match expected value");
                Assert.IsTrue(wasCurrentUserSessionInstanceGetCalled, "wasCurrentUserSessionInstanceGetCalled is false");
                Assert.IsTrue(wasCurrentUserClearCalled, "wasCurrentUserClearCalled is false");
                Assert.IsTrue(wasLoginModelSyncWithOrImportDataFromASPPCalled, "wasLoginModelSyncWithOrImportDataFromASPPCalled is false");
                Assert.IsTrue(wasUserEventsInitializeSessionCalled, "wasUserEventsInitializeSessionCalled is false");
                Assert.IsTrue(wasFormsAuthenticationSetAuthCookieCalled, "wasFormsAuthenticationSetAuthCookieCalled is false");
            }
        }
Ejemplo n.º 7
0
        public void A_user_can_associate_SIMPL_username_to_their_corp_username()
        {
            using (ShimsContext.Create())
            {
                //Setup

                var session = new System.Web.SessionState.Fakes.ShimHttpSessionState()
                {
                    ItemGetString = (key) =>
                    {
                        return key == "CurrentUser" ? new ShimCurrentUser() : null;
                    }
                };
                var context = new System.Web.Fakes.ShimHttpContext();
                var applicationShim = new System.Web.Fakes.ShimHttpApplicationState();
                context.ApplicationGet = delegate { return applicationShim; };

                System.Web.Fakes.ShimHttpContext.CurrentGet = delegate { return context; };
                System.Web.Fakes.ShimHttpContext.AllInstances.SessionGet = delegate { return session; };

                ShimUserEvents.AllInstances.InitializeSessionStringString = delegate { };
                ShimSingleConcurrentLoginManager.AllInstances.CreateLoginRecordStringString = delegate { return true; };
                var calledSetCurrentUser = false;
                ShimCurrentUser.SetInstanceString = delegate { calledSetCurrentUser = true; };
                ShimCurrentUser.Clear = delegate { };
                ShimCurrentUser.SessionInstanceGet = delegate { return new ShimCurrentUser(); };
                ShimLoginModel.AllInstances.SyncWithOrImportDataFromASPPIErrorLoggingServiceString = (loginModel, errorLoggingService, userNameSentToLoginModel) =>
                {
                };
                var calledSetAuthCookie = false;
                ShimFormsAuthentication.SetAuthCookieStringBooleanString = delegate { calledSetAuthCookie = true; };

                // Given a user
                const string corpUserName = "******";
                const string corpPassword = "******";
                const string simplUserName = "******";
                const string simplPassword = "******";
                var requestStub = new StubHttpRequestBase();
                var contextStub = new StubHttpContextBase {RequestGet = () => requestStub};

                var calledUpdateHistoricalRecored = false;
                ShimUserRepository.AllInstances.UpdateHistoricalRecordStringString = delegate
                {
                    calledUpdateHistoricalRecored = true;
                    return true;
                };

                var userAssociationModel = new AssociationViewModel();

                // And has known corp credentials
                userAssociationModel.UserName = corpUserName;
                userAssociationModel.Password = corpPassword;

                // And has known SIMPL credentials
                userAssociationModel.SIMPLUserName = simplUserName;
                userAssociationModel.SIMPLPassword = simplPassword;

                var wasAttemptToLogUserInCalledForCorp = false;
                var wasAttemptToLogUserInCalledForSIMPL = false;
                ShimLoginModel.AllInstances.AttemptToLogUserInStringString = (loginModel, userName, password) =>
                {
                    if (wasAttemptToLogUserInCalledForCorp && wasAttemptToLogUserInCalledForSIMPL)
                    {
                        return new LoginModel();
                    }
                    if (userName == corpUserName && password == corpPassword)
                    {
                        wasAttemptToLogUserInCalledForCorp = true;
                        return new LoginModel()
                        {
                            Message = SIMPL.Models.Code.Constants.Areas.Common.LoginModel.AuthenticationResultMessages.NoUserRoles
                        };
                    }
                    if (userName == simplUserName && password == simplPassword)
                    {
                        wasAttemptToLogUserInCalledForSIMPL = true;
                        return new LoginModel();
                    }
                    return new LoginModel()
                    {
                        Errors = true,
                        Message = SIMPL.Models.Code.Constants.Areas.Common.LoginModel.AuthenticationResultMessages.UnknownResult
                    };
                };

                // And corp username doesn’t match SIMPL username
                // When submitting the association form
                ShimUserManagement.AllInstances.UpdateUsernameStringString = delegate { return UserManagement.UpdateUsernameResult.Success; };
                LoginControllerForTests.ControllerContext = new ControllerContext { HttpContext = contextStub };
                var userAssociationResult = LoginControllerForTests.UserNameAssociation(userAssociationModel);

                // Then usernames are associated
                Assert.IsTrue(wasAttemptToLogUserInCalledForCorp, "Corp credential were not Authorized");
                Assert.IsTrue(wasAttemptToLogUserInCalledForSIMPL, "SIMPL credentials were not Authorized");
                Assert.IsTrue(calledUpdateHistoricalRecored, "UpdateHistoricalRecords was not called");
                Assert.IsNotNull(userAssociationResult);
                #pragma warning disable 183
                // ReSharper generates a warning on the next line, but having this check will guarantee that the return type is checked before the other asserts
                Assert.IsTrue(userAssociationResult is ActionResult, "The return from the UserLogin action method was not a ActionResult");
                #pragma warning restore 183
                Assert.IsTrue(userAssociationResult is RedirectResult, "The return from the UserLogin action method was not a RedirectResult");

                // And user is logged in
                Assert.IsTrue(calledSetCurrentUser, "The set CurrentUser was never called");
                Assert.IsTrue(calledSetAuthCookie, "The set Authorization cookie was never called");

                // And a message is displayed stating “Username association successful! Please use your corp credentials for future logins to SIMPL.”
                var redirectResult = userAssociationResult as RedirectResult;
                Assert.AreEqual("~/SIMPLNET/Search", redirectResult.Url, "The redirect URL was not the search page which should be called when you have a successful login");
            }
        }
Ejemplo n.º 8
0
        public void UserLoginTest_RedirectUrlNull_and_MessageNull()
        {
            using (ShimsContext.Create())
            {
                // Arrange
                Exception expectedException = null;
                const string userName = "******";
                const string password = "******";
                const string returnUrl = "doesNotMatter";

                var requestStub = new StubHttpRequestBase();
                var contextStub = new StubHttpContextBase { RequestGet = () => requestStub };

                LoginControllerForTests.ControllerContext = new ControllerContext
                {
                    HttpContext = contextStub
                };

                ShimLoginController.AllInstances.UserLoginActorStringStringStringStringStringString = (
                    configAdminMode, configAdminUsers, userNameValue, passwordValue, userHostAddress, returnUrlValue, loginViewModel) =>
                    {
                        LoginViewModelForTests.Message = null;
                        LoginViewModelForTests.RedirectUrl = null;
                        return LoginViewModelForTests;
                    };

                try
                {
                    // not assigning as we expect this to throw exception
                    LoginControllerForTests.UserLogin(userName, password, returnUrl);
                }
                catch (Exception ex)
                {
                    expectedException = ex;
                    Assert.AreEqual(Constants.Areas.Common.Controllers.LoginController.UserLoginMethodExceptions.NothingSet, expectedException.Message);
                }

                Assert.IsNotNull(expectedException, "Expected an Exception, but didn't get any exception");
            }
        }
Ejemplo n.º 9
0
        public void UserLoginTest_NeedToChangepasswordRedirection()
        {
            using (ShimsContext.Create())
            {
                // Arrange
                const string userName = "******";
                const string password = "******";
                const string returnUrl = "doesNotMatter";

                var requestStub = new StubHttpRequestBase();
                var contextStub = new StubHttpContextBase { RequestGet = () => requestStub };
                var key = string.Empty;
                var redirectUrl = string.Format("{0}?message=changepassword&params={1}", Constants.Urls.ResetPasswordPage, key);

                LoginControllerForTests.ControllerContext = new ControllerContext { HttpContext = contextStub };

                ShimLoginController.AllInstances.UserLoginActorStringStringStringStringStringString = (
                    configAdminMode, configAdminUsers, userNameValue, passwordValue, userHostAddress, returnUrlValue, loginViewModel) =>
                    {
                        const string message = SIMPL.Models.Code.Constants.Areas.Common.LoginModel.AuthenticationResultMessages.ChangePassword;
                        LoginViewModelForTests.Message = message;
                        LoginViewModelForTests.RedirectUrl = redirectUrl;
                        return LoginViewModelForTests;
                    };

                var resultUserLogin = LoginControllerForTests.UserLogin(userName, password, returnUrl);

                Assert.IsNotNull(resultUserLogin);
                #pragma warning disable 183
                // ReSharper generates a warning on the next line, but having this check will guarantee that the return type is checked before the other asserts
                Assert.IsTrue(resultUserLogin is ActionResult, "Not ActionResult");
                #pragma warning restore 183
                Assert.IsTrue(resultUserLogin is RedirectResult, "Not RedirectResult");

                var resultUserLoginAsRedirectResult = resultUserLogin as RedirectResult;
                Assert.IsTrue(resultUserLoginAsRedirectResult.Url.Contains(redirectUrl));
            }
        }
Ejemplo n.º 10
0
        public void UserLoginTest_ASPPErrorMessageReturned()
        {
            using (ShimsContext.Create())
            {
                // Arrange
                const string userName = "******";
                const string password = "******";
                const string returnUrl = "doesNotMatter";
                const string message = "Your login is correct, but there is a problem with your user profile. (No roles defined for user)";

                var requestStub = new StubHttpRequestBase();
                var contextStub = new StubHttpContextBase { RequestGet = () => requestStub };

                LoginControllerForTests.ControllerContext = new ControllerContext { HttpContext = contextStub };

                ShimLoginController.AllInstances.UserLoginActorStringStringStringStringStringString = (
                    configAdminMode, configAdminUsers, userNameValue, passwordValue, userHostAddress, returnUrlValue, loginViewModel) =>
                    {
                        LoginViewModelForTests.Message = message;
                        LoginViewModelForTests.RedirectUrl = null;
                        return LoginViewModelForTests;
                    };

                var resultUserLogin = LoginControllerForTests.UserLogin(userName, password, returnUrl);

                Assert.IsNotNull(resultUserLogin);
                #pragma warning disable 183
                // ReSharper generates a warning on the next line, but having this check will guarantee that the return type is checked before the other asserts
                Assert.IsTrue(resultUserLogin is ActionResult, "Not ActionResult");
                #pragma warning restore 183
                Assert.IsTrue(resultUserLogin is ViewResult, "Not ViewResult");

                var resultUserLoginAsViewResult = resultUserLogin as ViewResult;
                Assert.IsTrue(resultUserLoginAsViewResult.Model is LoginViewModel, "Not LoginViewModel");

                var testLoginViewModel = resultUserLoginAsViewResult.Model as LoginViewModel;
                Assert.IsNull(testLoginViewModel.RedirectUrl, "testLoginViewModel.RedirectUrl");
                Assert.AreEqual(message, testLoginViewModel.Message);
            }
        }
Ejemplo n.º 11
0
        public void Unknown_SIMPL_user_who_can_authenticate_with_LDAP_redirects_to_UserNameAssociationPage()
        {
            using (ShimsContext.Create())
            {
                // Arrange
                //Given a user
                const string userName = "******";
                const string password = "******";
                const string returnUrl = "doesNotMatter";

                string redirectURL =
                    string.Format("{0}?username={1}", Constants.Urls.UserNameAssociationPage, userName);
                var requestStub = new StubHttpRequestBase();
                var contextStub = new StubHttpContextBase { RequestGet = () => requestStub };

                //And an known AD username and password
                ShimUserManagement.AllInstances.AuthenticateStringString = delegate { return ASPP.UserManagement.AuthenticationResults.Success; };

                //And the AD username does not exist in ASPP
                ShimUserManagement.AllInstances.GetUserDetailsString = delegate { return null; };
                ShimUserManagement.AllInstances.GetUserGroupsString = delegate { return new List<ASPP_Groups>(); };

                LoginControllerForTests.ControllerContext = new ControllerContext { HttpContext = contextStub };

                //When attempting to log in to SIMPL
                var resultUserLogin = LoginControllerForTests.UserLogin(userName, password, returnUrl);

                //Then an error is reported to the user to log in using their ASPP credentials
                Assert.IsNotNull(resultUserLogin);
                #pragma warning disable 183
                // ReSharper generates a warning on the next line, but having this check will guarantee that the return type is checked before the other asserts
                Assert.IsTrue(resultUserLogin is ActionResult, "The return from the UserLogin action method was not a ActionResult");
                #pragma warning restore 183
                Assert.IsTrue(resultUserLogin is RedirectResult, "The return from the UserLogin action method was not a ViewResult");

                var resultUserLoginAsRedirectResult = resultUserLogin as RedirectResult;

                Assert.AreEqual(redirectURL, resultUserLoginAsRedirectResult.Url, string.Format("The RedirectUrl is {0}, should redirect to {1}", resultUserLoginAsRedirectResult.Url, redirectURL));

            }
        }
Ejemplo n.º 12
0
        public void SIMPL_user_timesout_then_logs_back_in_gets_correct_return_url()
        {
            using (ShimsContext.Create())
            {
                // Arrange
                //Given a user
                const string userName = "******";
                const string password = "******";
                const string returnUrl = "/SIMPLNET/Subscriber?subID=370001704986|state=WA|billingRegion=";

                const string redirectURL = "/SIMPLNET/Subscriber?subID=370001704986&state=WA&billingRegion=";
                var session = new System.Web.SessionState.Fakes.ShimHttpSessionState()
                {
                    ItemGetString = (key) =>
                    {
                        return key == "CurrentUser" ? new ShimCurrentUser() : null;
                    }
                };
                var context = new System.Web.Fakes.ShimHttpContext();
                var applicationShim = new System.Web.Fakes.ShimHttpApplicationState();
                context.ApplicationGet = delegate { return applicationShim; };
                var requestStub = new StubHttpRequestBase();
                var contextStub = new StubHttpContextBase { RequestGet = () => requestStub };

                System.Web.Fakes.ShimHttpContext.CurrentGet = delegate { return context; };
                System.Web.Fakes.ShimHttpContext.AllInstances.SessionGet = delegate { return session; };

                ShimUserEvents.AllInstances.InitializeSessionStringString = delegate { };
                ShimSingleConcurrentLoginManager.AllInstances.CreateLoginRecordStringString = delegate { return true; };

                ShimCurrentUser.SetInstanceString = delegate {  };
                ShimCurrentUser.Clear = delegate { };
                ShimCurrentUser.SessionInstanceGet = delegate { return new ShimCurrentUser(); };
                ShimLoginModel.AllInstances.SyncWithOrImportDataFromASPPIErrorLoggingServiceString = (loginModel, errorLoggingService, userNameSentToLoginModel) =>
                {
                };

                ShimSingleConcurrentLoginManager.AllInstances.CreateLoginRecordStringString = delegate { return true; };

                ShimFormsAuthentication.SetAuthCookieStringBooleanString = delegate {  };

                //And an known AD username and password
                ShimUserManagement.AllInstances.AuthenticateStringString = delegate { return ASPP.UserManagement.AuthenticationResults.Success; };

                //And the AD username does not exist in ASPP
                ShimUserManagement.AllInstances.GetUserDetailsString = delegate { return new ASPP_Users(); };
                ShimUserManagement.AllInstances.GetUserGroupsString = delegate
                {
                    return new List<ASPP_Groups>
                    {
                        new ASPP_Groups()
                    };
                };

                LoginControllerForTests.ControllerContext = new ControllerContext { HttpContext = contextStub };

                //When attempting to log in to SIMPL
                var resultUserLogin = LoginControllerForTests.UserLogin(userName, password, returnUrl);

                //Then an error is reported to the user to log in using their ASPP credentials
                Assert.IsNotNull(resultUserLogin);
            #pragma warning disable 183
                // ReSharper generates a warning on the next line, but having this check will guarantee that the return type is checked before the other asserts
                Assert.IsTrue(resultUserLogin is ActionResult, "The return from the UserLogin action method was not a ActionResult");
            #pragma warning restore 183
                Assert.IsTrue(resultUserLogin is RedirectResult, "The return from the UserLogin action method was not a ViewResult");

                var resultUserLoginAsRedirectResult = resultUserLogin as RedirectResult;

                Assert.AreEqual(redirectURL, resultUserLoginAsRedirectResult.Url, string.Format("The RedirectUrl is {0}, should redirect to {1}", resultUserLoginAsRedirectResult.Url, redirectURL));

            }
        }
        public void TestLogin()
        {
            string testUserName = "******";
            string testPassword = "******";
            bool testRememberMe = false;
            string returnUrl = "/foo.html";

            var loginModel = new LoginModel
            {
                UserName = testUserName,
                Password = testPassword,
                RememberMe = testRememberMe
            };

            var accountController = new AccountController();

            //Setup underpinning via stubbing such that UrlHelper
            //can validate that our "foo.html" is local
            var stubHttpContext = new StubHttpContextBase();
            var stubHttpRequestBase = new StubHttpRequestBase();
            stubHttpContext.RequestGet = () => stubHttpRequestBase;
            var requestContext = new RequestContext(stubHttpContext, new RouteData());
            accountController.Url = new UrlHelper(requestContext);

            RedirectResult redirectResult;
            //Scope the detours we're creating
            using (ShimsContext.Create())
            {
                //Sets up a detour for Membership.ValidateUser to our mocked implementation
                ShimMembership.ValidateUserStringString = (userName, password) =>
                {
                    Assert.AreEqual(testUserName, userName);
                    Assert.AreEqual(testPassword, password);
                    return true;
                };

                //Sets up a detour for FormsAuthentication.SetAuthCookie to our mocked implementation
                ShimFormsAuthentication.SetAuthCookieStringBoolean = (userName, rememberMe) =>
                {
                    Assert.AreEqual(testUserName, userName);
                    Assert.AreEqual(testRememberMe, rememberMe);
                };

                redirectResult = accountController.Login(loginModel, returnUrl) as RedirectResult;
            }

            Assert.NotNull(redirectResult);
            Assert.AreEqual(redirectResult.Url, returnUrl);
        }
Ejemplo n.º 14
0
        private void SetupTest(ContactModel contactModelToDo, CultureInfo culture, string actionStr)
        {
            LanguageEnum languageEnum = (culture.TwoLetterISOLanguageName == "fr" ? LanguageEnum.fr : LanguageEnum.en);

            if (contactModelToDo == null)
            {
                user = null;
            }
            else
            {
                user = new GenericPrincipal(new GenericIdentity(contactModelToDo.LoginEmail, "Forms"), null);
            }
            routeData = new RouteData();
            routeData.Values.Add("culture", culture);
            routeData.Values.Add("controller", controllerName);
            routeData.Values.Add("action", actionStr);

            stubHttpContext            = new StubHttpContextBase();
            stubHttpRequestBase        = new StubHttpRequestBase();
            stubHttpContext.RequestGet = () => stubHttpRequestBase;
            requestContext             = new RequestContext(stubHttpContext, routeData);
            controller     = new TelController();
            controller.Url = new UrlHelper(requestContext);
            controller.ControllerContext = new ControllerContext(stubHttpContext, routeData, controller);
            stubHttpContext.UserGet      = () => user;

            controller.SetRequestContext(requestContext);


            // BaseController Asserts
            Assert.IsNotNull(controller);
            Assert.AreEqual(2, controller.CultureListAllowable.Count);
            Assert.AreEqual("en-CA", controller.CultureListAllowable[0]);
            Assert.AreEqual("fr-CA", controller.CultureListAllowable[1]);
            Assert.IsNotNull(controller._ContactService);
            Assert.IsNotNull(controller._RequestContext);
            Assert.IsNotNull(controller._TVItemService);
            Assert.IsNotNull(controller._TVItemStatService);

            Assert.IsNotNull(culture.Name, controller._RequestContext.RouteData.Values["culture"].ToString());
            Assert.IsNotNull(controllerName, controller._RequestContext.RouteData.Values["controller"].ToString());
            Assert.IsNotNull(actionStr, controller._RequestContext.RouteData.Values["action"].ToString());
            Assert.AreEqual((culture.TwoLetterISOLanguageName == "fr" ? LanguageEnum.fr : LanguageEnum.en), controller.LanguageRequest);
            Assert.AreEqual((culture.TwoLetterISOLanguageName == "fr" ? LanguageEnum.fr : LanguageEnum.en), controller.ViewBag.Language);
            Assert.AreEqual(culture.Name, controller.CultureRequest);
            Assert.AreEqual(culture.Name, controller.ViewBag.Culture);
            Assert.AreEqual(Thread.CurrentThread.CurrentCulture, culture);
            Assert.AreEqual(Thread.CurrentThread.CurrentUICulture, culture);
            if (contactModelToDo != null)
            {
                Assert.AreEqual(contactModelToDo.IsAdmin, controller.IsAdmin);
                Assert.AreEqual(contactModelToDo.IsAdmin, controller.ViewBag.IsAdmin);
            }
            Assert.AreEqual(true, controller.Debug);
            Assert.AreEqual(true, controller.ViewBag.Debug);

            // TelController Asserts
            Assert.IsNotNull(controller._TelController);
            Assert.IsNotNull(controller._TelService);
            Assert.IsNotNull(controller._TVItemLinkService);

            // variables for testing
            randomService = new RandomService(languageEnum, user);
            telService    = new TelService(languageEnum, user);
        }