// ===== Admin Panel Module =====
const Admin = {
currentTab: 'dashboard',
async render() {
if (!Auth.isAdmin()) {
return '
Acesso negado
Area restrita a administradores.
';
}
const stats = await this.loadStats();
return `
Painel Administrativo
${this.renderDashboard(stats)}
Senha Redefinida
`;
},
async switchTab(tab) {
this.currentTab = tab;
document.querySelectorAll('.admin-tab').forEach(t => {
t.classList.toggle('active', t.dataset.tab === tab);
});
const content = document.getElementById('admin-content');
content.innerHTML = '';
try {
switch (tab) {
case 'dashboard':
const stats = await this.loadStats();
content.innerHTML = this.renderDashboard(stats);
break;
case 'users':
const users = await this.loadUsers();
content.innerHTML = this.renderUsers(users);
break;
case 'sessions':
const sessions = await this.loadSessions();
content.innerHTML = this.renderSessions(sessions);
break;
case 'logs':
const logs = await this.loadLogs();
content.innerHTML = this.renderLogs(logs);
break;
}
} catch (e) {
content.innerHTML = `Erro: ${e.message}
`;
}
},
async loadStats() {
const res = await fetch('/api/admin/stats', { headers: Auth.headers() });
return await res.json();
},
async loadUsers() {
const res = await fetch('/api/admin/users', { headers: Auth.headers() });
const data = await res.json();
return data.users;
},
async loadSessions() {
const res = await fetch('/api/admin/sessions', { headers: Auth.headers() });
const data = await res.json();
return data.sessions;
},
async loadLogs(page = 1) {
const res = await fetch(`/api/admin/logs?page=${page}&per_page=30`, { headers: Auth.headers() });
return await res.json();
},
renderDashboard(stats) {
return `
${stats.total_users}
Usuarios Ativos
${stats.active_sessions}
Sessoes Online
${stats.total_questions.toLocaleString('pt-BR')}
Questoes
${stats.total_topics}
Topicos
`;
},
renderUsers(users) {
let html = `
| Email | Nome | Role | Status | Sessoes | Tempo Total | Ultimo Login | Acoes |
`;
for (const u of users) {
const totalTime = u.total_time ? this.formatDuration(u.total_time) : '—';
const lastLogin = u.last_login ? new Date(u.last_login).toLocaleString('pt-BR') : '—';
html += `
| ${this.esc(u.email)} |
${this.esc(u.display_name || '—')} |
${u.role} |
${u.is_active ? 'Ativo' : 'Inativo'} |
${u.total_sessions || 0} |
${totalTime} |
${lastLogin} |
${u.is_active
? ``
: ``}
|
`;
}
html += '
';
return html;
},
renderSessions(sessions) {
if (sessions.length === 0) return 'Nenhuma sessao ativa no momento.
';
let html = `| Usuario | IP | Dispositivo | Login | Ultimo Heartbeat | Acoes |
`;
for (const s of sessions) {
html += `
${this.esc(s.email)}${s.display_name ? ` ${this.esc(s.display_name)}` : ''} |
${this.esc(s.ip_address || '—')} |
${this.esc(s.device_info || '—')} |
${new Date(s.login_time).toLocaleString('pt-BR')} |
${new Date(s.last_heartbeat).toLocaleString('pt-BR')} |
|
`;
}
html += '
';
return html;
},
renderLogs(data) {
const { logs, total } = data;
if (logs.length === 0) return 'Nenhum registro encontrado.
';
const kickedLabels = { 'self': 'Proprio', 'new_login': 'Novo login', 'timeout': 'Timeout', 'admin_kick': 'Admin', 'admin_deactivated': 'Desativado' };
let html = `Total: ${total} registros
| Email | IP | Dispositivo | Login | Logout | Duracao | Encerrado por |
`;
for (const l of logs) {
html += `
| ${this.esc(l.email || '—')} |
${this.esc(l.ip_address || '—')} |
${this.esc(l.device_info || '—')} |
${l.login_time ? new Date(l.login_time).toLocaleString('pt-BR') : '—'} |
${l.logout_time ? new Date(l.logout_time).toLocaleString('pt-BR') : '—'} |
${l.duration_seconds ? this.formatDuration(l.duration_seconds) : '—'} |
${kickedLabels[l.kicked_by] || l.kicked_by || '—'} |
`;
}
html += '
';
return html;
},
async createUser() {
const email = document.getElementById('new-user-email').value.trim();
const name = document.getElementById('new-user-name').value.trim();
const password = document.getElementById('new-user-password').value;
if (!email || !password) { alert('Email e senha sao obrigatorios'); return; }
try {
const res = await fetch('/api/admin/users', { method: 'POST', headers: Auth.headers(), body: JSON.stringify({ email, password, display_name: name }) });
const data = await res.json();
if (!res.ok) throw new Error(data.error);
alert(data.message);
this.closeModal('modal-create-user');
this.switchTab('users');
} catch (e) { alert('Erro: ' + e.message); }
},
async resetPassword(uid, email) {
if (!confirm(`Redefinir senha de ${email}?\nUma nova senha aleatoria sera gerada.`)) return;
try {
const res = await fetch(`/api/admin/users/${uid}/reset-password`, { method: 'POST', headers: Auth.headers() });
const data = await res.json();
if (!res.ok) throw new Error(data.error);
this._lastPasswordResult = `${data.email}: ${data.new_password}`;
document.getElementById('password-result-content').innerHTML = `
Nova senha gerada para ${this.esc(data.email)}:
${this.esc(data.new_password)}
Compartilhe esta senha com o usuario. Ela nao podera ser visualizada novamente.
`;
this.openModal('modal-password-result');
} catch (e) { alert('Erro: ' + e.message); }
},
async copyPasswordResult() {
if (this._lastPasswordResult) {
await navigator.clipboard.writeText(this._lastPasswordResult);
alert('Copiado!');
}
},
async toggleUser(uid, activate) {
if (!confirm(activate ? 'Ativar este usuario?' : 'Desativar este usuario?')) return;
try {
const res = await fetch(`/api/admin/users/${uid}/toggle`, { method: 'PUT', headers: Auth.headers() });
const data = await res.json();
if (!res.ok) throw new Error(data.error || 'Erro ao atualizar');
this.switchTab('users');
} catch (e) { alert('Erro: ' + e.message); }
},
async batchCreate() {
const raw = document.getElementById('batch-input').value.trim();
if (!raw) { alert('Insira pelo menos um email'); return; }
const lines = raw.split('\n').filter(l => l.trim());
const users = lines.map(line => {
const parts = line.split(',').map(p => p.trim());
return { email: parts[0], name: parts[1] || '' };
});
if (users.length === 0) { alert('Nenhum email valido encontrado'); return; }
if (!confirm(`Criar ${users.length} usuario(s)?`)) return;
try {
const res = await fetch('/api/admin/users/batch-create', {
method: 'POST', headers: Auth.headers(), body: JSON.stringify({ users })
});
const data = await res.json();
if (!res.ok) throw new Error(data.error);
let html = '';
if (data.total_created > 0) {
html += `${data.total_created} usuario(s) criado(s)
`;
html += '| Email | Nome | Senha |
';
this._batchResultText = 'Email\tNome\tSenha\n';
for (const u of data.created) {
html += `| ${this.esc(u.email)} | ${this.esc(u.name || '—')} | ${this.esc(u.password)} |
`;
this._batchResultText += `${u.email}\t${u.name || ''}\t${u.password}\n`;
}
html += '
';
}
if (data.total_errors > 0) {
html += `${data.total_errors} erro(s)
`;
for (const e of data.errors) {
html += `- ${this.esc(e.email)}: ${this.esc(e.error)}
`;
}
html += '
';
}
document.getElementById('batch-form').style.display = 'none';
document.getElementById('batch-results').style.display = 'block';
document.getElementById('batch-results-content').innerHTML = html;
} catch (e) { alert('Erro: ' + e.message); }
},
async copyBatchResults() {
if (this._batchResultText) {
await navigator.clipboard.writeText(this._batchResultText);
alert('Tabela copiada!');
}
},
closeBatchResults() {
document.getElementById('batch-form').style.display = 'block';
document.getElementById('batch-results').style.display = 'none';
document.getElementById('batch-input').value = '';
this.closeModal('modal-batch-create');
this.switchTab('users');
},
async kickSession(sid) {
if (!confirm('Encerrar esta sessao?')) return;
try {
const res = await fetch(`/api/admin/sessions/${sid}/kick`, { method: 'POST', headers: Auth.headers() });
if (!res.ok) throw new Error('Erro ao encerrar sessao');
this.switchTab('sessions');
} catch (e) { alert('Erro: ' + e.message); }
},
openModal(id) { document.getElementById(id).classList.add('show'); },
closeModal(id) { document.getElementById(id).classList.remove('show'); document.querySelectorAll(`#${id} input`).forEach(i => i.value = ''); },
formatDuration(seconds) {
if (!seconds || seconds < 0) return '—';
const h = Math.floor(seconds / 3600);
const m = Math.floor((seconds % 3600) / 60);
if (h > 0) return `${h}h ${m}m`;
if (m > 0) return `${m}m`;
return `${seconds}s`;
},
esc(str) {
if (!str) return '';
const div = document.createElement('div');
div.textContent = str;
return div.innerHTML;
}
};