public IActionResult EditUser(string userId)
 {
     var user = _dataAccess.GetUser(userId);
     var organizationId = user.GetOrganizationId();
     var viewModel = new EditUserModel()
     {
         UserId = userId,
         UserName = user.UserName,
         AssociatedSkills = user.AssociatedSkills,
         IsOrganizationAdmin = user.IsUserType(UserType.OrgAdmin),
         IsSiteAdmin = user.IsUserType(UserType.SiteAdmin),
         Organization = organizationId != null ? _dataAccess.GetOrganization(organizationId.Value) : null
     };
     return View(viewModel);
 }
 public IActionResult EditUser(string userId)
 {
     var user = _dataAccess.GetUser(userId);
     var tenantId = user.GetTenantId();
     var viewModel = new EditUserModel()
     {
         UserId = userId,
         UserName = user.UserName,
         AssociatedSkills = user.AssociatedSkills,
         IsTenantAdmin = user.IsUserType(UserType.TenantAdmin),
         IsSiteAdmin = user.IsUserType(UserType.SiteAdmin),
         Tenant = tenantId != null ? _dataAccess.GetTenant(tenantId.Value) : null
     };
     return View(viewModel);
 }
        public async Task<IActionResult> EditUser(EditUserModel viewModel)
        {
            if (!ModelState.IsValid)
            {
                return View(viewModel);
            }

            //Skill associations
            var user = _dataAccess.GetUser(viewModel.UserId);
            user.AssociatedSkills.RemoveAll(usk => viewModel.AssociatedSkills == null || !viewModel.AssociatedSkills.Any(msk => msk.SkillId == usk.SkillId));
            if (viewModel.AssociatedSkills != null)
            {
                user.AssociatedSkills.AddRange(viewModel.AssociatedSkills.Where(msk => !user.AssociatedSkills.Any(usk => usk.SkillId == msk.SkillId)));
            }
            if (user.AssociatedSkills != null && user.AssociatedSkills.Count > 0)
            {
                user.AssociatedSkills.ForEach(usk => usk.UserId = user.Id);
            }
            await _dataAccess.UpdateUser(user);

            var tenantAdminClaim = new Claim(Security.ClaimTypes.UserType, "TenantAdmin");
            if (viewModel.IsTenantAdmin)
            {
                //add tenant admin claim
                var result = await _userManager.AddClaimAsync(user, tenantAdminClaim);
                if (result.Succeeded)
                {
                    var callbackUrl = Url.Action("Login", "Admin", new { Email = user.Email }, protocol: HttpContext.Request.Scheme);
                    await _emailSender.SendEmailAsync(user.Email, "Account Approval", "Your account has been approved by an administrator. Please <a href=" + callbackUrl + ">Click here to Log in</a>");
                }
                else
                {
                    return Redirect("Error");
                }
            }
            else if (user.IsUserType(UserType.TenantAdmin))
            {
                //remove tenant admin claim
                var result = await _userManager.RemoveClaimAsync(user, tenantAdminClaim);
                if (!result.Succeeded)
                {
                    return Redirect("Error");
                }
            }

            return RedirectToAction(nameof(Index));
        }
        public IActionResult EditUser(string userId)
        {
            var user = GetUser(userId);
            var organizationId = user.GetOrganizationId();

            var viewModel = new EditUserModel
            {
                UserId = userId,
                UserName = user.UserName,
                AssociatedSkills = user.AssociatedSkills,
                IsOrganizationAdmin = user.IsUserType(UserType.OrgAdmin),
                IsSiteAdmin = user.IsUserType(UserType.SiteAdmin),
                Organization = organizationId != null ? _mediator.Send(new OrganizationByIdQuery { OrganizationId = organizationId.Value }) : null
            };

            return View(viewModel);
        }
        public async Task<IActionResult> EditUser(EditUserModel viewModel)
        {
            if (!ModelState.IsValid)
            {
                return View(viewModel);
            }

            //Skill associations
            var user = GetUser(viewModel.UserId);
            user.AssociatedSkills.RemoveAll(usk => viewModel.AssociatedSkills == null || !viewModel.AssociatedSkills.Any(msk => msk.SkillId == usk.SkillId));

            if (viewModel.AssociatedSkills != null)
            {
                user.AssociatedSkills.AddRange(viewModel.AssociatedSkills.Where(msk => !user.AssociatedSkills.Any(usk => usk.SkillId == msk.SkillId)));
            }

            if (user.AssociatedSkills != null && user.AssociatedSkills.Count > 0)
            {
                user.AssociatedSkills.ForEach(usk => usk.UserId = user.Id);
            }

            await _mediator.SendAsync(new UpdateUser { User = user });

            var organizationAdminClaim = new Claim(Security.ClaimTypes.UserType, "OrgAdmin");
            if (viewModel.IsOrganizationAdmin)
            {
                //add organization admin claim
                var result = await _userManager.AddClaimAsync(user, organizationAdminClaim);
                if (result.Succeeded)
                {
                    //mgmccarthy: there is no Login action method on the AdminController. The only login method I could find is on the AccountController. Not too sure what to do here
                    var callbackUrl = Url.Action(new UrlActionContext { Action = "Login", Controller = "Admin", Values = new { Email = user.Email }, Protocol = HttpContext.Request.Scheme });
                    await _mediator.SendAsync(new SendAccountApprovalEmail { Email = user.Email, CallbackUrl = callbackUrl });
                }
                else
                {
                    return Redirect("Error");
                }
            }
            else if (user.IsUserType(UserType.OrgAdmin))
            {
                //remove organization admin claim
                var result = await _userManager.RemoveClaimAsync(user, organizationAdminClaim);
                if (!result.Succeeded)
                {
                    return Redirect("Error");
                }
            }

            return RedirectToAction(nameof(Index));
        }
        public async Task EditUserPostSendsSendAccountApprovalEmailWithCorrectDataWhenModelsIsOrganizationAdminIsTrueAndOrganizationAdminClaimWasAddedSuccessfully()
        {
            var mediator = new Mock<IMediator>();
            var userManager = CreateApplicationUserMock();
            EditUserModel model = new EditUserModel()
            {
                IsOrganizationAdmin = true,
                UserId = It.IsAny<string>()

            };
            var user = new ApplicationUser()
            {
                Id = model.UserId,
                Email = "*****@*****.**"
            };

            mediator.Setup(x => x.Send(It.Is<UserByUserIdQuery>(q => q.UserId == model.UserId)))
                .Returns(user);
            userManager.Setup(x => x.AddClaimAsync(It.IsAny<ApplicationUser>(), It.IsAny<Claim>()))
                .Returns(() => Task.FromResult(IdentityResult.Success));

            var controller = new SiteController(userManager.Object, null, mediator.Object);
            controller.SetDefaultHttpContext();
            var expectedUrl = String.Format("Login/Admin?Email={0}", user.Email);
            controller.Url = GetMockUrlHelper(expectedUrl);
            await controller.EditUser(model);

            mediator.Verify(m => m.SendAsync(It.Is<SendAccountApprovalEmail>(q => q.Email == user.Email && q.CallbackUrl == expectedUrl ))
                            , Times.Once);
        }
        public async Task EditUserPostInvokesAddClaimAsyncWhenModelsIsOrganizationAdminIsTrue()
        {
            var mediator = new Mock<IMediator>();
            var userManager = CreateApplicationUserMock();
            EditUserModel model = new EditUserModel()
            {
                IsOrganizationAdmin = true,
                UserId = It.IsAny<string>()
                
            };
            var user = new ApplicationUser()
            {
                Id = model.UserId,
                Email = "*****@*****.**"
            };

            mediator.Setup(x => x.Send(It.Is<UserByUserIdQuery>(q => q.UserId == model.UserId)))
                .Returns(user);
            userManager.Setup(x => x.AddClaimAsync(It.IsAny<ApplicationUser>(), It.IsAny<Claim>()))
                .Returns(() => Task.FromResult(IdentityResult.Success));

            var controller = new SiteController(userManager.Object, null, mediator.Object);
            controller.SetDefaultHttpContext();
            controller.Url = GetMockUrlHelper("any");
            await controller.EditUser(model);

            userManager.Verify(x => x.AddClaimAsync(user, It.Is<Claim>(c => c.Value == "OrgAdmin")), Times.Once);
        }
        public async Task EditUserPostInvokesUpdateUserWithCorrectUserWhenUsersAssociatedSkillsAreNotNullAndThereIsAtLeastOneAssociatedSkillForTheUser()
        {
            var mediator = new Mock<IMediator>();
            EditUserModel model = new EditUserModel()
            {
                UserId = It.IsAny<string>(),
                AssociatedSkills = new List<UserSkill>() { new UserSkill() { SkillId = 1, Skill = new Skill() { Id = 1 } } }
            };
            var user = new ApplicationUser()
            {
                Id = model.UserId,
                AssociatedSkills = new List<UserSkill>() { new UserSkill() { SkillId = 2, Skill = new Skill() { Id = 2 } } }
            };
            mediator.Setup(x => x.Send(It.Is<UserByUserIdQuery>(q => q.UserId == model.UserId)))
                .Returns(user);

            var controller = new SiteController(null, null, mediator.Object);

            await controller.EditUser(model);
            mediator.Verify(m => m.SendAsync(It.Is<UpdateUser>(q => q.User.AssociatedSkills[0] == model.AssociatedSkills[0])), Times.Once);
        }
        public async Task EditUserPostSendsUpdateUserWithCorrectUserWhenUsersAssociatedSkillsAreNotNull()
        {
            var mediator = new Mock<IMediator>();
            EditUserModel model = new EditUserModel()
            {
                UserId = It.IsAny<string>(),
                AssociatedSkills = new List<UserSkill>() { new UserSkill() {Skill = It.IsAny<Skill>() } }
            };
            mediator.Setup(x => x.Send(It.Is<UserByUserIdQuery>(q => q.UserId == model.UserId)))
                .Returns(new ApplicationUser());
            var controller = new SiteController(null, null, mediator.Object);

            await controller.EditUser(model);
            mediator.Verify(m => m.SendAsync(It.Is<UpdateUser>(q => q.User.AssociatedSkills[0].Skill == model.AssociatedSkills[0].Skill)), Times.Once);
        }
        public async Task EditUserPostSendsUserByUserIdQueryWithCorrectUserId()
        {
            var mediator = new Mock<IMediator>();
            EditUserModel model = new EditUserModel()
            {
                UserId = "1234",
            };
            mediator.Setup(x => x.Send(It.Is<UserByUserIdQuery>(q => q.UserId == model.UserId)))
                .Returns(new ApplicationUser());
            var controller = new SiteController(null, null, mediator.Object);

            await controller.EditUser(model);
            mediator.Verify(m => m.Send(It.Is<UserByUserIdQuery>(q => q.UserId == model.UserId)), Times.Once);
        }