public async Task VerifyPhoneNumberPostSendsRemoveUserProfileIncompleteClaimCommandWhenUserIsNotNullAndPhoneNumberChangeWasSuccessfulAndUserProfileIsComplete()
        {
            //Arrange
            var userId      = "userId";
            var token       = "token";
            var phoneNumber = "phone";
            var user        = UserWithCompleteProfile(userId, phoneNumber);

            var model = new VerifyPhoneNumberViewModel {
                PhoneNumber = phoneNumber, Code = token
            };
            var userManager = UserManagerMockHelper.CreateUserManagerMock();

            userManager.Setup(x => x.GetUserId(It.IsAny <ClaimsPrincipal>())).Returns(userId);
            userManager.Setup(x => x.ChangePhoneNumberAsync(It.IsAny <ApplicationUser>(),
                                                            It.IsAny <string>(),
                                                            It.IsAny <string>())).ReturnsAsync(IdentityResult.Success);

            var signInManagerMock = SignInManagerMockHelper.CreateSignInManagerMock(userManager);
            var mediator          = new Mock <IMediator>();

            mediator.Setup(x => x.SendAsync(It.IsAny <UserByUserIdQuery>())).ReturnsAsync(user);

            var controller = new ManageController(userManager.Object, signInManagerMock.Object, mediator.Object);

            controller.SetFakeUser(userId);

            //Act
            await controller.VerifyPhoneNumber(model);

            //Assert
            mediator.Verify(x => x.SendAsync(It.IsAny <RemoveUserProfileIncompleteClaimCommand>()), Times.Once);
        }
Exemple #2
0
        public async Task SendShouldNotCreateInvite_WhenUserIsNotOrgAdminForCampaign()
        {
            // Arrange
            var mockMediator = new Mock <IMediator>();
            var @event       = new Event
            {
                Campaign = new Campaign()
                {
                    ManagingOrganizationId = 1
                }
            };

            mockMediator.Setup(mock => mock.SendAsync(It.IsAny <EventByEventIdQuery>())).ReturnsAsync(@event);

            var sut = new EventManagerInviteController(mockMediator.Object, UserManagerMockHelper.CreateUserManagerMock().Object);

            sut.MakeUserAnOrgAdmin(organizationId: "2");
            var invite = new EventManagerInviteViewModel();

            // Act
            IActionResult result = await sut.Send(eventId, invite);

            // Assert
            mockMediator.Verify(x => x.SendAsync(It.IsAny <CreateEventManagerInviteCommand>()), Times.Never);
        }
Exemple #3
0
        public async Task SendShouldCreateInvite_WhenUserIsOrgAdminForCampaign()
        {
            // Arrange
            var mockMediator = new Mock <IMediator>();
            var @event       = new Event
            {
                Campaign = new Campaign()
                {
                    ManagingOrganizationId = 1
                }
            };

            mockMediator.Setup(mock => mock.SendAsync(It.IsAny <EventByEventIdQuery>())).ReturnsAsync(@event);
            var userManager = UserManagerMockHelper.CreateUserManagerMock();

            userManager.Setup(x => x.GetUserAsync(It.IsAny <ClaimsPrincipal>())).ReturnsAsync(new ApplicationUser());

            var sut = new EventManagerInviteController(mockMediator.Object, userManager.Object);

            sut.MakeUserAnOrgAdmin(organizationId: "1");
            var invite = new EventManagerInviteViewModel
            {
                EventId             = 1,
                InviteeEmailAddress = "*****@*****.**",
                CustomMessage       = "test message"
            };

            // Act
            IActionResult result = await sut.Send(invite.EventId, invite);

            // Assert
            mockMediator.Verify(x => x.SendAsync(It.Is <CreateEventManagerInviteCommand>(c => c.Invite == invite)), Times.Once);
        }
Exemple #4
0
        public async Task RegisterInvokesCreateAsyncWithCorrectUserAndPassword()
        {
            const string defaultTimeZone = "DefaultTimeZone";

            var model = new RegisterViewModel {
                Email = "email", Password = "******"
            };

            var generalSettings = new Mock <IOptions <GeneralSettings> >();

            generalSettings.Setup(x => x.Value).Returns(new GeneralSettings {
                DefaultTimeZone = defaultTimeZone
            });

            var userManager = UserManagerMockHelper.CreateUserManagerMock();

            userManager.Setup(x => x.CreateAsync(It.IsAny <ApplicationUser>(), It.IsAny <string>())).ReturnsAsync(IdentityResult.Failed());

            var sut = new AdminController(userManager.Object, null, null, null, generalSettings.Object);

            await sut.Register(model);

            userManager.Verify(x => x.CreateAsync(It.Is <ApplicationUser>(au =>
                                                                          au.UserName == model.Email &&
                                                                          au.Email == model.Email &&
                                                                          au.TimeZoneId == defaultTimeZone),
                                                  model.Password));
        }
