public async Task <IHttpActionResult> AssignRolesToUser([FromUri] string id, [FromBody] string[] rolesToAssign) { _logger.Debug(string.Format("Begin. Id: [{0}], Roles: [{1}]", id, string.Join(", ", rolesToAssign))); var ndUser = await NdUserManager.FindByIdAsync(id); if (ndUser == null) { _logger.Debug(string.Format("User was not found. Id: [{0}]", id)); return(NotFound()); } var currentRoles = await NdUserManager.GetRolesAsync(ndUser.Id); var rolesNotExists = rolesToAssign.Except(NdRoleManager.Roles.Select(x => x.Name)).ToArray(); if (rolesNotExists.Count() > 0) { ModelState.AddModelError("", string.Format("Roles '{0}' does not exixts in the system", string.Join(",", rolesNotExists))); _logger.Error(string.Format( "Model state is not valid. ModelState: [{0}]", string.Join(Environment.NewLine, ModelState.Select(x => string.Format("{0}: {1}", x.Key, x.Value))))); return(BadRequest(ModelState)); } IdentityResult removeResult = await NdUserManager.RemoveFromRolesAsync(ndUser.Id, currentRoles.ToArray()); if (!removeResult.Succeeded) { ModelState.AddModelError("", "Failed to remove user roles"); _logger.Error(string.Format( "Model state is not valid. ModelState: [{0}]", string.Join(Environment.NewLine, ModelState.Select(x => string.Format("{0}: {1}", x.Key, x.Value))))); return(BadRequest(ModelState)); } IdentityResult addResult = await NdUserManager.AddToRolesAsync(ndUser.Id, rolesToAssign); if (!addResult.Succeeded) { ModelState.AddModelError("", "Failed to add user roles"); _logger.Error(string.Format( "Model state is not valid [ModelState: {0}]", string.Join(Environment.NewLine, ModelState.Select(x => string.Format("{0}: {1}", x.Key, x.Value))))); return(BadRequest(ModelState)); } _logger.Debug(string.Format("User assigned to roles successfully. Id: [{0}], Roles: [{1}]", id, string.Join(", ", rolesToAssign))); return(Ok()); }
public UserReturnDto Create(NdUser ndUser) { return(new UserReturnDto { Url = _UrlHelper.Link("GetUserById", new { id = ndUser.Id }), Id = ndUser.Id, Email = ndUser.Email, Roles = _NdUserManager.GetRolesAsync(ndUser.Id).Result, Clinic = ndUser.Clinic, FirstName = ndUser.FirstName, Gender = ndUser.Gender, LastName = ndUser.LastName, PhoneNumber = ndUser.PhoneNumber, Title = ndUser.Title }); }