public async Task <IActionResult> UpdateRoles(string id, [FromBody] UserUpdateRolesModel model) { if (!ModelState.IsValid) { return(BadRequest()); } return(Json(await _manager.UpdateRoles(id, model))); }
public async Task <List <RoleDisplayModel> > UpdateRoles(string id, UserUpdateRolesModel model) { var user = await _repositoryUser.GetFirst(x => x.Id == id && x.State == MREntityState.Active); if (user == null) { _eNotFound("User not found"); } if (!model.Roles.Contains(AppRoles.USER.ToString())) { throw new MRException <object>((int)ExceptionCode.BAD_MODEL, $"{AppRoles.USER.ToString()} role is required"); } var userRoles = await _managerUser.GetRolesAsync(user); var rolesToAdd = model.Roles.Where(x => !userRoles.Contains(x)); var rolesToDelete = userRoles.Where(x => !model.Roles.Contains(x)); if (rolesToAdd.Any()) { await _managerUser.AddToRolesAsync(user, rolesToAdd); } if (rolesToDelete.Any()) { await _managerUser.RemoveFromRolesAsync(user, rolesToDelete); } userRoles = await _managerUser.GetRolesAsync(user); return(userRoles.Select(x => new RoleDisplayModel { Name = x }).ToList()); }