Exemple #5
0
        public async Task SendPassesCorrectViewModelToView()
        {
            // Arrange
            var mockMediator = new Mock <IMediator>();
            var viewModel    = new EventManagerInviteViewModel
            {
                EventId        = eventId,
                EventName      = "TestEvent",
                CampaignId     = campaignId,
                CampaignName   = "TestCampaign",
                OrganizationId = 1
            };

            mockMediator.Setup(mock => mock.SendAsync(It.IsAny <EventManagerInviteQuery>())).ReturnsAsync(viewModel);

            var sut = new EventManagerInviteController(mockMediator.Object, UserManagerMockHelper.CreateUserManagerMock().Object);

            sut.MakeUserAnOrgAdmin(organizationId: "1");

            // Act
            IActionResult result = await sut.Send(eventId);

            // Assert
            ViewResult view  = result as ViewResult;
            var        model = Assert.IsType <EventManagerInviteViewModel>(view.ViewData.Model);

            Assert.Equal(eventId, model.EventId);
            Assert.Equal(campaignId, model.CampaignId);
            Assert.Equal("TestCampaign", model.CampaignName);
            Assert.Equal("TestEvent", model.EventName);
        }
Exemple #6
0
        public async Task ConfirmEmailSendsSendApproveOrganizationUserAccountEmailWithCorrectDataWhenUsersEmailIsConfirmedSuccessfully()
        {
            const string defaultAdminUserName = "******";
            const string callbackUrl          = "callbackUrl";

            var userManager = UserManagerMockHelper.CreateUserManagerMock();

            userManager.Setup(x => x.FindByIdAsync(It.IsAny <string>())).ReturnsAsync(new ApplicationUser());
            userManager.Setup(x => x.ConfirmEmailAsync(It.IsAny <ApplicationUser>(), It.IsAny <string>())).ReturnsAsync(IdentityResult.Success);

            var settings = new Mock <IOptions <SampleDataSettings> >();

            settings.Setup(x => x.Value).Returns(new SampleDataSettings {
                DefaultAdminUsername = defaultAdminUserName
            });

            var urlHelper = new Mock <IUrlHelper>();

            urlHelper.Setup(x => x.Action(It.IsAny <UrlActionContext>())).Returns(callbackUrl);

            var mediator = new Mock <IMediator>();

            var sut = new AdminController(userManager.Object, null, mediator.Object, settings.Object, null);

            sut.SetFakeHttpRequestSchemeTo(It.IsAny <string>());
            sut.Url = urlHelper.Object;

            await sut.ConfirmEmail(It.IsAny <string>(), "code");

            mediator.Verify(x => x.SendAsync(It.Is <SendApproveOrganizationUserAccountEmail>(y => y.DefaultAdminUsername == defaultAdminUserName && y.CallbackUrl == callbackUrl)));
        }
