public IActionResult Grant() { var roles = roleService.Roles.ToHashSet(); var profiles = profileService.Users.ToHashSet(); var model = new RoleGrantViewModel() { Roles = roles .Select(r => new SelectListItem() { Text = r.ToString(), Value = r.Name }).OrderBy(i => i.Text), AvailableProfiles = profiles.Where(p => p.UserName != User.Identity.Name && (p.DateDeleted == null || p.DateDeleted.Value.Date > DateTime.Now.Date)) .Select(p => new SelectListItem() { Text = $"{p.UserName} ({p.Email})", Value = p.UserName }).OrderBy(i => i.Text) }; return(View(model)); }
public async Task <IActionResult> Grant(RoleGrantViewModel model) { if (string.IsNullOrWhiteSpace(model.RoleName)) { return(BadRequest(new { Message = string.Format(SelectionNullErrorMessage, "a role") })); } if (model.SelectedProfiles == null || !model.SelectedProfiles.Any()) { return(BadRequest(new { Message = string.Format(SelectionNullErrorMessage, "at least one profile") })); } var infoMessages = new string[0]; int grantsCount = 0; foreach (var username in model.SelectedProfiles) { string message = string.Empty; User profile = await profileService.FindByNameAsync(username); if (await profileService.IsInRoleAsync(profile, model.RoleName)) { message = $"Profile '{username}' already has role '{model.RoleName}'."; } else { var roleGrantResult = await profileService.AddToRoleAsync(profile, model.RoleName); if (!roleGrantResult.Succeeded) { logger.LogError(string.Join(Environment.NewLine, roleGrantResult.Errors.Select(e => e.Description))); return(BadRequest(new { Message = string.Join(HtmlNewLine, roleGrantResult.Errors.Select(e => e.Description)) })); } var roleClaim = new Claim(RoleKey, model.RoleName); await profileService.AddClaimAsync(profile, roleClaim); logger.LogInformation($"'{User.Identity.Name}' granted role '{model.RoleName}' to '{username}'."); message = $"Role '{model.RoleName}' granted to profile '{username}'."; grantsCount++; } infoMessages = infoMessages.Append(message).ToArray(); } if (infoMessages.Length <= ViewMaxStatusMessageLines) { return(Json(new { Message = string.Join(HtmlNewLine, infoMessages) })); } else { string message = $"Role '{model.RoleName}' granted to {grantsCount} profile(s)."; if (infoMessages.Length > grantsCount) { int profilesInRoleCount = infoMessages.Length - grantsCount; message += $"<br />{profilesInRoleCount} profiles already have role '{model.RoleName}'"; } await employeeService.UpdateLastWorkedAsync(User.GetId()); return(Json(new { Message = message })); } }