Adds authorization permissions administrator dashboard

This commit is contained in:
BinaryAlley committed 2024-12-22 19:17:47 +02:00
1 parent 152cb48050
commit 583b8db865
106 files changed
+5916 -2085

No files matched your search

@@ -2,100 +2,231 @@
/admin/manage-permissions/
*@
@using Lumina.Presentation.Web.Common.Models.Authorization
@using Lumina.Presentation.Web.Common.Models.UsersManagement
@using Lumina.Presentation.Web.Common.Services
@using Microsoft.AspNetCore.Mvc.Localization
@using Lumina.Presentation.Web.Common.Models.Authorization
@{
var roles = ViewData["roles"] as RoleModel[];
var rolePermissions = ViewData["rolePermissions"] as PermissionModel[];
}
var users = ViewData["users"] as UserModel[];
var permissions = ViewData["permissions"] as PermissionModel[];
// generate a unique id for the scripts section of this view, so it can be dynamically loaded/unloaded by the global AJAX navigator handler
var scriptId = ScriptIdentifierHelper.GenerateScriptId();
}
@inject IViewLocalizer _localizer
@inject IUrlService _urlService
<form id="rolesPermissionsForm" method="post" action="/Permissions/CreateRole">
<input type="hidden" name="rolesRoleId" id="rolesRoleId" value="" />
<!-- Roles dropdown row -->
<div class="h-30px w-100 text-end">
<label for="rolesRolesDropdown" class="text-light-one">@_localizer["Roles"]</label>
<form id="authorization-permissions-form" method="post" class="w-100 h-100 mx-auto pl-10 pr-10 pt-10 pb-10">
<div id="authorization-permissions-container">
<input type="hidden" name="authorization-users-selected-id" id="authorization-users-selected-id" value="" />
<input type="hidden" name="authorization-roles-selected-id" id="authorization-roles-selected-id" value="" />
<!-- Users dropdown row -->
<div class="h-30px w-100 text-end mb-5">
<label for="authorization-users-combobox" class="text-light-one">@_localizer["Users"]</label>
<div class="enlightenment-combobox w-250px inline-block" id="rolesRolesDropdown">
<div class="shine-effect" style="top: 1px;"></div>
<input type="checkbox" id="rolesRolesDropdownToggle" class="enlightenment-toggle-checkbox" />
<label class="enlightenment-toggle" for="rolesRolesDropdownToggle">
<span class="enlightenment-selected-text">@_localizer["SelectARole"]</span>
</label>
<div class="enlightenment-dropdown">
<div class="shine-effect" style="top: -4px;"></div>
<div class="enlightenment-option first-option disabled">@_localizer["SelectARole"]</div>
@if (roles is not null)
{
@for (int i = 0; i < roles.Length; i++)
<div class="enlightenment-combobox w-250px inline-block" id="authorization-users-combobox">
<div class="shine-effect" style="top: 1px;"></div>
<input type="checkbox" id="authorization-users-combobox-toggle" class="enlightenment-toggle-checkbox" />
<label class="enlightenment-toggle" for="authorization-users-combobox-toggle">
<span class="enlightenment-selected-text">@_localizer["SelectAUser"]</span>
</label>
<div class="enlightenment-dropdown" id="authorization-users-combobox-dropdown">
<div class="shine-effect" style="top: -4px;"></div>
<div class="enlightenment-option first-option disabled">@_localizer["SelectAUser"]</div>
@if (users is not null)
{
<div class="enlightenment-option @(i == roles.Length - 1 ? "last-option" : "")" data-value="@roles[i].Id">@roles[i].RoleName</div>
}
}
</div>
</div>
</div>
<!-- Role name input row -->
<div class="h-30px w-100 text-end mb-5">
<label for="rolesRoleInput" class="text-light-one">@_localizer["RoleName"]</label>
<input type="text" id="rolesRoleInput" name="roleName" class="enlightenment-input w-250px" />
</div>
<!-- Permissions row -->
<div class="containerRoles row panel inset">
<div class="explorerContainer">
<div class="explorer">
@if (rolePermissions is not null)
{
@foreach (var rolePermission in rolePermissions)
{
<div class="e no-border transparent">
<label class="enlightenment-checkbox-label">
<input type="checkbox" class="enlightenment-checkbox-hidden" name="rolePermissions" value="@rolePermission.Id">
<span class="enlightenment-checkbox"></span>
@_localizer[rolePermission.PermissionName.ToString()]
</label>
</div>
}
}
</div>
</div>
</div>
<!-- Submit Button Row -->
<div class="w-100 text-end">
<button type="button" class="abort-button f-14 h-24px v-align-t hidden" id="rolesDeleteRoleBtn">@_localizer["DeleteRole"]</button>
<button type="submit" class="confirm-button f-14 h-24px v-align-t" id="rolesConfirmBtn">@_localizer["CreateRole"]</button>
</div>
</form>
@* <div class="enlightenment-panel shadow-effect p-2 mx-auto panel w-90 mb-10" style="min-width: 320px; margin-top: 1rem;">
<div class="shine-effect"></div>
<form method="post" id="add-media-library-form" class="inline">
@Html.AntiForgeryToken()
@{
<div class="form-field">
<div class="enlightenment-combobox inline-block w-100">
<div class="shine-effect" style="top: 1px;"></div>
<input type="checkbox" class="enlightenment-toggle-checkbox" id="library-type" />
<label class="enlightenment-toggle" for="library-type">
<span id="library-selected-item" class="enlightenment-selected-text" data-value="None">@_localizer["None"]</span>
</label>
<div class="enlightenment-dropdown">
<div class="shine-effect" style="top: -4px;"></div>
<div class="enlightenment-option first-option disabled">@_localizer["None"]</div>
@foreach (var item in aa!)
@for (int i = 0; i < users.Length; i++)
{
<div class="enlightenment-option">@_localizer[item.ToString()]</div>
<div class="enlightenment-option @(i == users.Length - 1 ? "last-option" : "")" data-value="@users[i].Id">@users[i].Username</div>
}
}
</div>
</div>
</div>
<!-- Roles dropdown row -->
<div class="h-30px w-100 text-end mb-5">
<label for="authorization-roles-combobox" class="text-light-one">@_localizer["Roles"]</label>
<div class="enlightenment-combobox w-250px inline-block" id="authorization-roles-combobox">
<div class="shine-effect" style="top: 1px;"></div>
<input type="checkbox" id="authorization-roles-combobox-toggle" class="enlightenment-toggle-checkbox" />
<label class="enlightenment-toggle" for="authorization-roles-combobox-toggle">
<span class="enlightenment-selected-text">@_localizer["SelectARole"]</span>
</label>
<div class="enlightenment-dropdown" id="authorization-roles-combobox-dropdown">
<div class="shine-effect" style="top: -4px;"></div>
<div class="enlightenment-option first-option disabled">@_localizer["SelectARole"]</div>
@if (roles is not null)
{
@for (int i = 0; i < roles.Length; i++)
{
<div class="enlightenment-option @(i == roles.Length - 1 ? "last-option" : "")" data-value="@roles[i].Id">@roles[i].RoleName</div>
}
}
</div>
</div>
</div>
<!-- Permissions row -->
<div id="authorization-permissions-permissions-container" class="">
<div id="authorization-permissions-permissions">
<div id="authorization-permissions-permissions-scroll" class="scroll-horizontal">
<div id="authorization-permissions-permissions-list" class="list" style="flex-direction: column;">
@if (permissions is not null)
{
@foreach (var permission in permissions)
{
<div class="e no-border transparent mt-5 mb-5">
<label class="enlightenment-checkbox-label">
<input type="checkbox" class="enlightenment-checkbox-hidden" name="authorization-permissions-permissions" value="@permission.Id">
<span class="enlightenment-checkbox"></span>
@_localizer[permission.PermissionName.ToString()]
</label>
</div>
}
}
</div>
</div>
</div>
}
<p>a</p>
</div>
</form>
</div> *@
<!-- Submit Button Row -->
<div class="w-100 h-25px mt-5 text-end">
<button id="btn-update-user" type="submit" class="confirm-button f-14 h-24px v-align-t" disabled>@_localizer["Update"]</button>
</div>
</div>
</form>
@section Scripts {
<script type="text/javascript" data-form="@scriptId" defer>
// create cleanup registry for this view
const cleanupFunctions = [];
const btnUpdateUser = document.getElementById('btn-update-user');
const form = document.getElementById('authorization-permissions-form');
const rolesDropdown = document.getElementById('authorization-roles-combobox-dropdown');
const usersDropdown = document.getElementById('authorization-users-combobox-dropdown');
const roleIdInput = document.getElementById('authorization-roles-selected-id');
const userIdInput = document.getElementById('authorization-users-selected-id');
// update user permissions and role
async function handleUserAuthorizationSubmitAsync() {
const formData = {
userId: userIdInput.value,
roleId: roleIdInput.value !== '' ? roleIdInput.value : null,
permissions: Array.from(form.querySelectorAll("input[name='authorization-permissions-permissions']:checked"))
.map(checkbox => checkbox.value)
};
const data = await callApiPutAsync('@_urlService.GetAbsoluteUrl("UpdateUserAuthorization", "Admin")', formData);
if (data)
notificationService.show('@_localizer["UserAuthorizationUpdated"]', NotificationType.SUCCESS);
}
async function fetchUserRoleAsync(userId) {
const url = '@_urlService.GetAbsoluteUrl("GetRoleByUserId", "Admin", new { userId = default(Guid) })';
const data = await callApiGetAsync(url.replace('/@(default(Guid))', `/${userId}`)); // userId needs to be replaced here, because GetAbsoluteUrl is server side, userId is client side
if (data) {
var roleElement = document.querySelector('#authorization-roles-combobox .enlightenment-option[data-value="' + data.id + '"]');
var roleName = roleElement.textContent;
document.querySelector('#authorization-roles-combobox .enlightenment-selected-text').textContent = roleName;
document.querySelector('#authorization-roles-combobox .enlightenment-toggle').dataset.value = data.id;
roleIdInput.value = data.id;
}
}
async function fetchUserPermissionsAsync(userId) {
const url = '@_urlService.GetAbsoluteUrl("GetPermissionsByUserId", "Admin", new { userId = default(Guid) })';
const data = await callApiGetAsync(url.replace('/@(default(Guid))', `/${userId}`)); // userId needs to be replaced here, because GetAbsoluteUrl is server side, userId is client side
if (data) {
// clear all checkboxes
document.querySelectorAll("input[name='authorization-permissions-permissions']")
.forEach(input => input.checked = false);
// check the checkboxes for which permissions are assigned
data.forEach(p => {
const checkbox = document.querySelector(`input[name='authorization-permissions-permissions'][value='${p.id}']`);
if (checkbox)
checkbox.checked = true;
});
}
}
// on Enter key pressed
const handleEnterKey = async function(e) {
if (e.key === 'Enter') {
e.preventDefault();
await handleUserAuthorizationSubmitAsync();
}
};
// on form submit event
const handleSubmit = async function(e) {
e.preventDefault();
await handleUserAuthorizationSubmitAsync();
};
// on document click
const handleDocumentClick = async function(e) {
// users dropdown change
if (e.target.closest('#authorization-users-combobox .enlightenment-option')) {
var selectedUserId = e.target.dataset.value;
document.querySelector('#authorization-roles-combobox .enlightenment-selected-text').textContent = '@_localizer["SelectARole"]';
document.querySelectorAll("input[name='authorization-permissions-permissions']").forEach(input => input.checked = false);
roleIdInput.value = '';
userIdInput.value = '';
if (selectedUserId) {
userIdInput.value = selectedUserId;
btnUpdateUser.disabled = false;
await fetchUserRoleAsync(selectedUserId);
await fetchUserPermissionsAsync(selectedUserId);
}
else
btnUpdateUser.disabled = true;
}
// roles dropdown change
else if (e.target.closest('#authorization-roles-combobox .enlightenment-option')) {
const roleId = e.target.dataset.value;
roleIdInput.value = roleId || '';
}
};
// add listeners
form.addEventListener('keypress', handleEnterKey);
form.addEventListener('submit', handleSubmit);
document.addEventListener('click', handleDocumentClick);
// register cleanup for these listeners
cleanupFunctions.push(() => {
form.removeEventListener('keypress', handleEnterKey);
form.removeEventListener('submit', handleSubmit);
document.removeEventListener('click', handleDocumentClick);
});
// when form's height changes, adjust the roles combobox dropdown maximum height accordingly, so it doesn't cause an <article> section overflow
const resizeObserver = new ResizeObserver(entries => {
const formHeight = form.getBoundingClientRect().height;
usersDropdown.style.maxHeight = `calc(${formHeight}px - 50px)`;
rolesDropdown.style.maxHeight = `calc(${formHeight}px - 90px)`;
usersDropdown.style.overflowY = `auto`;
rolesDropdown.style.overflowY = `auto`;
});
resizeObserver.observe(form);
// register cleanup for observer
cleanupFunctions.push(() => {
resizeObserver.disconnect();
});
// store all cleanups for this view on window object using the scriptId
window.viewCleanups = window.viewCleanups || {};
window.viewCleanups['@scriptId'] = () => {
cleanupFunctions.forEach(cleanup => cleanup());
console.log(`Unloaded @scriptId`);
};
console.log(`Loaded @scriptId`);
</script>
}
@@ -1 +1,46 @@