Exemple #7
0
        public async Task SendCodeGetReturnsSendCodeViewModelWithCorrectData()
        {
            const string returnUrl  = "returnUrl";
            const bool   rememberMe = true;

            var userFactors = new List <string> {
                "userFactor1", "userFactor2"
            };
            var expectedProviders = userFactors.Select(factor => new SelectListItem {
                Text = factor, Value = factor
            }).ToList();

            var userManager   = UserManagerMockHelper.CreateUserManagerMock();
            var signInManager = SignInManagerMockHelper.CreateSignInManagerMock(userManager);

            signInManager.Setup(x => x.GetTwoFactorAuthenticationUserAsync()).ReturnsAsync(new ApplicationUser());
            userManager.Setup(x => x.GetValidTwoFactorProvidersAsync(It.IsAny <ApplicationUser>())).ReturnsAsync(userFactors);

            var sut = new AdminController(userManager.Object, signInManager.Object, null, null, null);

            var result = await sut.SendCode(returnUrl, rememberMe) as ViewResult;

            var modelResult = result.ViewData.Model as SendCodeViewModel;

            Assert.Equal(modelResult.ReturnUrl, returnUrl);
            Assert.Equal(modelResult.RememberMe, rememberMe);
            Assert.Equal(expectedProviders, modelResult.Providers, new SelectListItemComparer());
        }
        public async Task IndexPostReturnsCorrectViewModelWhenModelStateIsInvalid()
        {
            //Arrange
            var userManagerMock   = UserManagerMockHelper.CreateUserManagerMock();
            var signInManagerMock = SignInManagerMockHelper.CreateSignInManagerMock(userManagerMock);

            var mediator = new Mock <IMediator>();

            mediator.Setup(m => m.SendAsync(It.IsAny <UserByUserIdQuery>())).ReturnsAsync(new ApplicationUser());
            var controller = new ManageController(userManagerMock.Object, signInManagerMock.Object, mediator.Object);

            controller.SetFakeUser("userId");
            IndexViewModel invalidVm = new IndexViewModel();

            controller.ModelState.AddModelError("FirstName", "Can't be a number");

            //Act
            var result = await controller.Index(invalidVm);

            var resultViewModel = ((ViewResult)result);
            var vm = (IndexViewModel)resultViewModel.ViewData.Model;

            //Assert
            Assert.IsType <IndexViewModel>(vm);
        }
        public async Task IndexPostInvokesAddClaimAsyncWithCorrectParametersWhenUsersTimeZoneDoesNotEqualModelsTimeZone()
        {
            //Arrange
            var userManagerMock = UserManagerMockHelper.CreateUserManagerMock();

            userManagerMock.Setup(x => x.AddClaimAsync(It.IsAny <ApplicationUser>(), It.IsAny <Claim>())).ReturnsAsync(IdentityResult.Success);

            var signInManagerMock = SignInManagerMockHelper.CreateSignInManagerMock(userManagerMock);

            var mediator = new Mock <IMediator>();
            var user     = new ApplicationUser {
                TimeZoneId = "timeZoneId"
            };

            mediator.Setup(m => m.SendAsync(It.IsAny <UserByUserIdQuery>())).ReturnsAsync(user);

            var controller = new ManageController(userManagerMock.Object, signInManagerMock.Object, mediator.Object);

            controller.SetFakeUser("userId");
            var vM = new IndexViewModel {
                TimeZoneId = "differentTimeZoneId"
            };

            //Act
            await controller.Index(vM);

            //Assert
            userManagerMock.Verify(x => x.AddClaimAsync(user, It.Is <Claim>(c => c.Type == AllReady.Security.ClaimTypes.TimeZoneId)), Times.Once);
        }
        public async Task RemovePhoneNumberRedirectsToCorrectActionWithCorrectRouteValuesWhenUserIsNotNullAndPhoneNumberWasSetSuccessfully()
        {
            //Arrange
            var userId      = "userId";
            var phoneNumber = "phone";
            var user        = UserWithCompleteProfile(userId, phoneNumber);

            var userManager = UserManagerMockHelper.CreateUserManagerMock();

            userManager.Setup(x => x.GetUserId(It.IsAny <ClaimsPrincipal>())).Returns(userId);
            userManager.Setup(x => x.SetPhoneNumberAsync(It.IsAny <ApplicationUser>(),
                                                         It.IsAny <string>())).ReturnsAsync(IdentityResult.Success);

            var signInManager = SignInManagerMockHelper.CreateSignInManagerMock(userManager);

            var mediator = new Mock <IMediator>();

            mediator.Setup(x => x.SendAsync(It.IsAny <UserByUserIdQuery>())).ReturnsAsync(user);

            var controller = new ManageController(userManager.Object, signInManager.Object, mediator.Object);

            controller.SetFakeUser(userId);

            //Act
            var result = await controller.RemovePhoneNumber() as RedirectToActionResult;

            //Assert
            Assert.Equal("Index", result.ActionName);
            Assert.Equal(ManageController.ManageMessageId.RemovePhoneSuccess, result.RouteValues["Message"]);
        }
        public async Task IndexPostSendsUserByUserIdQueryWithCorrectUserId()
        {
            //Arrange
            var userId = "userId";

            var userManagerMock = UserManagerMockHelper.CreateUserManagerMock();

            userManagerMock.Setup(x => x.GetUserId(It.IsAny <ClaimsPrincipal>())).Returns(userId);

            var signInManagerMock = SignInManagerMockHelper.CreateSignInManagerMock(userManagerMock);

            var mediator = new Mock <IMediator>();

            mediator.Setup(x => x.SendAsync(It.IsAny <AllReady.Features.Manage.UserByUserIdQuery>())).ReturnsAsync(new ApplicationUser());

            var controller = new ManageController(userManagerMock.Object, signInManagerMock.Object, mediator.Object);

            controller.SetFakeUser(userId);

            var vm = new IndexViewModel();

            await controller.Index(vm);

            mediator.Verify(m => m.SendAsync(It.Is <AllReady.Features.Manage.UserByUserIdQuery>(u => u.UserId == userId)), Times.Once);
        }
        public async Task RemovePhoneNumberInvokesRefreshSignInAsyncWithCorrectParametersWhenUserIsNotNullAndPhoneNumberWasSetSuccessfullyAndUsersProfileIsComplete()
        {
            //Arrange
            var userId      = "userId";
            var phoneNumber = "phone";
            var user        = UserWithCompleteProfile(userId, phoneNumber);

            var userManager = UserManagerMockHelper.CreateUserManagerMock();

            userManager.Setup(x => x.GetUserId(It.IsAny <ClaimsPrincipal>())).Returns(userId);
            userManager.Setup(x => x.SetPhoneNumberAsync(It.IsAny <ApplicationUser>(),
                                                         It.IsAny <string>())).ReturnsAsync(IdentityResult.Success);

            var signInManager = SignInManagerMockHelper.CreateSignInManagerMock(userManager);

            var mediator = new Mock <IMediator>();

            mediator.Setup(x => x.SendAsync(It.IsAny <UserByUserIdQuery>())).ReturnsAsync(user);

            var controller = new ManageController(userManager.Object, signInManager.Object, mediator.Object);

            controller.SetFakeUser(userId);

            //Act
            await controller.RemovePhoneNumber();

            //Assert
            signInManager.Verify(x => x.RefreshSignInAsync(It.IsAny <ApplicationUser>()), Times.Once);
        }
        public async Task AddPhoneNumberPostInvokesGenerateChangePhoneNumberTokenAsyncWithCorrectParametersWhenModelStateIsValid()
        {
            //Arrange
            var userId = "userId";
            var token  = "token";
            var user   = new ApplicationUser {
                Id = userId
            };
            var model = new AddPhoneNumberViewModel {
                PhoneNumber = "phone"
            };

            var userManager = UserManagerMockHelper.CreateUserManagerMock();

            userManager.Setup(x => x.GetUserId(It.IsAny <ClaimsPrincipal>())).Returns(userId);
            userManager.Setup(x => x.GenerateChangePhoneNumberTokenAsync(It.IsAny <ApplicationUser>(),
                                                                         It.IsAny <string>())).ReturnsAsync(token);

            var signInManagerMock = SignInManagerMockHelper.CreateSignInManagerMock(userManager);
            var mediator          = new Mock <IMediator>();

            mediator.Setup(x => x.SendAsync(It.IsAny <UserByUserIdQuery>())).ReturnsAsync(user);

            var controller = new ManageController(userManager.Object, signInManagerMock.Object, mediator.Object);

            controller.SetFakeUser(userId);

            //Act
            await controller.AddPhoneNumber(model);

            //Assert
            userManager.Verify(x => x.GenerateChangePhoneNumberTokenAsync(It.Is <ApplicationUser>(u => u.Id == userId),
                                                                          It.Is <string>(p => p == model.PhoneNumber)),
                               Times.Once);
        }
        public async Task RemovePhoneNumberInvokesSetPhoneNumberAsyncWithCorrectParametersWhenUserIsNotNull()
        {
            //Arrange
            var userId = "userId";
            var user   = new ApplicationUser {
                Id = userId
            };
            var userManager = UserManagerMockHelper.CreateUserManagerMock();

            userManager.Setup(x => x.GetUserId(It.IsAny <ClaimsPrincipal>())).Returns(userId);
            userManager.Setup(x => x.SetPhoneNumberAsync(It.IsAny <ApplicationUser>(),
                                                         It.IsAny <string>())).ReturnsAsync(new IdentityResult());

            var signInManagerMock = SignInManagerMockHelper.CreateSignInManagerMock(userManager);
            var mediator          = new Mock <IMediator>();

            mediator.Setup(x => x.SendAsync(It.IsAny <UserByUserIdQuery>())).ReturnsAsync(user);

            var controller = new ManageController(userManager.Object, signInManagerMock.Object, mediator.Object);

            controller.SetFakeUser(userId);

            //Act
            await controller.RemovePhoneNumber();

            //Assert
            userManager.Verify(x => x.SetPhoneNumberAsync(It.Is <ApplicationUser>(u => u == user),
                                                          It.Is <string>(p => p == null)),
                               Times.Once);
        }
