1
0
mirror of https://github.com/chylex/Minecraft-Phantom-Panel.git synced 2024-11-22 08:42:44 +01:00
Minecraft-Phantom-Panel/Server/Phantom.Server.Web/Shared/UserRolesDialog.razor

90 lines
2.9 KiB
Plaintext

@using Phantom.Utils.Collections
@using System.Collections.Immutable
@using Microsoft.AspNetCore.Identity
@using Phantom.Server.Services.Audit
@inherits UserEditDialogBase
@inject UserManager<IdentityUser> UserManager
@inject RoleManager<IdentityRole> RoleManager
@inject AuditLog AuditLog
<Modal Id="@ModalId" TitleText="Manage User Roles">
<Body>
Roles for user: <strong class="fw-semibold">@EditedUserName</strong><br>
@for (var index = 0; index < items.Count; index++) {
var item = items[index];
<div class="mt-1">
<input id="role-@index" type="checkbox" class="form-check-input" @bind="@item.Checked" />
<label for="role-@index" class="form-check-label">@item.Name</label>
</div>
}
</Body>
<Footer>
<FormSubmitError Model="SubmitModel" />
<FormButtonSubmit Model="SubmitModel" Label="Save Roles" type="button" class="btn btn-success" @onclick="Submit" />
<button type="button" class="btn btn-secondary" data-bs-dismiss="modal" @onclick="OnClosed">Cancel</button>
</Footer>
</Modal>
@code {
private List<RoleItem> items = new();
protected override async Task BeforeShown(IdentityUser user) {
var userRoles = await GetUserRoles(user);
this.items = RoleManager.Roles
.Select(static role => role.Name)
.AsEnumerable()
.WhereNotNull()
.Select(role => new RoleItem(role, userRoles.Contains(role)))
.ToList();
}
protected override async Task DoEdit(IdentityUser user) {
var userRoles = await GetUserRoles(user);
var addedToRoles = new List<string>();
var removedFromRoles = new List<string>();
var errors = new List<string>();
foreach (var item in items) {
var shouldHaveRole = item.Checked;
var roleName = item.Name;
if (shouldHaveRole == userRoles.Contains(roleName)) {
continue;
}
var result = shouldHaveRole ? await UserManager.AddToRoleAsync(user, roleName) : await UserManager.RemoveFromRoleAsync(user, roleName);
if (result.Succeeded) {
var modifiedList = shouldHaveRole ? addedToRoles : removedFromRoles;
modifiedList.Add(roleName);
}
else {
errors.AddRange(result.Errors.Select(static error => error.Description));
}
}
if (errors.Count == 0) {
await AuditLog.AddUserRolesChangedEvent(user, addedToRoles, removedFromRoles);
await OnEditSuccess();
}
else {
OnEditFailure(string.Join("\n", errors));
}
}
private async Task<ImmutableHashSet<string>> GetUserRoles(IdentityUser user) {
return (await UserManager.GetRolesAsync(user)).ToImmutableHashSet();
}
private sealed class RoleItem {
public string Name { get; }
public bool Checked { get; set; }
public RoleItem(string name, bool @checked) {
this.Name = name;
this.Checked = @checked;
}
}
}