Download static/js/admin.js from QBANK/OFTQUEST: direct link, hf CLI and curl.
- Browser
- Download file 18.4 kB
-
https://huggingface.co/spaces/QBANK/OFTQUEST/resolve/main/static/js/admin.js
- Command line
-
hf download hf://spaces/QBANK/OFTQUEST/static/js/admin.js
-
curl -L -o admin.js https://huggingface.co/spaces/QBANK/OFTQUEST/resolve/main/static/js/admin.js
18.4 kB
| // ===== Admin Panel Module ===== | |
| const Admin = { | |
| currentTab: 'dashboard', | |
| async render() { | |
| if (!Auth.isAdmin()) { | |
| return '<div class="container"><h2>Acesso negado</h2><p>Area restrita a administradores.</p></div>'; | |
| } | |
| const stats = await this.loadStats(); | |
| return ` | |
| <div class="container"> | |
| <h1 class="page-title">Painel Administrativo</h1> | |
| <div class="admin-tabs"> | |
| <button class="admin-tab active" data-tab="dashboard" onclick="Admin.switchTab('dashboard')">Dashboard</button> | |
| <button class="admin-tab" data-tab="users" onclick="Admin.switchTab('users')">Usuarios</button> | |
| <button class="admin-tab" data-tab="sessions" onclick="Admin.switchTab('sessions')">Sessoes Ativas</button> | |
| <button class="admin-tab" data-tab="logs" onclick="Admin.switchTab('logs')">Historico</button> | |
| </div> | |
| <div id="admin-content"> | |
| ${this.renderDashboard(stats)} | |
| </div> | |
| </div> | |
| <!-- Create User Modal --> | |
| <div class="modal-overlay" id="modal-create-user"> | |
| <div class="modal"> | |
| <h2>Novo Usuario</h2> | |
| <div class="form-group"> | |
| <label>Email</label> | |
| <input type="email" id="new-user-email" placeholder="usuario@email.com"> | |
| </div> | |
| <div class="form-group"> | |
| <label>Nome</label> | |
| <input type="text" id="new-user-name" placeholder="Nome do usuario"> | |
| </div> | |
| <div class="form-group"> | |
| <label>Senha</label> | |
| <input type="password" id="new-user-password" placeholder="Senha"> | |
| </div> | |
| <div class="modal-actions"> | |
| <button class="btn btn-secondary" onclick="Admin.closeModal('modal-create-user')">Cancelar</button> | |
| <button class="btn btn-primary" style="width:auto" onclick="Admin.createUser()">Criar Usuario</button> | |
| </div> | |
| </div> | |
| </div> | |
| <!-- Batch Create Modal --> | |
| <div class="modal-overlay" id="modal-batch-create"> | |
| <div class="modal" style="max-width:600px"> | |
| <h2>Cadastro em Lote</h2> | |
| <div id="batch-form"> | |
| <div class="form-group"> | |
| <label>Lista de alunos (um por linha)</label> | |
| <textarea id="batch-input" rows="10" placeholder="email@exemplo.com, Nome do Aluno outro@email.com, Outro Nome apenas@email.com" style="width:100%;font-family:monospace;font-size:13px;padding:10px;border:1px solid #ddd;border-radius:8px;resize:vertical;"></textarea> | |
| <small style="color:var(--text-sec);display:block;margin-top:6px;">Formato: email ou email, nome (um por linha). Senhas serao geradas automaticamente.</small> | |
| </div> | |
| <div class="modal-actions"> | |
| <button class="btn btn-secondary" onclick="Admin.closeModal('modal-batch-create')">Cancelar</button> | |
| <button class="btn btn-primary" style="width:auto" onclick="Admin.batchCreate()">Criar Usuarios</button> | |
| </div> | |
| </div> | |
| <div id="batch-results" style="display:none"> | |
| <div id="batch-results-content"></div> | |
| <div class="modal-actions"> | |
| <button class="btn btn-secondary" onclick="Admin.closeBatchResults()">Fechar</button> | |
| <button class="btn btn-primary" style="width:auto" onclick="Admin.copyBatchResults()">Copiar Tabela</button> | |
| </div> | |
| </div> | |
| </div> | |
| </div> | |
| <!-- Password Result Modal --> | |
| <div class="modal-overlay" id="modal-password-result"> | |
| <div class="modal"> | |
| <h2>Senha Redefinida</h2> | |
| <div id="password-result-content"></div> | |
| <div class="modal-actions"> | |
| <button class="btn btn-secondary" onclick="Admin.closeModal('modal-password-result')">Fechar</button> | |
| <button class="btn btn-primary" style="width:auto" onclick="Admin.copyPasswordResult()">Copiar</button> | |
| </div> | |
| </div> | |
| </div> | |
| `; | |
| }, | |
| 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 = '<div class="loading"><div class="spinner"></div>Carregando...</div>'; | |
| 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 = `<div class="loading">Erro: ${e.message}</div>`; | |
| } | |
| }, | |
| 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 ` | |
| <div class="stat-cards"> | |
| <div class="stat-card"><div class="stat-value">${stats.total_users}</div><div class="stat-label">Usuarios Ativos</div></div> | |
| <div class="stat-card"><div class="stat-value">${stats.active_sessions}</div><div class="stat-label">Sessoes Online</div></div> | |
| <div class="stat-card"><div class="stat-value">${stats.total_questions.toLocaleString('pt-BR')}</div><div class="stat-label">Questoes</div></div> | |
| <div class="stat-card"><div class="stat-value">${stats.total_topics}</div><div class="stat-label">Topicos</div></div> | |
| </div> | |
| `; | |
| }, | |
| renderUsers(users) { | |
| let html = ` | |
| <div style="margin-bottom:16px; display:flex; justify-content:flex-end; gap:8px;"> | |
| <button class="btn btn-secondary" style="width:auto" onclick="Admin.openModal('modal-batch-create')">Cadastro em Lote</button> | |
| <button class="btn btn-primary" style="width:auto" onclick="Admin.openModal('modal-create-user')">+ Novo Aluno</button> | |
| </div> | |
| <table class="data-table"> | |
| <thead><tr><th>Email</th><th>Nome</th><th>Role</th><th>Status</th><th>Sessoes</th><th>Tempo Total</th><th>Ultimo Login</th><th>Acoes</th></tr></thead> | |
| <tbody> | |
| `; | |
| 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 += ` | |
| <tr> | |
| <td>${this.esc(u.email)}</td> | |
| <td>${this.esc(u.display_name || 'β')}</td> | |
| <td><span class="badge ${u.role === 'admin' ? 'badge-admin' : ''}">${u.role}</span></td> | |
| <td><span class="badge ${u.is_active ? 'badge-active' : 'badge-inactive'}">${u.is_active ? 'Ativo' : 'Inativo'}</span></td> | |
| <td>${u.total_sessions || 0}</td> | |
| <td>${totalTime}</td> | |
| <td>${lastLogin}</td> | |
| <td style="display:flex;gap:4px;flex-wrap:wrap;"> | |
| <button class="btn btn-secondary btn-sm" onclick="Admin.resetPassword(${u.id}, '${u.email.replace(/'/g,"\\'")}')">🔑 Senha</button> | |
| ${u.is_active | |
| ? `<button class="btn btn-danger btn-sm" onclick="Admin.toggleUser(${u.id}, false)">Desativar</button>` | |
| : `<button class="btn btn-secondary btn-sm" onclick="Admin.toggleUser(${u.id}, true)">Ativar</button>`} | |
| </td> | |
| </tr>`; | |
| } | |
| html += '</tbody></table>'; | |
| return html; | |
| }, | |
| renderSessions(sessions) { | |
| if (sessions.length === 0) return '<div class="loading">Nenhuma sessao ativa no momento.</div>'; | |
| let html = `<table class="data-table"><thead><tr><th>Usuario</th><th>IP</th><th>Dispositivo</th><th>Login</th><th>Ultimo Heartbeat</th><th>Acoes</th></tr></thead><tbody>`; | |
| for (const s of sessions) { | |
| html += `<tr> | |
| <td><strong>${this.esc(s.email)}</strong>${s.display_name ? `<br><small>${this.esc(s.display_name)}</small>` : ''}</td> | |
| <td><code>${this.esc(s.ip_address || 'β')}</code></td> | |
| <td><small>${this.esc(s.device_info || 'β')}</small></td> | |
| <td>${new Date(s.login_time).toLocaleString('pt-BR')}</td> | |
| <td>${new Date(s.last_heartbeat).toLocaleString('pt-BR')}</td> | |
| <td><button class="btn btn-danger btn-sm" onclick="Admin.kickSession(${s.id})">Encerrar</button></td> | |
| </tr>`; | |
| } | |
| html += '</tbody></table>'; | |
| return html; | |
| }, | |
| renderLogs(data) { | |
| const { logs, total } = data; | |
| if (logs.length === 0) return '<div class="loading">Nenhum registro encontrado.</div>'; | |
| const kickedLabels = { 'self': 'Proprio', 'new_login': 'Novo login', 'timeout': 'Timeout', 'admin_kick': 'Admin', 'admin_deactivated': 'Desativado' }; | |
| let html = `<p style="margin-bottom:12px;color:var(--text-sec)">Total: ${total} registros</p> | |
| <table class="data-table"><thead><tr><th>Email</th><th>IP</th><th>Dispositivo</th><th>Login</th><th>Logout</th><th>Duracao</th><th>Encerrado por</th></tr></thead><tbody>`; | |
| for (const l of logs) { | |
| html += `<tr> | |
| <td>${this.esc(l.email || 'β')}</td> | |
| <td><code>${this.esc(l.ip_address || 'β')}</code></td> | |
| <td><small>${this.esc(l.device_info || 'β')}</small></td> | |
| <td>${l.login_time ? new Date(l.login_time).toLocaleString('pt-BR') : 'β'}</td> | |
| <td>${l.logout_time ? new Date(l.logout_time).toLocaleString('pt-BR') : 'β'}</td> | |
| <td>${l.duration_seconds ? this.formatDuration(l.duration_seconds) : 'β'}</td> | |
| <td><span class="badge">${kickedLabels[l.kicked_by] || l.kicked_by || 'β'}</span></td> | |
| </tr>`; | |
| } | |
| html += '</tbody></table>'; | |
| 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 = ` | |
| <p style="margin-bottom:12px">Nova senha gerada para <strong>${this.esc(data.email)}</strong>:</p> | |
| <code style="display:block;background:#f5f5f5;padding:12px;border-radius:8px;font-size:16px;text-align:center;user-select:all">${this.esc(data.new_password)}</code> | |
| <p style="margin-top:12px;color:var(--text-sec);font-size:13px">Compartilhe esta senha com o usuario. Ela nao podera ser visualizada novamente.</p> | |
| `; | |
| 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 += `<p style="margin-bottom:8px;color:var(--correct);font-weight:600">${data.total_created} usuario(s) criado(s)</p>`; | |
| html += '<table class="data-table" style="font-size:13px"><thead><tr><th>Email</th><th>Nome</th><th>Senha</th></tr></thead><tbody>'; | |
| this._batchResultText = 'Email\tNome\tSenha\n'; | |
| for (const u of data.created) { | |
| html += `<tr><td>${this.esc(u.email)}</td><td>${this.esc(u.name || 'β')}</td><td><code style="user-select:all">${this.esc(u.password)}</code></td></tr>`; | |
| this._batchResultText += `${u.email}\t${u.name || ''}\t${u.password}\n`; | |
| } | |
| html += '</tbody></table>'; | |
| } | |
| if (data.total_errors > 0) { | |
| html += `<p style="margin-top:12px;margin-bottom:8px;color:var(--wrong);font-weight:600">${data.total_errors} erro(s)</p><ul style="font-size:13px">`; | |
| for (const e of data.errors) { | |
| html += `<li>${this.esc(e.email)}: ${this.esc(e.error)}</li>`; | |
| } | |
| html += '</ul>'; | |
| } | |
| 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; | |
| } | |
| }; | |