// Sign-in, users and roles. Loaded before the other scripts, so every request the page makes goes
// through the permission handling below: a 401 asks for a sign-in and then retries, a 403 shows a notice.
(function () {
'use strict';
var AREAS = ['presets', 'sequences', 'zones', 'groups', 'devices', 'outputs', 'patterns', 'sim', 'settings', 'users'];
var AREA_LABELS = {
presets: 'Presets', sequences: 'Sequences', zones: 'Zones & profiles', groups: 'Groups', devices: 'Devices',
outputs: 'Outputs', patterns: 'Patterns & palettes', sim: 'Simulator', settings: 'Settings & updates', users: 'Users & roles',
};
var LEVELS = ['none', 'view', 'control', 'edit'];
var state = { enabled: false, user: '', role: '', perms: {} };
var origFetch = window.fetch.bind(window);
var pendingLogin = null;
function esc(s) {
return String(s == null ? '' : s).replace(/[&<>"']/g, function (c) {
return { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c];
});
}
function isAuthUrl(url) {
return String(url).indexOf('/auth') === 0;
}
function can(area, level) {
return !state.enabled || (state.perms[area] || 0) >= level;
}
function errorText(res) {
return res.json().then(function (j) { return j.error || ('Error ' + res.status); }, function () { return 'Error ' + res.status; });
}
/* ------------------------------------------------------------ styles and small UI */
function injectStyle() {
var st = document.createElement('style');
st.textContent = [
'[data-need][hidden]{display:none !important}',
'.auth-toast{position:fixed;left:50%;bottom:24px;transform:translateX(-50%);background:#3a1d1d;color:#fff;padding:10px 16px;border-radius:8px;z-index:10000;box-shadow:0 4px 16px rgba(0,0,0,.35);max-width:90vw;font-size:14px}',
'.auth-backdrop{position:fixed;inset:0;background:rgba(0,0,0,.55);display:flex;align-items:center;justify-content:center;z-index:9000;padding:16px}',
'.auth-dialog{background:var(--panel,#1e1e24);color:var(--text,#eee);border-radius:10px;padding:18px;min-width:280px;max-width:900px;width:100%;max-height:90vh;overflow:auto;box-shadow:0 8px 32px rgba(0,0,0,.5)}',
'.auth-dialog h3{margin:0 0 12px}',
'.auth-dialog label{display:block;margin:8px 0 4px;font-size:13px;opacity:.85}',
'.auth-dialog input,.auth-dialog select{width:100%;box-sizing:border-box;padding:6px 8px;border-radius:6px;border:1px solid #555;background:#111;color:#eee}',
'.auth-dialog table{border-collapse:collapse;width:100%;margin:8px 0}',
'.auth-dialog th,.auth-dialog td{padding:6px 8px;border-bottom:1px solid #333;text-align:left;font-size:13px}',
'.auth-dialog .auth-row{display:flex;gap:8px;align-items:center;flex-wrap:wrap}',
'.auth-dialog .auth-actions{display:flex;gap:8px;justify-content:flex-end;margin-top:14px;flex-wrap:wrap}',
'.auth-dialog button{padding:6px 12px;border-radius:6px;border:1px solid #555;background:#2a2a33;color:#eee;cursor:pointer}',
'.auth-dialog button.primary{background:#2d6cdf;border-color:#2d6cdf}',
'.auth-dialog button.danger{background:#7a2323;border-color:#7a2323}',
'.auth-err{color:#ff8a8a;font-size:13px;min-height:1em;margin-top:6px}',
'.auth-button{margin-left:8px;padding:4px 10px;border-radius:6px;border:1px solid #555;background:#2a2a33;color:#eee;cursor:pointer;font-size:13px;white-space:nowrap}',
].join('\n');
document.head.appendChild(st);
}
function toast(msg) {
var t = document.createElement('div');
t.className = 'auth-toast';
t.textContent = msg;
document.body.appendChild(t);
setTimeout(function () { t.remove(); }, 3500);
}
// A modal dialog. build(body) fills it; it returns a close function.
function dialog(title, build) {
var back = document.createElement('div');
back.className = 'auth-backdrop';
back.innerHTML = '
';
document.body.appendChild(back);
var body = back.querySelector('.auth-body');
function close() {
back.remove();
document.removeEventListener('keydown', onKey);
}
function onKey(e) {
if (e.key === 'Escape') {
close();
}
}
back.addEventListener('mousedown', function (e) {
if (e.target === back) {
close();
}
});
document.addEventListener('keydown', onKey);
build(body, close);
return close;
}
/* ------------------------------------------------------------ state */
function refresh() {
return origFetch('/auth', { credentials: 'same-origin' })
.then(function (r) { return r.json(); })
.then(function (s) {
state = s;
applyPerms();
return s;
})
.catch(function () { return state; });
}
function applyPerms() {
document.body.dataset.authRole = state.role || '';
document.body.dataset.authUser = state.user || '';
document.querySelectorAll('[data-need]').forEach(function (el) {
var need = el.getAttribute('data-need').split(':');
el.hidden = !can(need[0], LEVELS.indexOf(need[1]));
});
var btn = document.getElementById('auth-button');
if (btn) {
btn.textContent = !state.enabled ? 'Set up users' : state.user ? state.user + ' (' + state.role + ')' : 'Sign in';
}
}
/* ------------------------------------------------------------ sign in */
function askLogin() {
if (pendingLogin) {
return pendingLogin;
}
pendingLogin = new Promise(function (resolve) {
dialog('Sign in', function (body, close) {
body.innerHTML = [
'',
].join('');
var form = body.querySelector('form');
body.querySelector('#auth-user').focus();
body.querySelector('#auth-cancel').onclick = function () { close(); resolve(false); };
form.onsubmit = function (e) {
e.preventDefault();
var user = body.querySelector('#auth-user').value.trim(), pw = body.querySelector('#auth-pass').value;
origFetch('/auth/login', {
method: 'POST', credentials: 'same-origin',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ username: user, password: pw }),
}).then(function (res) {
if (!res.ok) {
return errorText(res).then(function (m) { body.querySelector('#auth-err').textContent = m; });
}
close();
return refresh().then(function () { resolve(true); });
});
};
});
}).then(function (ok) {
pendingLogin = null;
return ok;
});
return pendingLogin;
}
function changePassword() {
dialog('Change password', function (body, close) {
body.innerHTML = [
'',
].join('');
body.querySelector('#auth-cancel').onclick = close;
body.querySelector('form').onsubmit = function (e) {
e.preventDefault();
origFetch('/auth/password', {
method: 'PUT', credentials: 'same-origin', headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ old: body.querySelector('#auth-old').value, new: body.querySelector('#auth-new').value }),
}).then(function (res) {
if (!res.ok) {
return errorText(res).then(function (m) { body.querySelector('#auth-err').textContent = m; });
}
close();
toast('Password changed');
});
};
});
}
function signOut() {
origFetch('/auth/logout', { method: 'POST', credentials: 'same-origin' }).then(refresh).then(function () {
toast('Signed out');
});
}
/* ------------------------------------------------------------ users and roles */
function usersAndRoles() {
dialog('Users & roles', function (body) {
body.innerHTML = 'Loading…
';
var err = body.querySelector('#auth-err');
var content = body.querySelector('#auth-content');
var roles = [];
function req(method, url, data) {
err.textContent = '';
return origFetch(url, {
method: method, credentials: 'same-origin',
headers: data ? { 'Content-Type': 'application/json' } : undefined,
body: data ? JSON.stringify(data) : undefined,
}).then(function (res) {
if (!res.ok) {
return errorText(res).then(function (m) { err.textContent = m; throw new Error(m); });
}
return res.json().catch(function () { return {}; });
});
}
function roleOptions(selected) {
return roles.map(function (r) {
return '';
}).join('');
}
function render(users) {
var userRows = users.map(function (u) {
return '| ' + esc(u.username) + ' | ' +
' | ' +
'' +
' |
';
}).join('');
var head = '| Area | ' + roles.map(function (r) { return '' + esc(r.name) + ' | '; }).join('') + '
';
var matrix = AREAS.map(function (a) {
return '| ' + esc(AREA_LABELS[a]) + ' | ' + roles.map(function (r) {
var lvl = (r.perms && r.perms[a]) || 0;
var locked = r.name === 'admin';
return ' | ';
}).join('') + '
';
}).join('');
content.innerHTML = [
'Users
',
'| Username | Role | |
' + (userRows || '| No users yet |
') + '
',
'',
'',
'',
'
',
'Permissions
',
'none: hidden · view: read · control: play, stop, brightness, identify · edit: change anything.
',
'',
'',
'',
'
',
'' + roles.filter(function (r) { return !r.builtin; }).map(function (r) {
return '';
}).join(' ') + '
',
].join('');
wire();
}
function wire() {
content.querySelectorAll('[data-user-role]').forEach(function (sel) {
sel.onchange = function () {
req('PUT', '/auth/users/' + encodeURIComponent(sel.dataset.userRole), { role: sel.value })
.then(load, function () { load(); });
};
});
content.querySelectorAll('[data-reset]').forEach(function (b) {
b.onclick = function () {
var pw = window.prompt('New password for ' + b.dataset.reset + ' (8 to 128 characters)');
if (pw) {
req('PUT', '/auth/users/' + encodeURIComponent(b.dataset.reset), { password: pw }).then(load, function () {});
}
};
});
content.querySelectorAll('[data-delete-user]').forEach(function (b) {
b.onclick = function () {
if (window.confirm('Delete user ' + b.dataset.deleteUser + '?')) {
req('DELETE', '/auth/users/' + encodeURIComponent(b.dataset.deleteUser)).then(load, function () {});
}
};
});
content.querySelector('#add-user').onclick = function () {
req('POST', '/auth/users', {
username: content.querySelector('#new-user').value.trim(),
password: content.querySelector('#new-pass').value,
role: content.querySelector('#new-role').value,
}).then(load, function () {});
};
content.querySelector('#add-role').onclick = function () {
var name = content.querySelector('#new-role-name').value.trim();
var perms = {};
AREAS.forEach(function (a) { perms[a] = 0; });
req('POST', '/auth/roles', { name: name, perms: perms }).then(load, function () {});
};
content.querySelector('#save-roles').onclick = function () {
var jobs = roles.filter(function (r) { return r.name !== 'admin'; }).map(function (r) {
var perms = {};
AREAS.forEach(function (a) {
var sel = content.querySelector('[data-perm-role="' + r.name + '"][data-area="' + a + '"]');
perms[a] = sel ? parseInt(sel.value, 10) : 0;
});
return req('PUT', '/auth/roles/' + encodeURIComponent(r.name), { perms: perms });
});
Promise.all(jobs).then(function () { toast('Permissions saved'); load(); }, function () { load(); });
};
content.querySelectorAll('[data-delete-role]').forEach(function (b) {
b.onclick = function () {
if (window.confirm('Delete role ' + b.dataset.deleteRole + '?')) {
req('DELETE', '/auth/roles/' + encodeURIComponent(b.dataset.deleteRole)).then(load, function () {});
}
};
});
}
function load() {
Promise.all([req('GET', '/auth/roles'), req('GET', '/auth/users')]).then(function (res) {
try {
roles = res[0];
render(res[1]);
} catch (e) {
err.textContent = 'Could not show users and roles: ' + e.message;
}
}, function () {
if (!err.textContent) {
err.textContent = 'Could not load users and roles';
}
});
}
load();
});
}
/* ------------------------------------------------------------ header button */
function accountMenu() {
dialog(state.user ? 'Signed in as ' + state.user : 'Users', function (body, close) {
var rows = [];
if (!state.enabled) {
rows.push('No users yet, so anyone can edit. Create the first admin to turn sign-in on.
');
}
rows.push('');
if (!state.user && state.enabled) {
rows.push('');
}
if (state.user) {
rows.push('');
rows.push('');
}
if (can('users', AREA_EDIT_LEVEL)) {
rows.push('');
}
rows.push('
');
body.innerHTML = rows.join('');
var bind = function (id, fn) { var el = body.querySelector('#' + id); if (el) { el.onclick = function () { close(); fn(); }; } };
bind('auth-do-login', askLogin);
bind('auth-do-pass', changePassword);
bind('auth-do-out', signOut);
bind('auth-do-users', usersAndRoles);
body.querySelector('#auth-do-close').onclick = close;
});
}
var AREA_EDIT_LEVEL = 3;
function addHeaderButton() {
// Beside the Menu button, which stays visible; the header actions inside the menu are hidden until it opens
var menu = document.getElementById('main-menu-btn');
var host = menu ? menu.parentElement : document.querySelector('header');
if (!host || document.getElementById('auth-button')) {
return;
}
var btn = document.createElement('button');
btn.id = 'auth-button';
btn.type = 'button';
btn.className = 'auth-button';
btn.title = 'Sign in, change password, users and roles';
btn.onclick = accountMenu;
host.insertBefore(btn, menu || host.firstChild);
applyPerms();
}
/* ------------------------------------------------------------ fetch wrapper */
window.fetch = function (input, init) {
var url = typeof input === 'string' ? input : (input && input.url) || '';
var auth = isAuthUrl(url);
var method = String((init && init.method) || (input && input.method) || 'GET').toUpperCase();
return origFetch(input, init).then(function (res) {
if (auth) {
return res;
}
// Only a change asks for a sign-in; a read the page cannot do just fails quietly
if (res.status === 401 && method !== 'GET') {
return askLogin().then(function (ok) {
return ok ? origFetch(input, init) : res;
});
}
if (res.status === 403 && method !== 'GET') {
errorText(res.clone()).then(toast);
}
return res;
});
};
/* ------------------------------------------------------------ start */
function start() {
injectStyle();
addHeaderButton();
refresh();
window.authPerms = {
can: can,
refresh: refresh,
usersAndRoles: usersAndRoles,
};
}
if (document.readyState === 'loading') {
document.addEventListener('DOMContentLoaded', start);
} else {
start();
}
})();