Exemple #15
0
        public async Task RegisterRedirectsToCorrectActionWhenUserCreationIsSuccessful()
        {
            var generalSettings = new Mock <IOptions <GeneralSettings> >();

            generalSettings.Setup(x => x.Value).Returns(new GeneralSettings());

            var userManager = UserManagerMockHelper.CreateUserManagerMock();

            userManager.Setup(x => x.CreateAsync(It.IsAny <ApplicationUser>(), It.IsAny <string>())).ReturnsAsync((IdentityResult.Success));
            userManager.Setup(x => x.GenerateEmailConfirmationTokenAsync(It.IsAny <ApplicationUser>())).ReturnsAsync(It.IsAny <string>());

            var urlHelper = new Mock <IUrlHelper>();

            urlHelper.Setup(x => x.Action(It.IsAny <UrlActionContext>())).Returns(It.IsAny <string>());

            var sut = new AdminController(userManager.Object, null, Mock.Of <IMediator>(), null, generalSettings.Object);

            sut.SetFakeHttpRequestSchemeTo(It.IsAny <string>());
            sut.Url = urlHelper.Object;

            var result = await sut.Register(new RegisterViewModel()) as RedirectToActionResult;

            Assert.Equal(result.ActionName, nameof(AdminController.DisplayEmail));
            Assert.Equal(result.ControllerName, "Admin");
        }
