feat: per-user panel permissions system

Replace hardcoded role-based access with granular per-panel permissions.
Each user can now be assigned any combination of 6 panels (Corporate, BI
Executive, Clientes, Providers, Usuarios, Meu Dashboard) regardless of
their role. Existing users are auto-migrated with defaults based on role.

- Add src/panels.js with panel registry and default permissions
- Add permissions column to SQLite + migration for existing users
- Add requirePermission() middleware, replace requireRole on all routes
- Dynamic nav in buildHeader based on user permissions
- Permissions checkbox UI in admin panel with role presets
- Anti-lockout: users cannot remove 'usuarios' from themselves

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
This commit is contained in:
root
2026-02-17 17:27:36 -05:00
parent cd5773a1be
commit 8641100a18
12 changed files with 324 additions and 174 deletions

View File

@@ -2,10 +2,18 @@
* Admin Panel - HTML builder for user management
*/
const { buildHeader, buildFooter, buildHead } = require('./ui-template');
const { PANELS, DEFAULT_PERMISSIONS } = require('./panels');
function buildAdminHTML(agentes, admin) {
const now = new Date().toLocaleString('pt-BR');
// Precompute permissions JSON for each agent row
const agentesWithPerms = agentes.map(a => {
let perms = [];
try { perms = JSON.parse(a.permissions || '[]'); } catch(e) {}
return { ...a, _perms: perms };
});
const pageCSS = `
<style>
.toolbar {
@@ -51,6 +59,12 @@ function buildAdminHTML(agentes, admin) {
.status-badge.corporate { background: var(--corporate-bg); color: var(--corporate-accent); }
.status-badge.agent { background: var(--blue-bg); color: var(--blue); }
.perm-badge {
display: inline-block; padding: 2px 7px; border-radius: 8px;
font-size: 10px; font-weight: 600; margin: 1px 2px;
background: var(--blue-bg); color: var(--blue);
}
.actions { display: flex; gap: 6px; }
.btn-action {
padding: 6px 12px; border-radius: 6px; font-size: 11px; font-weight: 600;
@@ -73,7 +87,7 @@ function buildAdminHTML(agentes, admin) {
}
.modal-overlay.active { display: flex; }
.modal {
background: var(--card); border-radius: 16px; width: 100%; max-width: 480px;
background: var(--card); border-radius: 16px; width: 100%; max-width: 520px;
max-height: 90vh; overflow-y: auto; box-shadow: 0 20px 60px rgba(0,0,0,0.2);
}
.modal-header {
@@ -122,6 +136,20 @@ function buildAdminHTML(agentes, admin) {
}
.btn-submit:hover { background: #25732a; }
/* Permissions checkboxes */
.perm-grid {
display: grid; grid-template-columns: 1fr 1fr; gap: 8px;
margin-top: 6px;
}
.perm-check {
display: flex; align-items: center; gap: 8px;
padding: 8px 10px; border-radius: 8px; border: 1.5px solid var(--border);
cursor: pointer; transition: all 0.15s; font-size: 13px;
}
.perm-check:hover { border-color: var(--admin-accent); background: var(--green-bg); }
.perm-check input[type="checkbox"] { width: 16px; height: 16px; cursor: pointer; accent-color: var(--admin-accent); }
.perm-check.checked { border-color: var(--admin-accent); background: var(--green-bg); }
.alert {
padding: 12px 16px; border-radius: 8px; font-size: 13px; font-weight: 500;
margin-bottom: 20px; display: none;
@@ -166,6 +194,7 @@ function buildAdminHTML(agentes, admin) {
gap: 8px;
}
.modal-footer button { width: 100%; }
.perm-grid { grid-template-columns: 1fr; }
}
@media (max-width: 480px) {
@@ -193,9 +222,16 @@ function buildAdminHTML(agentes, admin) {
[data-theme="dark"] .btn-edit:hover { background: rgba(88,166,255,0.15); }
[data-theme="dark"] .btn-toggle:hover { background: rgba(240,136,62,0.15); }
[data-theme="dark"] .btn-password:hover { background: rgba(188,140,255,0.15); }
[data-theme="dark"] .perm-check { border-color: var(--border); }
[data-theme="dark"] .perm-check:hover { background: rgba(63,185,80,0.08); }
[data-theme="dark"] .perm-check.checked { background: rgba(63,185,80,0.08); border-color: var(--green); }
</style>
`;
// Panel label map for badges
const panelLabels = {};
PANELS.forEach(p => { panelLabels[p.key] = p.label; });
return `<!DOCTYPE html>
<html lang="pt-BR">
<head>
@@ -203,7 +239,7 @@ ${buildHead('Usuarios', pageCSS)}
</head>
<body>
${buildHeader({ role: 'admin', userName: admin.nome, activePage: 'users' })}
${buildHeader({ role: admin.role || 'admin', userName: admin.nome, activePage: 'users', permissions: admin.permissions || [] })}
<div class="app-container">
<div id="alertBox" class="alert"></div>
@@ -222,6 +258,7 @@ ${buildHeader({ role: 'admin', userName: admin.nome, activePage: 'users' })}
<th>Nome</th>
<th>E-mail</th>
<th>Role</th>
<th>Permissoes</th>
<th>Agente ID</th>
<th>Status</th>
<th>Criado em</th>
@@ -229,17 +266,18 @@ ${buildHeader({ role: 'admin', userName: admin.nome, activePage: 'users' })}
</tr>
</thead>
<tbody id="agentesTable">
${agentes.map(a => `
<tr data-id="${a.id}">
${agentesWithPerms.map(a => `
<tr data-id="${a.id}" data-permissions='${JSON.stringify(a._perms)}'>
<td>${a.id}</td>
<td>${a.nome}</td>
<td>${a.email}</td>
<td><span class="status-badge ${a.role === 'admin' ? 'admin' : a.role === 'corporate' ? 'corporate' : 'agent'}">${a.role === 'admin' ? 'Admin' : a.role === 'corporate' ? 'Corporate' : 'Agente'}</span></td>
<td>${(a.role === 'admin' || a.role === 'corporate') ? '-' : a.agente_id}</td>
<td>${a._perms.map(k => '<span class="perm-badge">' + (panelLabels[k] || k) + '</span>').join(' ')}</td>
<td>${a.agente_id || '-'}</td>
<td><span class="status-badge ${a.ativo ? 'active' : 'inactive'}">${a.ativo ? 'Ativo' : 'Inativo'}</span></td>
<td>${a.created_at ? new Date(a.created_at).toLocaleDateString('pt-BR') : '-'}</td>
<td class="actions">
${a.role === 'agente' ? `<a href="/corporate/emular/${a.agente_id}" class="btn-action btn-emular" title="Ver como este agente">Emular</a>` : ''}
${a.agente_id ? `<a href="/corporate/emular/${a.agente_id}" class="btn-action btn-emular" title="Ver como este agente">Emular</a>` : ''}
<button class="btn-action btn-edit" onclick="openEditModal(${a.id}, '${a.nome.replace(/'/g, "\\'")}', '${a.email.replace(/'/g, "\\'")}', ${a.agente_id}, '${a.role || 'agente'}', event)">Editar</button>
<button class="btn-action btn-toggle" onclick="toggleAgente(${a.id}, ${a.ativo})">${a.ativo ? 'Desativar' : 'Ativar'}</button>
<button class="btn-action btn-password" onclick="openPasswordModal(${a.id}, '${a.nome.replace(/'/g, "\\'")}')">Senha</button>
@@ -273,13 +311,24 @@ ${buildFooter()}
<input type="email" id="agentEmail" name="email" required placeholder="usuario@email.com">
</div>
<div class="form-group">
<label>Tipo de Usuario</label>
<select id="agentRole" name="role" onchange="toggleAgenteIdField()">
<label>Tipo de Usuario (preset)</label>
<select id="agentRole" name="role" onchange="onRoleChange()">
<option value="agente">Agente</option>
<option value="corporate">Corporate</option>
<option value="admin">Administrador</option>
</select>
</div>
<div class="form-group">
<label>Permissoes de Acesso</label>
<div class="perm-grid" id="permGrid">
${PANELS.map(p => `
<label class="perm-check" id="permLabel_${p.key}">
<input type="checkbox" name="perm_${p.key}" value="${p.key}" onchange="onPermChange(this)">
${p.label}
</label>
`).join('')}
</div>
</div>
<div class="form-group" id="agenteIdGroup">
<label>Agente ID (Sistema)</label>
<input type="number" id="agentAgenteId" name="agente_id" placeholder="ID numerico do agente">
@@ -325,27 +374,66 @@ ${buildFooter()}
</div>
<script>
let isEditing = false;
var isEditing = false;
var DEFAULT_PERMS = ${JSON.stringify(DEFAULT_PERMISSIONS)};
function showAlert(message, type) {
const alert = document.getElementById('alertBox');
var alert = document.getElementById('alertBox');
alert.textContent = message;
alert.className = 'alert ' + type + ' show';
setTimeout(() => { alert.className = 'alert'; }, 4000);
setTimeout(function() { alert.className = 'alert'; }, 4000);
}
function getPermCheckboxes() {
return document.querySelectorAll('#permGrid input[type="checkbox"]');
}
function setPermissions(keys) {
getPermCheckboxes().forEach(function(cb) {
cb.checked = keys.includes(cb.value);
updatePermLabel(cb);
});
toggleAgenteIdField();
}
function onPermChange(cb) {
updatePermLabel(cb);
toggleAgenteIdField();
}
function updatePermLabel(cb) {
var label = document.getElementById('permLabel_' + cb.value);
if (label) {
if (cb.checked) label.classList.add('checked');
else label.classList.remove('checked');
}
}
function getSelectedPermissions() {
var perms = [];
getPermCheckboxes().forEach(function(cb) {
if (cb.checked) perms.push(cb.value);
});
return perms;
}
function onRoleChange() {
var role = document.getElementById('agentRole').value;
var defaults = DEFAULT_PERMS[role] || [];
setPermissions(defaults);
}
function toggleAgenteIdField() {
const role = document.getElementById('agentRole').value;
const agenteIdGroup = document.getElementById('agenteIdGroup');
const agenteIdInput = document.getElementById('agentAgenteId');
// Admin and Corporate don't need agente_id
if (role === 'admin' || role === 'corporate') {
agenteIdGroup.style.display = 'none';
agenteIdInput.required = false;
agenteIdInput.value = '';
} else {
var perms = getSelectedPermissions();
var agenteIdGroup = document.getElementById('agenteIdGroup');
var agenteIdInput = document.getElementById('agentAgenteId');
if (perms.includes('dashboard')) {
agenteIdGroup.style.display = 'block';
agenteIdInput.required = !isEditing;
} else {
agenteIdGroup.style.display = 'none';
agenteIdInput.required = false;
}
}
@@ -359,8 +447,8 @@ function openCreateModal(event) {
document.getElementById('agentRole').value = 'agente';
document.getElementById('senhaGroup').style.display = 'block';
document.getElementById('agentSenha').required = true;
toggleAgenteIdField();
setTimeout(() => {
onRoleChange();
setTimeout(function() {
document.getElementById('agentModal').classList.add('active');
document.getElementById('agentNome').focus();
}, 10);
@@ -378,8 +466,16 @@ function openEditModal(id, nome, email, agenteId, role, event) {
document.getElementById('agentRole').value = role || 'agente';
document.getElementById('senhaGroup').style.display = 'none';
document.getElementById('agentSenha').required = false;
toggleAgenteIdField();
setTimeout(() => {
// Load permissions from data attribute
var row = document.querySelector('tr[data-id="' + id + '"]');
var perms = [];
if (row) {
try { perms = JSON.parse(row.getAttribute('data-permissions') || '[]'); } catch(e) {}
}
setPermissions(perms);
setTimeout(function() {
document.getElementById('agentModal').classList.add('active');
document.getElementById('agentNome').focus();
}, 10);
@@ -399,25 +495,26 @@ function closeModal(id) {
async function submitAgentForm(e) {
e.preventDefault();
const id = document.getElementById('agentId').value;
const role = document.getElementById('agentRole').value;
const data = {
var id = document.getElementById('agentId').value;
var role = document.getElementById('agentRole').value;
var permissions = getSelectedPermissions();
var data = {
nome: document.getElementById('agentNome').value,
email: document.getElementById('agentEmail').value,
role: role,
permissions: permissions,
};
// Only agents need agente_id
if (role === 'agente') {
const agenteId = document.getElementById('agentAgenteId').value;
if (!isEditing && !agenteId) {
showAlert('Agente ID e obrigatorio para agentes', 'error');
// Agente ID
var agenteIdVal = document.getElementById('agentAgenteId').value;
if (permissions.includes('dashboard')) {
if (!isEditing && !agenteIdVal) {
showAlert('Agente ID e obrigatorio para acesso ao Meu Dashboard', 'error');
return;
}
data.agente_id = parseInt(agenteId) || 0;
data.agente_id = parseInt(agenteIdVal) || 0;
} else {
// Admin and Corporate don't have agente_id
data.agente_id = 0;
data.agente_id = parseInt(agenteIdVal) || 0;
}
if (!isEditing) {
@@ -425,18 +522,18 @@ async function submitAgentForm(e) {
}
try {
const url = isEditing ? '/admin/agentes/' + id : '/admin/agentes';
const method = isEditing ? 'PUT' : 'POST';
const res = await fetch(url, {
method,
var url = isEditing ? '/admin/agentes/' + id : '/admin/agentes';
var method = isEditing ? 'PUT' : 'POST';
var res = await fetch(url, {
method: method,
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data)
});
const result = await res.json();
var result = await res.json();
if (res.ok) {
showAlert(isEditing ? 'Usuario atualizado com sucesso!' : 'Usuario criado com sucesso!', 'success');
closeModal('agentModal');
setTimeout(() => location.reload(), 1000);
setTimeout(function() { location.reload(); }, 1000);
} else {
showAlert(result.error || 'Erro ao salvar usuario', 'error');
}
@@ -447,9 +544,9 @@ async function submitAgentForm(e) {
async function submitPasswordForm(e) {
e.preventDefault();
const id = document.getElementById('passwordAgentId').value;
const newPassword = document.getElementById('newPassword').value;
const confirmPassword = document.getElementById('confirmPassword').value;
var id = document.getElementById('passwordAgentId').value;
var newPassword = document.getElementById('newPassword').value;
var confirmPassword = document.getElementById('confirmPassword').value;
if (newPassword !== confirmPassword) {
showAlert('As senhas nao coincidem', 'error');
@@ -457,12 +554,12 @@ async function submitPasswordForm(e) {
}
try {
const res = await fetch('/admin/agentes/' + id, {
var res = await fetch('/admin/agentes/' + id, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ senha: newPassword })
});
const result = await res.json();
var result = await res.json();
if (res.ok) {
showAlert('Senha redefinida com sucesso!', 'success');
closeModal('passwordModal');
@@ -475,19 +572,19 @@ async function submitPasswordForm(e) {
}
async function toggleAgente(id, currentStatus) {
const action = currentStatus ? 'desativar' : 'ativar';
var action = currentStatus ? 'desativar' : 'ativar';
if (!confirm('Deseja ' + action + ' este usuario?')) return;
try {
const res = await fetch('/admin/agentes/' + id, {
var res = await fetch('/admin/agentes/' + id, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ ativo: currentStatus ? 0 : 1 })
});
const result = await res.json();
var result = await res.json();
if (res.ok) {
showAlert('Usuario ' + (currentStatus ? 'desativado' : 'ativado') + ' com sucesso!', 'success');
setTimeout(() => location.reload(), 1000);
setTimeout(function() { location.reload(); }, 1000);
} else {
showAlert(result.error || 'Erro ao alterar status', 'error');
}
@@ -497,25 +594,25 @@ async function toggleAgente(id, currentStatus) {
}
// Close modal on overlay click
document.querySelectorAll('.modal-overlay').forEach(overlay => {
overlay.addEventListener('click', (e) => {
document.querySelectorAll('.modal-overlay').forEach(function(overlay) {
overlay.addEventListener('click', function(e) {
if (e.target === overlay) overlay.classList.remove('active');
});
});
// Prevent clicks inside modal from closing it
document.querySelectorAll('.modal').forEach(modal => {
modal.addEventListener('click', (e) => e.stopPropagation());
document.querySelectorAll('.modal').forEach(function(modal) {
modal.addEventListener('click', function(e) { e.stopPropagation(); });
});
// Close modal on Escape key
document.addEventListener('keydown', (e) => {
document.addEventListener('keydown', function(e) {
if (e.key === 'Escape') {
document.querySelectorAll('.modal-overlay.active').forEach(m => m.classList.remove('active'));
document.querySelectorAll('.modal-overlay.active').forEach(function(m) { m.classList.remove('active'); });
}
});
</script>
<\/script>
</body>
</html>`;
}