public async Task TestChangeUserRoleAsync_WithTestData_ShouldChangeUsersRole() { var testApplicationUser = this.context.Users.FirstOrDefault(); // Take the first user. var testRole = "Admin"; var testApplicationUserServiceModel = this.mapper.Map <ApplicationUserServiceModel>(testApplicationUser); // Act await adminServices.ChangeUserRoleAsync(testApplicationUserServiceModel, testRole); var expectedRole = testRole; var actualRole = context.Users .FirstOrDefault(user => user.UserName == testApplicationUserServiceModel.UserName) .Role; // Assert Assert.Equal(expectedRole, actualRole); }
public async Task <IActionResult> ChangeUserRole(ChangeUserRoleInputModel changeUserRoleInputModel) { // Validate The admin var admin = this.userServices.GetUserByName(changeUserRoleInputModel.Username); var validPassword = await userManager .CheckPasswordAsync(this.mapper.Map <ApplicationUser>(admin), changeUserRoleInputModel.SecretPassword); var user = await userManager.FindByNameAsync(changeUserRoleInputModel.Username); if (ModelState.IsValid && validPassword && user != null) { var userRoles = await this.userManager.GetRolesAsync(user); await userManager.RemoveFromRoleAsync(user, userRoles[0]); if (!await this.roleManager.RoleExistsAsync(changeUserRoleInputModel.RoleName)) { await this.roleManager.CreateAsync(new IdentityRole(changeUserRoleInputModel.RoleName)); } await userManager.AddToRoleAsync(user, changeUserRoleInputModel.RoleName); await adminServices.ChangeUserRoleAsync(this.mapper.Map <ApplicationUserServiceModel>(user), changeUserRoleInputModel.RoleName);; return(RedirectToAction("ShowUserDetails", "AdminUser", new { id = user.Id })); } else { if (user == null) { ModelState.AddModelError("Username", "There is no such user!"); } else if (validPassword == false) { ModelState.AddModelError("Password", "Invalid Passowrd!"); } return(RedirectToAction("ChangeUserRole", "AdminUser", new { userId = user.Id, username = user.UserName, currentRole = user.Role })); } }