Exemple #16
0
        public async Task UnregisterTaskReturnsCorrectStatus()
        {
            const string status = "status";

            var mediator = new Mock <IMediator>();

            mediator.Setup(x => x.SendAsync(It.IsAny <VolunteerTaskUnenrollCommand>())).ReturnsAsync(new VolunteerTaskUnenrollResult {
                Status = status
            });

            var userManager = UserManagerMockHelper.CreateUserManagerMock();

            userManager.Setup(x => x.GetUserId(It.IsAny <ClaimsPrincipal>())).Returns(It.IsAny <string>());

            var sut = new TaskApiController(mediator.Object, null, userManager.Object);

            sut.SetDefaultHttpContext();

            var jsonResult = await sut.UnregisterTask(It.IsAny <int>());

            var result = jsonResult.GetValueForProperty <string>("Status");

            Assert.IsType <JsonResult>(jsonResult);
            Assert.IsType <string>(result);
            Assert.Equal(result, status);
        }
Exemple #17
0
        public async Task ConfirmEmailInvokesUrlActionWithCorrectParametersWhenUsersEmailIsConfirmedSuccessfully()
        {
            const string requestScheme = "requestScheme";
            const string userId        = "1";

            var userManager = UserManagerMockHelper.CreateUserManagerMock();

            userManager.Setup(x => x.FindByIdAsync(It.IsAny <string>())).ReturnsAsync(new ApplicationUser {
                Id = userId
            });
            userManager.Setup(x => x.ConfirmEmailAsync(It.IsAny <ApplicationUser>(), It.IsAny <string>())).ReturnsAsync(IdentityResult.Success);

            var settings = new Mock <IOptions <SampleDataSettings> >();

            settings.Setup(x => x.Value).Returns(new SampleDataSettings());

            var urlHelper = new Mock <IUrlHelper>();

            var sut = new AdminController(userManager.Object, null, Mock.Of <IMediator>(), settings.Object, null);

            sut.SetFakeHttpRequestSchemeTo(requestScheme);
            sut.Url = urlHelper.Object;

            await sut.ConfirmEmail(It.IsAny <string>(), "code");

            urlHelper.Verify(x => x.Action(It.Is <UrlActionContext>(uac =>
                                                                    uac.Action == "EditUser" &&
                                                                    uac.Controller == "Site" &&
                                                                    uac.Protocol == requestScheme &&
                                                                    uac.Values.ToString() == $"{{ area = Admin, userId = {userId} }}")),
                             Times.Once);
        }
Exemple #18
0
        public async Task AssociateUser_ShouldInvokeFindByEmailAsyncOnce_WhenAssociateUserIsInvokedMoreThanOnceWithSameClaimsPrincipal()
        {
            const string email = "Email";
            const string authentciationType = "CustomApiKeyAuth";

            var userManager = UserManagerMockHelper.CreateUserManagerMock();

            userManager.Setup(x => x.FindByEmailAsync(email)).ReturnsAsync(new ApplicationUser {
                Email = email
            });

            var sut = new UserAuthorizationService(userManager.Object, Mock.Of <AllReadyContext>());

            var claimsIdentity1 = new ClaimsIdentity(new List <Claim>(), authentciationType);

            claimsIdentity1.AddClaim(new Claim(ClaimsIdentity.DefaultNameClaimType, email));

            var claimsIdentity2 = new ClaimsIdentity(new List <Claim>(), authentciationType);

            claimsIdentity2.AddClaim(new Claim(ClaimsIdentity.DefaultNameClaimType, email));

            await sut.AssociateUser(new ClaimsPrincipal(claimsIdentity1));

            await sut.AssociateUser(new ClaimsPrincipal(claimsIdentity2));

            userManager.Verify(x => x.FindByEmailAsync(email), Times.Exactly(1));
        }
