public static Model.RolePatchInfo Convert(string userName, Client.RolePatchInfo clientRolePatchInfo) { if (userName == null) { throw new ArgumentNullException(nameof(userName)); } if (clientRolePatchInfo == null) { throw new ArgumentNullException(nameof(clientRolePatchInfo)); } var modelRolePatchInfo = new Model.RolePatchInfo(userName, clientRolePatchInfo.UserRole); return(modelRolePatchInfo); }
public async Task <IActionResult> PatchRoleAsync([FromRoute] string userName, [FromBody] Client.RolePatchInfo clientRolePatchInfo, CancellationToken cancellationToken) { cancellationToken.ThrowIfCancellationRequested(); if (clientRolePatchInfo == null) { var error = ErrorResponsesService.BodyIsMissing(nameof(clientRolePatchInfo)); return(BadRequest(error)); } var user = await userManager.FindByNameAsync(userName); if (user == null) { var error = ErrorResponsesService.NotFoundError(TargetUser, $"User with name '{userName}' not found."); return(NotFound(error)); } var modelRolePatchInfo = Converter.RolePatchInfoConverter.Convert(userName, clientRolePatchInfo); var modelRole = await roleManager.FindByNameAsync(modelRolePatchInfo.UserRole.ToLower()); if (modelRole == null) { var error = ErrorResponsesService.NotFoundError(TargetRole, $"Role with name '{modelRolePatchInfo.UserRole}' not found."); return(NotFound(error)); } if (user.Roles.Contains(modelRolePatchInfo.UserRole.ToUpper())) { await userManager.RemoveFromRoleAsync(user, modelRolePatchInfo.UserRole); } else { await userManager.AddToRoleAsync(user, modelRolePatchInfo.UserRole); } return(Ok(user)); }