public bool UpdateUserRoles(ViewUserRoles user) { bool rolesUpdated = false; try { IdentityUser identityUser = _userManager.FindByEmailAsync(user.Email).Result; if (identityUser != null) { Dictionary <string, bool> roles = new Dictionary <string, bool>() { { "Admin", user.Admin }, { "User", user.User }, { "Manager", user.Manager } }; foreach (var role in roles) { bool userHasRole = _userManager.IsInRoleAsync(identityUser, role.Key).Result; // Add role if user does not have it if (role.Value == true) { if (userHasRole == false) { var roleResult = _userManager.AddToRoleAsync(identityUser, role.Key).Result; if (!roleResult.Succeeded) { Debug.WriteLine("Error: could not add user to role"); } rolesUpdated = true; } } // Remove role if user has it else if (role.Value == false) { if (userHasRole == true) { var roleResult = _userManager.RemoveFromRoleAsync(identityUser, role.Key).Result; if (!roleResult.Succeeded) { Debug.WriteLine("Error: could not remove user from role"); } rolesUpdated = true; } } } } } catch (Exception err) { Debug.WriteLine($"Error: {err.Message}"); } return(rolesUpdated); }
public IActionResult EditRoles(string email) { IdentityUser user = _userRepository.GetUserByEmail(email); List <string> userRoles = _userRepository.GetRolesByUser(user); ViewUserRoles userWithRoles = new ViewUserRoles() { Name = user.UserName, Email = user.Email, User = userRoles.Contains("User"), Admin = userRoles.Contains("Admin"), Manager = userRoles.Contains("Manager") }; return(View(userWithRoles)); }
public IActionResult UpdateRoles(ViewUserRoles user) { if (ModelState.IsValid) { user.Email = Request.Form["Email"]; user.Admin = Request.Form["Admin"].Contains("true"); user.Manager = Request.Form["Manager"].Contains("true"); user.User = Request.Form["User"].Contains("true"); bool roleAdded = _userRepository.UpdateUserRoles(user); if (roleAdded == true) { Debug.WriteLine("New role added!"); return(RedirectToAction("Index", "User")); } } return(View("EditRoles")); }