Exemple #19
0
        public async Task ConfirmEmailReturnsCorrectViewWhenUsersConfirmationIsSuccessful()
        {
            var userManager = UserManagerMockHelper.CreateUserManagerMock();

            userManager.Setup(x => x.FindByIdAsync(It.IsAny <string>())).ReturnsAsync(new ApplicationUser());
            userManager.Setup(x => x.ConfirmEmailAsync(It.IsAny <ApplicationUser>(), It.IsAny <string>())).ReturnsAsync(IdentityResult.Success);

            var urlHelper = new Mock <IUrlHelper>();

            urlHelper.Setup(x => x.Action(It.IsAny <UrlActionContext>())).Returns(It.IsAny <string>());

            var settings = new Mock <IOptions <SampleDataSettings> >();

            settings.Setup(x => x.Value).Returns(new SampleDataSettings {
                DefaultAdminUsername = It.IsAny <string>()
            });

            var sut = new AdminController(userManager.Object, null, Mock.Of <IMediator>(), settings.Object, null);

            sut.SetFakeHttpRequestSchemeTo(It.IsAny <string>());
            sut.Url = urlHelper.Object;

            var result = await sut.ConfirmEmail("userId", "code") as ViewResult;

            Assert.Equal(result.ViewName, "ConfirmEmail");
        }
Exemple #20
0
        public async Task GetLedItineraryIds_DoesNotCallContextOnSecondLoad()
        {
            var userManager = UserManagerMockHelper.CreateUserManagerMock();

            userManager.Setup(x => x.FindByEmailAsync(It.IsAny <string>())).ReturnsAsync(new ApplicationUser {
                Id = UserId
            });
            var sut = new UserAuthorizationService(userManager.Object, Context);

            var claimsIdentity = new ClaimsIdentity(new List <Claim>(), "CustomApiKeyAuth");

            await sut.AssociateUser(new ClaimsPrincipal(claimsIdentity));

            await sut.GetLedItineraryIds();

            var manager = Context.VolunteerTaskSignups.First();

            Context.Remove(manager);
            Context.SaveChanges();

            Context.VolunteerTaskSignups.Count().ShouldBe(0);

            var teamLeadIds2 = await sut.GetLedItineraryIds();

            teamLeadIds2.Count.ShouldBe(1);
        }
Exemple #21
0
        public async Task SendCodePostReturnsRedirectToActionResult()
        {
            var model = new SendCodeViewModel {
                SelectedProvider = string.Empty, ReturnUrl = "ReturnUrl", RememberMe = true
            };

            var routeValues = new Dictionary <string, object>
            {
                ["Provider"]   = model.SelectedProvider,
                ["ReturnUrl"]  = model.ReturnUrl,
                ["RememberMe"] = model.RememberMe
            };

            var userManager   = UserManagerMockHelper.CreateUserManagerMock();
            var signInManager = SignInManagerMockHelper.CreateSignInManagerMock(userManager);

            signInManager.Setup(x => x.GetTwoFactorAuthenticationUserAsync()).ReturnsAsync(new ApplicationUser());
            userManager.Setup(x => x.GenerateTwoFactorTokenAsync(It.IsAny <ApplicationUser>(), It.IsAny <string>())).ReturnsAsync("token");

            var sut    = new AdminController(userManager.Object, signInManager.Object, null, null, null);
            var result = await sut.SendCode(model) as RedirectToActionResult;

            Assert.Equal(result.ActionName, nameof(AdminController.VerifyCode));
            Assert.Equal(result.RouteValues, routeValues);
        }
        public async Task LoginReturnsCorrectCookieString()
        {
            var model = new LoginViewModel()
            {
                Email    = "*****@*****.**",
                Password = "******"
            };

            var mediator      = new Mock <IMediator>();
            var userManager   = UserManagerMockHelper.CreateUserManagerMock();
            var signInManager = SignInManagerMockHelper.CreateSignInManagerMock(userManager);

            signInManager.Setup(
                x =>
                x.PasswordSignInAsync(It.IsAny <string>(), It.IsAny <string>(), It.IsAny <bool>(),
                                      It.IsAny <bool>()))
            .ReturnsAsync(Microsoft.AspNetCore.Identity.SignInResult.Success);

            var sut = new MeApiController(userManager.Object, signInManager.Object, mediator.Object);
            var mockedHttpRequest = sut.GetMockHttpRequest();

            await sut.Login(model);

            mockedHttpRequest.Verify(x => x.Cookies[".AspNet.ApplicationCookie"], Times.Once());
        }