#authorization-permissions-container {
display: flex;
margin: auto;
width: 100%;
height: 100%;
flex-direction: column;
flex-wrap: nowrap;
}
#authorization-permissions-permissions-container {
flex-grow: 1;
min-width: 135px;
min-height: 0px;
}
#authorization-permissions-permissions {
border: 1px solid var(--border-color-light-high);
border-top: 1px solid var(--border-color-dark);
border-left: 1px solid var(--border-color-dark);
margin: auto;
padding-left: 5px;
width: 100%;
height: 100%;
display: flex;
flex-direction: row;
flex-wrap: nowrap;
justify-content: left;
align-items: stretch;
}
#authorization-permissions-permissions-scroll {
background-color: #232323;
margin: auto;
width: 100%;
height: 100%;
}
#authorization-permissions-permissions-list {
margin: 1px;
display: flex;
flex-direction: column;
flex-wrap: wrap;
border: 0px solid black;
padding: 0px;
gap: 0px 10px;
}
@@ -8,7 +8,7 @@
@{
var roles = ViewData["roles"] as RoleModel[];
var rolePermissions = ViewData["rolePermissions"] as PermissionModel[];
var permissions = ViewData["permissions"] as PermissionModel[];
// generate a unique id for the scripts section of this view, so it can be dynamically loaded/unloaded by the global AJAX navigator handler
var scriptId = ScriptIdentifierHelper.GenerateScriptId();
}
@@ -54,15 +54,15 @@
<div id="authorization-roles-permissions">
<div id="authorization-roles-permissions-scroll" class="scroll-horizontal">
<div id="authorization-roles-permissions-list" class="list" style="flex-direction: column;">
@if (rolePermissions is not null)
@if (permissions is not null)
{
@foreach (var rolePermission in rolePermissions)
@foreach (var permission in permissions)
{
<div class="e no-border transparent mt-5 mb-5">
<label class="enlightenment-checkbox-label">
<input type="checkbox" class="enlightenment-checkbox-hidden" name="authorization-role-permissions" value="@rolePermission.Id">
<input type="checkbox" class="enlightenment-checkbox-hidden" name="authorization-role-permissions" value="@permission.Id">
<span class="enlightenment-checkbox"></span>
@_localizer[rolePermission.PermissionName.ToString()]
@_localizer[permission.PermissionName.ToString()]
</label>
</div>
}
@@ -82,28 +82,20 @@
@section Scripts {
<script type="text/javascript" data-form="@scriptId" defer>
// create cleanup registry for this view
const cleanupFunctions = [];
const btnDeleteRole = document.getElementById('btn-delete-role');
const btnConfirmRole = document.getElementById('btn-confirm-role');
const txtRoleName = document.getElementById('txt-role-name');
const form = document.getElementById('authorization-roles-form');
const dropdown = document.getElementById('authorization-roles-combobox-dropdown')
// on Enter key pressed
form.addEventListener('keypress', async (e) => {
if (e.key === 'Enter') {
e.preventDefault();
await handleRoleSubmit(e.target.closest('form'));
}
});
// on form submit event
form.addEventListener('submit', async (e) => {
e.preventDefault();
await handleRoleSubmit(e.target);
});
const dropdown = document.getElementById('authorization-roles-combobox-dropdown');
const roleIdInput = document.getElementById('authorization-roles-selected-id');
// create new or update existing role
async function handleRoleSubmit(form) {
async function handleRoleSubmitAsync() {
const formData = {
roleId: document.getElementById('authorization-roles-selected-id').value,
roleId: roleIdInput.value,
roleName: txtRoleName.value,
permissions: Array.from(form.querySelectorAll("input[name='authorization-role-permissions']:checked"))
.map(checkbox => checkbox.value)
@@ -111,57 +103,17 @@
const isRoleSelected = formData.roleId !== '';
const data = isRoleSelected ?
await callApiPutAsync('@_urlService.GetAbsoluteUrl("UpdateRole", "Admin")', formData) :
await callApiPostAsync('@_urlService.GetAbsoluteUrl("CreateRole", "Admin")', formData);
const data = isRoleSelected ?
await callApiPutAsync('@_urlService.GetAbsoluteUrl("UpdateRole", "Admin")', formData) :
await callApiPostAsync('@_urlService.GetAbsoluteUrl("CreateRole", "Admin")', formData);
if (data) {
await fetchRoles();
await fetchRolesAsync();
notificationService.show(isRoleSelected ? '@_localizer["RoleUpdated"]' : '@_localizer["RoleCreated"]', NotificationType.SUCCESS);
}
}
btnDeleteRole.addEventListener('click', async function(e) {
const roleId = document.getElementById('authorization-roles-selected-id').value;
// ask the user for confirmation before deleting the role
if (await dialogService.show('@_localizer["DeleteRoleConfirm"]', jsLocalizedDialogs.confirmation, DialogButtons.YES_NO_CANCEL, DialogIcon.QUESTION) === DialogButton.YES) {
const url = '@_urlService.GetAbsoluteUrl("DeleteRole", "Admin", new { roleId = default(Guid) })';
const success = await callApiDeleteAsync(url.replace('/@(default(Guid))', `/${roleId}`)); // roleId needs to be replaced here, because GetAbsoluteUrl is server side, roleId is client side
if (success) {
await fetchRoles();
notificationService.show('@_localizer["RoleDeleted"]', NotificationType.SUCCESS);
}
}
});
// on role dropdown change
document.addEventListener('click', function(e) {
if (e.target.classList.contains('enlightenment-option')) {
const roleId = e.target.dataset.value;
const selectedText = e.target.textContent;
const txtRoleName = document.getElementById('txt-role-name');
txtRoleName.value = roleId ? selectedText : '';
fetchRolePermissions(roleId);
const roleIdInput = document.getElementById('authorization-roles-selected-id');
if (roleId) {
btnDeleteRole.classList.remove('hidden');
btnDeleteRole.classList.add('inline');
btnConfirmRole.textContent = '@_localizer["UpdateRole"]';
roleIdInput.value = roleId;
} else {
roleIdInput.value = '';
btnDeleteRole.classList.remove('inline');
btnDeleteRole.classList.add('hidden');
btnConfirmRole.textContent = '@_localizer["CreateRole"]';
}
}
});
async function fetchRoles() {
const url = '@_urlService.GetAbsoluteUrl("GetRoles", "Admin")';
const data = await callApiGetAsync(url);
async function fetchRolesAsync() {
const data = await callApiGetAsync('@_urlService.GetAbsoluteUrl("GetRoles", "Admin")');
if (data) {
// clear the roles drop down list
const rolesDropdown = document.querySelector("#authorization-roles-combobox .enlightenment-dropdown");
@@ -198,7 +150,7 @@
}
}
async function fetchRolePermissions(roleId) {
async function fetchRolePermissionsAsync(roleId) {
if (roleId) {
const url = '@_urlService.GetAbsoluteUrl("GetPermissionsByRoleId", "Admin", new { roleId = default(Guid) })';
const data = await callApiGetAsync(url.replace('/@(default(Guid))', `/${roleId}`)); // roleId needs to be replaced here, because GetAbsoluteUrl is server side, roleId is client side
@@ -221,6 +173,72 @@
.forEach(input => input.checked = false);
}
}
// on Enter key pressed
const handleEnterKey = async function(e) {
if (e.key === 'Enter') {
e.preventDefault();
await handleRoleSubmitAsync();
}
};
// on form submit event
const handleSubmit = async function(e) {
e.preventDefault();
await handleRoleSubmitAsync();
};
// on delete role button click
const handleBtnDeleteRoleClick = async function(e) {
// ask the user for confirmation before deleting the role
if (await dialogService.show('@_localizer["DeleteRoleConfirm"]', jsLocalizedDialogs.confirmation, DialogButtons.YES_NO, DialogIcon.QUESTION) === DialogButton.YES) {
const url = '@_urlService.GetAbsoluteUrl("DeleteRole", "Admin", new { roleId = default(Guid) })';
const success = await callApiDeleteAsync(url.replace('/@(default(Guid))', `/${roleIdInput.value}`)); // roleId needs to be replaced here, because GetAbsoluteUrl is server side, roleId is client side
if (success) {
await fetchRolesAsync();
notificationService.show('@_localizer["RoleDeleted"]', NotificationType.SUCCESS);
}
}
};
// on document click
const handleDocumentClick = async function(e) {
// roles dropdown change
if (e.target.closest('#authorization-roles-combobox .enlightenment-option')) {
const roleId = e.target.dataset.value;
const selectedText = e.target.textContent;
txtRoleName.value = roleId ? selectedText : '';
await fetchRolePermissionsAsync(roleId);
if (roleId) {
btnDeleteRole.classList.remove('hidden');
btnDeleteRole.classList.add('inline');
btnConfirmRole.textContent = '@_localizer["UpdateRole"]';
roleIdInput.value = roleId;
} else {
roleIdInput.value = '';
btnDeleteRole.classList.remove('inline');
btnDeleteRole.classList.add('hidden');
btnConfirmRole.textContent = '@_localizer["CreateRole"]';
}
}
};
// add listeners
form.addEventListener('keypress', handleEnterKey);
form.addEventListener('submit', handleSubmit);
btnDeleteRole.addEventListener('click', handleBtnDeleteRoleClick);
document.addEventListener('click', handleDocumentClick);
// register cleanup for these listeners
cleanupFunctions.push(() => {
form.removeEventListener('keypress', handleEnterKey);
form.removeEventListener('submit', handleSubmit);
btnDeleteRole.removeEventListener('click', handleBtnDeleteRoleClick);
document.removeEventListener('click', handleDocumentClick);
});
// when form's height changes, adjust the roles combobox dropdown maximum height accordingly, so it doesn't cause an <article> section overflow
const resizeObserver = new ResizeObserver(entries => {
const formHeight = form.getBoundingClientRect().height;
@@ -228,5 +246,18 @@
dropdown.style.overflowY = `auto`;
});
resizeObserver.observe(form);
// register cleanup for observer
cleanupFunctions.push(() => {
resizeObserver.disconnect();
});
// store all cleanups for this view on window object using the scriptId
window.viewCleanups = window.viewCleanups || {};
window.viewCleanups['@scriptId'] = () => {
cleanupFunctions.forEach(cleanup => cleanup());
console.log(`Unloaded @scriptId`);
};
console.log(`Loaded @scriptId`);
</script>
}
@@ -70,30 +70,22 @@
</div>
@section Scripts {
<script type="text/javascript" data-form="@scriptId" defer>
document.getElementById('change-password-form').addEventListener('keypress', async (e) => {
if (e.key === 'Enter') {
e.preventDefault();
const form = e.target.closest('form');
await handleChangePassword(form);
}
});
// create cleanup registry for this view
const cleanupFunctions = [];
document.getElementById('change-password-form').addEventListener('submit', async (e) => {
e.preventDefault();
await handleChangePassword(e.target);
});
const form = document.getElementById('change-password-form');
const txtCurrentPassword = form.querySelector('[name="CurrentPassword"]');
const txtNewPassword = form.querySelector('[name="NewPassword"]');
const txtNewPasswordConfirm = form.querySelector('[name="NewPasswordConfirm"]');
async function handleChangePassword(form) {
const txtCurrentPassword = form.querySelector('[name="CurrentPassword"]');
const txtNewPassword = form.querySelector('[name="NewPassword"]');
const txtNewPasswordConfirm = form.querySelector('[name="NewPasswordConfirm"]');
const changePasswordSuccess = document.getElementById('change-password-success');
const divCurrentPassword = document.getElementById('div-current-password');
const divNewPassword = document.getElementById('div-new-password');
const divNewPasswordConfirm = document.getElementById('div-new-password-confirm');
const divChangePasswordSubmit = document.getElementById('div-change-password-submit');
const changePasswordSuccess = document.getElementById('change-password-success');
const divCurrentPassword = document.getElementById('div-current-password');
const divNewPassword = document.getElementById('div-new-password');
const divNewPasswordConfirm = document.getElementById('div-new-password-confirm');
const divChangePasswordSubmit = document.getElementById('div-change-password-submit');
// perform the password change
async function handleChangePasswordAsync() {
const formData = {
CurrentPassword: txtCurrentPassword.value,
NewPassword: txtNewPassword.value,
@@ -108,5 +100,37 @@
divChangePasswordSubmit.classList.add('hidden');
}
}
// on Enter key pressed
const handleEnterKey = async function(e) {
if (e.key === 'Enter') {
e.preventDefault();
await handleChangePasswordAsync();
}
};
// on form submit event
const handleSubmit = async function(e) {
e.preventDefault();
await handleChangePasswordAsync();
};
// add listeners
form.addEventListener('keypress', handleEnterKey);
form.addEventListener('submit', handleSubmit);
// register cleanup for these listeners
cleanupFunctions.push(() => {
form.removeEventListener('keypress', handleEnterKey);
form.removeEventListener('submit', handleSubmit);
});
// store all cleanups for this view on window object using the scriptId
window.viewCleanups = window.viewCleanups || {};
window.viewCleanups['@scriptId'] = () => {
cleanupFunctions.forEach(cleanup => cleanup());
console.log(`Unloaded @scriptId`);
};
console.log(`Loaded @scriptId`);
</script>
}
@@ -64,28 +64,21 @@
</div>
@section Scripts {
<script type="text/javascript" data-form="@scriptId" defer>
document.getElementById('login-form').addEventListener('keypress', async (e) => {
if (e.key === 'Enter') {
e.preventDefault();
const form = e.target.closest('form');
await handleLogin(form);
}
});
// create cleanup registry for this view
const cleanupFunctions = [];
document.getElementById('login-form').addEventListener('submit', async (e) => {
e.preventDefault();
await handleLogin(e.target);
});
async function handleLogin(form) {
const returnUrlInput = form.querySelector('[name="ReturnUrl"]');
const txtUsername = form.querySelector('[name="Username"]');
const txtPassword = form.querySelector('[name="Password"]');
const txtTotpCode = form.querySelector('[name="TotpCode"]');
const divTotpCode = document.getElementById('div-totp-code');
const btnLogin = document.getElementById('btn-login');
const btnRecoverPassword = document.getElementById('btn-recover-password');
const btnValidateTotp = document.getElementById('btn-validate-totp');
const form = document.getElementById('login-form');
const returnUrlInput = form.querySelector('[name="ReturnUrl"]');
const txtUsername = form.querySelector('[name="Username"]');
const txtPassword = form.querySelector('[name="Password"]');
const txtTotpCode = form.querySelector('[name="TotpCode"]');
const divTotpCode = document.getElementById('div-totp-code');
const btnLogin = document.getElementById('btn-login');
const btnRecoverPassword = document.getElementById('btn-recover-password');
const btnValidateTotp = document.getElementById('btn-validate-totp');
// perform the authentication
async function handleLoginAsync() {
const formData = {
Username: txtUsername.value,
Password: txtPassword.value,
@@ -105,8 +98,44 @@
else if (data)
window.location.href = data;
}
document.getElementById('btn-recover-password').addEventListener('click', () => {
// on Enter key pressed
const handleEnterKey = async function(e) {
if (e.key === 'Enter') {
e.preventDefault();
await handleLoginAsync();
}
};
// on form submit event
const handleSubmit = async function(e) {
e.preventDefault();
await handleLoginAsync();
};
// on recover password button click
const handleBtnRecoverPasswordClick = function() {
window.location.href = '@_urlService.GetAbsoluteUrl("RecoverPassword", "Auth")';
};
// add listeners
form.addEventListener('keypress', handleEnterKey);
form.addEventListener('submit', handleSubmit);
btnRecoverPassword.addEventListener('click', handleBtnRecoverPasswordClick);
// register cleanup for these listeners
cleanupFunctions.push(() => {
form.removeEventListener('keypress', handleEnterKey);
form.removeEventListener('submit', handleSubmit);
btnRecoverPassword.removeEventListener('click', handleBtnRecoverPasswordClick);
});
// store all cleanups for this view on window object using the scriptId
window.viewCleanups = window.viewCleanups || {};
window.viewCleanups['@scriptId'] = () => {
cleanupFunctions.forEach(cleanup => cleanup());
console.log(`Unloaded @scriptId`);
};
console.log(`Loaded @scriptId`);
</script>
}
@@ -58,29 +58,21 @@
</div>
@section Scripts {
<script type="text/javascript" data-form="@scriptId" defer>
document.getElementById('recover-password-form').addEventListener('keypress', async (e) => {
if (e.key === 'Enter') {
e.preventDefault();
const form = e.target.closest('form');
await handleRecoverPassword(form);
}
});
// create cleanup registry for this view
const cleanupFunctions = [];
document.getElementById('recover-password-form').addEventListener('submit', async (e) => {
e.preventDefault();
await handleRecoverPassword(e.target);
});
async function handleRecoverPassword(form) {
const txtUsername = form.querySelector('[name="Username"]');
const txtTotpCode = form.querySelector('[name="TotpCode"]');
const recoverPasswordSuccess = document.getElementById('recover-password-success');
const btnRedirectLogin = document.getElementById('btn-redirect-login');
const btnLogin = document.getElementById('btn-login');
const btnValidateTotp = document.getElementById('btn-validate-totp');
const divUsername = document.getElementById('div-username');
const divTotpCode = document.getElementById('div-totp-code');
const form = document.getElementById('recover-password-form');
const txtUsername = form.querySelector('[name="Username"]');
const txtTotpCode = form.querySelector('[name="TotpCode"]');
const recoverPasswordSuccess = document.getElementById('recover-password-success');
const btnRedirectLogin = document.getElementById('btn-redirect-login');
const btnLogin = document.getElementById('btn-login');
const btnValidateTotp = document.getElementById('btn-validate-totp');
const divUsername = document.getElementById('div-username');
const divTotpCode = document.getElementById('div-totp-code');
// perform the password recovery
async function handleRecoverPasswordAsync() {
const formData = {
Username: txtUsername.value,
TotpCode: txtTotpCode.value
@@ -95,11 +87,51 @@
recoverPasswordSuccess.classList.replace('hidden', 'block');
}
}
document.getElementById('btn-login').addEventListener('click', () => {
// on Enter key pressed
const handleEnterKey = async function(e) {
if (e.key === 'Enter') {
e.preventDefault();
await handleRecoverPasswordAsync();
}
};
// on form submit event
const handleSubmit = async function(e) {
e.preventDefault();
await handleRecoverPasswordAsync();
};
// on login button click
const handleBtnLoginClick = function() {
window.location.href = '@_urlService.GetAbsoluteUrl("Login", "Auth")';
});
document.getElementById('btn-redirect-login').addEventListener('click', () => {
};
// on login redirect button click
const handleBtnRedirectLoginClick = function() {
window.location.href = '@_urlService.GetAbsoluteUrl("Login", "Auth")';
};
// add listeners
form.addEventListener('keypress', handleEnterKey);
form.addEventListener('submit', handleSubmit);
btnLogin.addEventListener('click', handleBtnLoginClick);
btnRedirectLogin.addEventListener('click', handleBtnRedirectLoginClick);
// register cleanup for these listeners
cleanupFunctions.push(() => {
form.removeEventListener('keypress', handleEnterKey);
form.removeEventListener('submit', handleSubmit);
btnLogin.removeEventListener('click', handleBtnLoginClick);
btnRedirectLogin.removeEventListener('click', handleBtnRedirectLoginClick);
});
// store all cleanups for this view on window object using the scriptId
window.viewCleanups = window.viewCleanups || {};
window.viewCleanups['@scriptId'] = () => {
cleanupFunctions.forEach(cleanup => cleanup());
console.log(`Unloaded @scriptId`);
};
console.log(`Loaded @scriptId`);
</script>
}
@@ -99,28 +99,23 @@
</div>
@section Scripts {
<script type="text/javascript" data-form="@scriptId" defer>
// create cleanup registry for this view
const cleanupFunctions = [];
const form = document.getElementById('register-account-form');
const txtUsername = form.querySelector('[name="Username"]');
const txtPassword = form.querySelector('[name="Password"]');
const txtPasswordConfirm = form.querySelector('[name="PasswordConfirm"]');
const chkUse2FA = form.querySelector('[name="Use2fa"]');
const registerSuccess = document.getElementById('register-success');
const totpMessage = document.querySelector('#totp-message');
const totpImage = document.querySelector('#totp-image');
const btnLogin = document.getElementById('btn-login');
document.getElementById('register-account-form').addEventListener('keypress', async (e) => {
if (e.key === 'Enter') {
e.preventDefault();
const form = e.target.closest('form');
await handleRegisterAccount(form);
}
});
const spnTwoFaAttention = document.getElementById('register-two-fa-attention');
const useTwoFaInput = document.getElementById('hidden-use-two-fa');
document.getElementById('register-account-form').addEventListener('submit', async (e) => {
e.preventDefault();
await handleRegisterAccount(e.target);
});
async function handleRegisterAccount(form) {
const txtUsername = form.querySelector('[name="Username"]');
const txtPassword = form.querySelector('[name="Password"]');
const txtPasswordConfirm = form.querySelector('[name="PasswordConfirm"]');
const chkUse2FA = form.querySelector('[name="Use2fa"]');
const registerSuccess = document.getElementById('register-success');
const totpMessage = document.querySelector('#totp-message');
const totpImage = document.querySelector('#totp-image');
// perform the account registration
async function handleRegisterAccountAsync() {
const formData = {
Username: txtUsername.value,
Password: txtPassword.value,
@@ -147,18 +142,56 @@
}
}
}
document.querySelector('[name="Use2fa"]').addEventListener('change', function () {
// on Enter key pressed
const handleEnterKey = async function(e) {
if (e.key === 'Enter') {
e.preventDefault();
await handleRegisterAccountAsync();
}
};
// on form submit event
const handleSubmit = async function(e) {
e.preventDefault();
await handleRegisterAccountAsync();
};
// on use 2FA change event
const handleChkUse2FAChange = function() {
const isChecked = this.checked;
document.getElementById('register-two-fa-attention').classList.replace(
spnTwoFaAttention.classList.replace(
isChecked ? 'inline' : 'hidden',
isChecked ? 'hidden' : 'inline'
);
document.getElementById('hidden-use-two-fa').value = isChecked.toString();
useTwoFaInput.value = isChecked.toString();
};
// on login button click
const handleBtnLoginClick = function() {
window.location.href = '@_urlService.GetAbsoluteUrl("Login", "Auth")';
};
// add listeners
form.addEventListener('keypress', handleEnterKey);
form.addEventListener('submit', handleSubmit);
chkUse2FA.addEventListener('click', handleChkUse2FAChange);
btnLogin.addEventListener('click', handleBtnLoginClick);
// register cleanup for these listeners
cleanupFunctions.push(() => {
form.removeEventListener('keypress', handleEnterKey);
form.removeEventListener('submit', handleSubmit);
chkUse2FA.removeEventListener('click', handleChkUse2FAChange);
btnLogin.removeEventListener('click', handleBtnLoginClick);
});
if (btnLogin) {
btnLogin.addEventListener('click', () => {
window.location.href = '@_urlService.GetAbsoluteUrl("Login", "Auth")';
});
}
// store all cleanups for this view on window object using the scriptId
window.viewCleanups = window.viewCleanups || {};
window.viewCleanups['@scriptId'] = () => {
cleanupFunctions.forEach(cleanup => cleanup());
console.log(`Unloaded @scriptId`);
};
console.log(`Loaded @scriptId`);
</script>
}
@@ -138,24 +138,18 @@
</div>
@section Scripts {
<script type="text/javascript" data-form="@scriptId" defer>
// create cleanup registry for this view
const cleanupFunctions = [];
const saveSuccess = document.getElementById('save-success');
const btnBackToLibraries = document.getElementById('btn-back-to-libraries');
const btnAddNewLibrary = document.getElementById('btn-add-new-library');
const form = document.getElementById('add-media-library-form');
const imgAddMediaDirectory = document.getElementById('add-media-directory');
const formTable = document.querySelector('.form-table');
form.addEventListener('keypress', async (e) => {
if (e.key === 'Enter') {
e.preventDefault();
await handleAddMediaLibrary(e.target.closest('form'));
}
});
form.addEventListener('submit', async (e) => {
e.preventDefault();
await handleAddMediaLibrary(e.target);
});
async function handleAddMediaLibrary(form) {
// create new or update existing media library
async function handleAddMediaLibraryAsync() {
const formData = {
Id: form.querySelector('[name="Id"]').value || null,
UserId: form.querySelector('[name="UserId"]').value || null,
@@ -173,25 +167,7 @@
}
}
btnBackToLibraries.addEventListener('click', () => {
window.location.href = '@_urlService.GetAbsoluteUrl("Index", "LibraryManagement")';
});
btnAddNewLibrary.addEventListener('click', () => {
window.location.href = '@_urlService.GetAbsoluteUrl("EditLibrary", "LibraryManagement")';
});
document.getElementById('add-media-directory').addEventListener('click', function () {
showFileSystemBrowserDialogAsync('C:\\Users\\', true, false, addNewPaths); // TODO: take path and include hidden elements from settings
});
document.querySelectorAll('.remove-form-table-row-icon').forEach(icon => {
icon.addEventListener('click', function () {
this.parentElement.remove();
});
});
function addNewPaths(selectedPaths) {
function addNewFileSystemPaths(selectedPaths) {
// get the form table where the new paths will be added
const formTable = document.querySelector('.form-table');
// process the selected paths
@@ -210,5 +186,66 @@
}
});
}
// on Enter key pressed
const handleEnterKey = async function(e) {
if (e.key === 'Enter') {
e.preventDefault();
await handleAddMediaLibraryAsync();
}
};
// on form submit event
const handleSubmit = async function(e) {
e.preventDefault();
await handleAddMediaLibraryAsync();
};
// on back to libraries button click
const handleBtnBackToLibrariesClick = function() {
window.location.href = '@_urlService.GetAbsoluteUrl("Index", "LibraryManagement")';
};
// on add new library button click
const handleBtnAddNewLibraryClick = function() {
window.location.href = '@_urlService.GetAbsoluteUrl("EditLibrary", "LibraryManagement")';
};
// on add media directory image click
const handleImgAddMediaDirectoryClick = async function() {
await showFileSystemBrowserDialogAsync('C:\\Users\\', true, false, addNewFileSystemPaths); // TODO: take path and include hidden elements from settings
};
// on remove row icon click
const handleRowRemoval = (e) => {
if (e.target.matches('.remove-form-table-row-icon'))
e.target.parentElement.remove();
};
// add listeners
form.addEventListener('keypress', handleEnterKey);
form.addEventListener('submit', handleSubmit);
btnBackToLibraries.addEventListener('click', handleBtnBackToLibrariesClick);
btnAddNewLibrary.addEventListener('click', handleBtnAddNewLibraryClick);
imgAddMediaDirectory.addEventListener('click', handleImgAddMediaDirectoryClick);
formTable.addEventListener('click', handleRowRemoval);
// register cleanup for these listeners
cleanupFunctions.push(() => {
form.removeEventListener('keypress', handleEnterKey);
form.removeEventListener('submit', handleSubmit);
btnBackToLibraries.removeEventListener('click', handleBtnBackToLibrariesClick);
btnAddNewLibrary.removeEventListener('click', handleBtnAddNewLibraryClick);
imgAddMediaDirectory.removeEventListener('click', handleImgAddMediaDirectoryClick);
formTable.removeEventListener('click', handleRowRemoval);
});
// store all cleanups for this view on window object using the scriptId
window.viewCleanups = window.viewCleanups || {};
window.viewCleanups['@scriptId'] = () => {
cleanupFunctions.forEach(cleanup => cleanup());
console.log(`Unloaded @scriptId`);
};
console.log(`Loaded @scriptId`);
</script>
}
@@ -4,11 +4,16 @@
@using Lumina.Presentation.Web.Common.Enums.Notifications
@using Lumina.Presentation.Web.Common.Exceptions
@using Lumina.Presentation.Web.Common.Models.FileSystemManagement
@using Lumina.Presentation.Web.Common.Services
@using Microsoft.AspNetCore.Mvc.Localization
@using Microsoft.AspNetCore.Components
@using System.Text.Json
@using System.Text
@{
var componentScriptId = ScriptIdentifierHelper.GenerateScriptId();
}
@inject IViewLocalizer _localizer
<div id="file-system-browser-dialog" class="container-background above-modal">
@@ -522,14 +527,23 @@
</div>
<div id="visible-selection-rectangle"></div>
<div id="selection-rectangle"></div>
<script defer src="~/js/file-system-browser-dialog.js" asp-append-version="true"></script>
<script defer>
document.addEventListener('DOMContentLoaded', async function () {
await initFileSystemBrowser(
'@Model.ServerBasePath',
'@Model.ClientBasePath',
'@Model.Path.Replace(@"\", @"\\")',
'@Model.ViewMode.ToString().ToLower()',
'@Model.IconSize.ToString().ToLower()');
});
<script defer src="~/js/file-system-browser-dialog.js" data-component-script="file-system-browser"></script>
<script defer data-component-init="file-system-browser">
// this outer function executes immediately and creates a scope for the variables
(function() {
// this inner function contains the actual initialization code that needs to run
async function checkAndInit() {
if (typeof initFileSystemBrowser === 'undefined' || typeof callApiGetAsync === 'undefined') {
setTimeout(checkAndInit, 10);
return;
}
await initFileSystemBrowser(
'@Model.ServerBasePath',
'@Model.ClientBasePath',
'@Model.Path.Replace(@"\", @"\\")',
'@Model.ViewMode.ToString().ToLower()',
'@Model.IconSize.ToString().ToLower()');
}
checkAndInit().catch(error => console.error('Failed to initialize file system browser:', error));
})();
</script>
@@ -29,6 +29,7 @@
<article class="h-100"> <!--needs to be 100% height so that child pages that require full height as well, can stretch-->
@RenderBody()
<div id="modal-background-article"></div>
<div class="dialog-container"></div>
</article>
</main>
@if (User?.Identity?.IsAuthenticated == true)