Exemple #23
0
        public async Task SendReturnsSendView_WhenUserIsOrgAdminForCampaign()
        {
            // Arrange
            var mockMediator = new Mock <IMediator>();
            var viewModel    = new EventManagerInviteViewModel
            {
                OrganizationId = 1
            };

            mockMediator.Setup(mock => mock.SendAsync(It.IsAny <EventManagerInviteQuery>())).ReturnsAsync(viewModel);
            var userManager = UserManagerMockHelper.CreateUserManagerMock();

            userManager.Setup(x => x.GetUserAsync(It.IsAny <ClaimsPrincipal>())).ReturnsAsync(new ApplicationUser());

            var sut = new EventManagerInviteController(mockMediator.Object, userManager.Object);

            sut.MakeUserAnOrgAdmin(organizationId: "1");

            // Act
            IActionResult result = await sut.Send(eventId);

            // Assert
            Assert.IsType <ViewResult>(result);
            ViewResult view = result as ViewResult;
        }
Exemple #24
0
        public async Task RegisterInvokesGenerateEmailConfirmationTokenAsyncWithCorrectUserWhenUserCreationIsSuccessful()
        {
            const string defaultTimeZone = "DefaultTimeZone";

            var model = new RegisterViewModel {
                Email = "email", Password = "******"
            };

            var generalSettings = new Mock <IOptions <GeneralSettings> >();

            generalSettings.Setup(x => x.Value).Returns(new GeneralSettings {
                DefaultTimeZone = defaultTimeZone
            });

            var userManager = UserManagerMockHelper.CreateUserManagerMock();

            userManager.Setup(x => x.CreateAsync(It.IsAny <ApplicationUser>(), It.IsAny <string>())).ReturnsAsync(IdentityResult.Success);

            var sut = new AdminController(userManager.Object, null, Mock.Of <IMediator>(), null, generalSettings.Object);

            sut.SetFakeHttpRequestSchemeTo(It.IsAny <string>());
            sut.Url = Mock.Of <IUrlHelper>();

            await sut.Register(model);

            userManager.Verify(x => x.GenerateEmailConfirmationTokenAsync(It.Is <ApplicationUser>(au =>
                                                                                                  au.UserName == model.Email &&
                                                                                                  au.Email == model.Email &&
                                                                                                  au.TimeZoneId == defaultTimeZone)));
        }
Exemple #25
0
        public async Task SendPostReturnsUnauthorizedResult_WhenUserIsNotOrgAdminForCampaign()
        {
            // Arrange
            var mockMediator = new Mock <IMediator>();
            var @event       = new Event
            {
                Campaign = new Campaign()
                {
                    ManagingOrganizationId = 1
                }
            };

            mockMediator.Setup(mock => mock.SendAsync(It.IsAny <EventByEventIdQuery>())).ReturnsAsync(@event);

            var sut = new EventManagerInviteController(mockMediator.Object, UserManagerMockHelper.CreateUserManagerMock().Object);

            sut.MakeUserAnOrgAdmin(organizationId: "2");
            var invite = new EventManagerInviteViewModel();

            // Act
            IActionResult result = await sut.Send(eventId, invite);

            // Assert
            Assert.IsType <UnauthorizedResult>(result);
        }
Exemple #26
0
        public async Task RegisterInvokesUrlActionWithCorrectParametersWhenUserCreationIsSuccessful()
        {
            const string requestScheme = "requestScheme";

            var generalSettings = new Mock <IOptions <GeneralSettings> >();

            generalSettings.Setup(x => x.Value).Returns(new GeneralSettings());

            var userManager = UserManagerMockHelper.CreateUserManagerMock();

            userManager.Setup(x => x.CreateAsync(It.IsAny <ApplicationUser>(), It.IsAny <string>())).ReturnsAsync(IdentityResult.Success);
            userManager.Setup(x => x.GenerateEmailConfirmationTokenAsync(It.IsAny <ApplicationUser>())).ReturnsAsync(It.IsAny <string>());

            var sut = new AdminController(userManager.Object, null, Mock.Of <IMediator>(), null, generalSettings.Object);

            sut.SetFakeHttpRequestSchemeTo(requestScheme);
            var urlHelper = new Mock <IUrlHelper>();

            sut.Url = urlHelper.Object;

            await sut.Register(new RegisterViewModel());

            //note: I can't test the Values part here b/c I do not have control over the Id generation (which is a guid represented as as string) on ApplicationUser b/c it's new'ed up in the controller
            urlHelper.Verify(mock => mock.Action(It.Is <UrlActionContext>(uac =>
                                                                          uac.Action == "ConfirmEmail" &&
                                                                          uac.Controller == "Admin" &&
                                                                          uac.Protocol == requestScheme)),
                             Times.Once);
        }
Exemple #27
0
        public async Task SendShouldNotCreateInvite_WhenAnInviteAlreadyExistsForInviteeEmailAddress()
        {
            // Arrange
            var mockMediator = new Mock <IMediator>();
            var @event       = new Event
            {
                Campaign = new Campaign()
                {
                    ManagingOrganizationId = 1
                }
            };

            mockMediator.Setup(mock => mock.SendAsync(It.IsAny <EventByEventIdQuery>())).ReturnsAsync(@event);
            mockMediator.Setup(mock => mock.SendAsync(It.IsAny <UserHasEventManagerInviteQuery>())).ReturnsAsync(true);

            var sut = new EventManagerInviteController(mockMediator.Object, UserManagerMockHelper.CreateUserManagerMock().Object);

            sut.MakeUserAnOrgAdmin(organizationId: "1");
            var invite = new EventManagerInviteViewModel
            {
                EventId             = 1,
                InviteeEmailAddress = "*****@*****.**",
                CustomMessage       = "test message"
            };

            // Act
            IActionResult result = await sut.Send(invite.EventId, invite);

            // Assert
            mockMediator.Verify(x => x.SendAsync(It.Is <CreateEventManagerInviteCommand>(c => c.Invite == invite)), Times.Never);
        }
Exemple #28
0
        public async Task RegisterSendsSendConfirmAccountEmailWithCorrectDataWhenUserCreationIsSuccessful()
        {
            const string callbackUrl = "callbackUrl";

            var model = new RegisterViewModel {
                Email = "email"
            };

            var generalSettings = new Mock <IOptions <GeneralSettings> >();

            generalSettings.Setup(x => x.Value).Returns(new GeneralSettings());

            var userManager = UserManagerMockHelper.CreateUserManagerMock();

            userManager.Setup(x => x.CreateAsync(It.IsAny <ApplicationUser>(), It.IsAny <string>())).ReturnsAsync(IdentityResult.Success);
            userManager.Setup(x => x.GenerateEmailConfirmationTokenAsync(It.IsAny <ApplicationUser>())).ReturnsAsync(It.IsAny <string>());

            var urlHelper = new Mock <IUrlHelper>();

            urlHelper.Setup(x => x.Action(It.IsAny <UrlActionContext>())).Returns(callbackUrl);

            var mediator = new Mock <IMediator>();

            var sut = new AdminController(userManager.Object, null, mediator.Object, null, generalSettings.Object);

            sut.SetFakeHttpRequestSchemeTo(It.IsAny <string>());
            sut.Url = urlHelper.Object;

            await sut.Register(model);

            mediator.Verify(x => x.SendAsync(It.Is <SendConfirmAccountEmail>(y => y.Email == model.Email && y.CallbackUrl == callbackUrl)));
        }
        public async Task ShowEventReturnsCorrrectViewAndViewModelWhenViewModelIsNotNull()
        {
            const string userId = "1";

            var eventViewModel = new EventViewModel();

            var mediator = new Mock <IMediator>();

            mediator.Setup(x => x.SendAsync(It.IsAny <ShowEventQuery>())).ReturnsAsync(eventViewModel);

            var userManager = UserManagerMockHelper.CreateUserManagerMock();

            userManager.Setup(x => x.GetUserAsync(It.IsAny <ClaimsPrincipal>())).ReturnsAsync(new ApplicationUser {
                Id = userId
            });

            var sut = new EventController(mediator.Object, userManager.Object);

            sut.SetFakeUser(userId);

            var result = await sut.ShowEvent(It.IsAny <int>()) as ViewResult;

            Assert.Equal(eventViewModel, result.Model);
            Assert.Equal("EventWithTasks", result.ViewName);
        }
        public async Task VerifyPhoneNumberPostReturnsTheSameViewAndModelWhenModelStateIsInvalid()
        {
            //Arrange
            var userManagerMock   = UserManagerMockHelper.CreateUserManagerMock();
            var signInManagerMock = SignInManagerMockHelper.CreateSignInManagerMock(userManagerMock);
            var mediator          = new Mock <IMediator>();
            var phoneNumber       = "number";

            mediator.Setup(m => m.SendAsync(It.IsAny <UserByUserIdQuery>())).ReturnsAsync(new ApplicationUser());

            var controller   = new ManageController(userManagerMock.Object, signInManagerMock.Object, mediator.Object);
            var invalidModel = new VerifyPhoneNumberViewModel {
                PhoneNumber = phoneNumber
            };

            controller.ModelState.AddModelError("PhoneNumber", "Must be a number");

            //Act
            var result = await controller.VerifyPhoneNumber(invalidModel);

            var resultViewModel = (ViewResult)result;
            var viewModel       = (VerifyPhoneNumberViewModel)resultViewModel.ViewData.Model;

            //Assert
            Assert.Equal(phoneNumber, viewModel.PhoneNumber);
        }