v2: user CRUD + schema автозапуск + router тесты — модуль пользователя готов
This commit is contained in:
+130
-10
@@ -1,24 +1,144 @@
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
// V2 — пользовательский CRUD (пустышка)
|
||||
// Будет: таблица записей, форма добавления, выбор компании из дропдауна
|
||||
// V2 — пользовательский CRUD
|
||||
// Вход: req.v2_* из resolveContext (email, clientId, allClientIds, profiles, ...)
|
||||
// Всегда показывает выбор компании (даже если одна).
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
const express = require('express');
|
||||
const q = require('../db/queries');
|
||||
|
||||
function createUserRouter() {
|
||||
const router = express.Router();
|
||||
|
||||
router.get('/', (req, res) => {
|
||||
res.send(`<h2>User CRUD</h2>
|
||||
<p>email: ${req.v2_email}</p>
|
||||
<p>clientId: ${req.v2_clientId}</p>
|
||||
<p>isAdmin: ${req.v2_isAdmin}</p>
|
||||
<p>isImpersonated: ${req.v2_isImpersonated}</p>
|
||||
<p><a href="/v2/admin">Админка</a> | <a href="/v2/logout">Выйти</a></p>
|
||||
`);
|
||||
// ── GET / — главная: список записей + форма ────────────────────────────
|
||||
router.get('/', async (req, res) => {
|
||||
try {
|
||||
const clId = req.v2_clientId;
|
||||
const allCompanies = req.v2_profiles.length > 0
|
||||
? req.v2_profiles
|
||||
: [{ client_id: clId, company_name: req.v2_companyName || clId }];
|
||||
|
||||
const company = await q.getOrCreateCompany(clId, allCompanies.find(c => c.client_id === clId)?.company_name || clId);
|
||||
const includeDeleted = req.query.deleted === '1';
|
||||
const entries = await q.listEntries(company.id, includeDeleted);
|
||||
const limit = await q.getLimit(company);
|
||||
const used = entries.filter(e => !e.deleted_at).length;
|
||||
|
||||
// Переключение компании
|
||||
if (req.query.switchTo && allCompanies.find(c => c.client_id === req.query.switchTo)) {
|
||||
req.session.v2_user.activeClientId = req.query.switchTo;
|
||||
return res.redirect('/v2/app');
|
||||
}
|
||||
|
||||
res.send(renderPage({ entries, company, limit, used, allCompanies, clId, user: req.v2_user, includeDeleted }));
|
||||
} catch (e) {
|
||||
res.status(500).send('<h2>Ошибка</h2><pre>' + e.message + '</pre><a href="/v2/app">Назад</a>');
|
||||
}
|
||||
});
|
||||
|
||||
// ── POST /add ───────────────────────────────────────────────────────────
|
||||
router.post('/add', async (req, res) => {
|
||||
try {
|
||||
const clId = req.v2_clientId;
|
||||
const company = await q.getOrCreateCompany(clId, clId);
|
||||
const result = await q.createEntry(company.id, req.body.cidr || '', req.body.comment || '', req.v2_email, req.v2_impersonatedBy);
|
||||
const msg = result.wasNormalized ? 'Добавлено (адрес нормализован)' : 'Добавлено';
|
||||
res.redirect('/v2/app?msg=' + encodeURIComponent(msg));
|
||||
} catch (e) {
|
||||
res.redirect('/v2/app?error=' + encodeURIComponent(e.message));
|
||||
}
|
||||
});
|
||||
|
||||
// ── POST /edit/:id ──────────────────────────────────────────────────────
|
||||
router.post('/edit/:id', async (req, res) => {
|
||||
try {
|
||||
const clId = req.v2_clientId;
|
||||
const company = await q.getOrCreateCompany(clId, clId);
|
||||
const result = await q.updateEntry(parseInt(req.params.id), company.id, req.body.cidr || '', req.body.comment || '', req.v2_email, req.v2_impersonatedBy);
|
||||
const msg = result.wasNormalized ? 'Изменено (адрес нормализован)' : 'Изменено';
|
||||
res.redirect('/v2/app?msg=' + encodeURIComponent(msg));
|
||||
} catch (e) {
|
||||
res.redirect('/v2/app?error=' + encodeURIComponent(e.message));
|
||||
}
|
||||
});
|
||||
|
||||
// ── POST /delete/:id ────────────────────────────────────────────────────
|
||||
router.post('/delete/:id', async (req, res) => {
|
||||
try {
|
||||
const clId = req.v2_clientId;
|
||||
const company = await q.getOrCreateCompany(clId, clId);
|
||||
await q.deleteEntry(parseInt(req.params.id), company.id, req.v2_email, req.v2_impersonatedBy);
|
||||
res.redirect('/v2/app?msg=Удалено');
|
||||
} catch (e) {
|
||||
res.redirect('/v2/app?error=' + encodeURIComponent(e.message));
|
||||
}
|
||||
});
|
||||
|
||||
return router;
|
||||
}
|
||||
|
||||
// ── HTML-рендеринг (временный, будет заменён на EJS) ─────────────────────
|
||||
|
||||
function renderPage({ entries, company, limit, used, allCompanies, clId, user, includeDeleted }) {
|
||||
const companyOptions = allCompanies.map(c =>
|
||||
`<option value="${c.client_id}" ${c.client_id === clId ? 'selected' : ''}>${c.company_name || c.client_id} (${c.client_id})</option>`
|
||||
).join('');
|
||||
|
||||
const rows = entries.map(e => {
|
||||
const del = e.deleted_at;
|
||||
const style = del ? 'text-decoration:line-through;opacity:0.5' : '';
|
||||
const actions = del ? '<span style="color:#888">удалено</span>' : `
|
||||
<form method="POST" action="/v2/app/edit/${e.id}" style="display:inline">
|
||||
<input name="cidr" value="${e.value_cidr}" size="18">
|
||||
<input name="comment" value="${e.comment || ''}" size="20">
|
||||
<button>изменить</button>
|
||||
</form>
|
||||
<form method="POST" action="/v2/app/delete/${e.id}" style="display:inline">
|
||||
<button onclick="return confirm('Удалить?')">удалить</button>
|
||||
</form>`;
|
||||
return `<tr style="${style}"><td>${e.value_cidr}</td><td>${e.comment || ''}</td><td>${e.created_by}</td><td>${new Date(e.created_at).toLocaleString('ru')}</td><td>${actions}</td></tr>`;
|
||||
}).join('');
|
||||
|
||||
return `<!DOCTYPE html>
|
||||
<html><head><meta charset="utf-8"><title>V2 IP WhiteList</title>
|
||||
<style>
|
||||
body{font-family:sans-serif;max-width:960px;margin:20px auto;color:#222}
|
||||
table{width:100%;border-collapse:collapse;margin:10px 0}
|
||||
th,td{border:1px solid #ccc;padding:6px;text-align:left}
|
||||
th{background:#f5f5f5}
|
||||
.bar{display:flex;justify-content:space-between;align-items:center;background:#eee;padding:10px;margin-bottom:10px}
|
||||
button,input,select{padding:4px 8px}
|
||||
.add-form{background:#f0f8ff;padding:10px;margin:10px 0}
|
||||
</style></head><body>
|
||||
<div class="bar">
|
||||
<span><strong>V2 IP WhiteList</strong></span>
|
||||
<span>${user.email} ${user.isAdmin ? '| <a href="/v2/admin">ADMIN</a>' : ''}</span>
|
||||
<span>
|
||||
<form method="GET" action="/v2/app" style="display:inline">
|
||||
<select name="switchTo" onchange="this.form.submit()">${companyOptions}</select>
|
||||
</form>
|
||||
<a href="/v2/logout">Выйти</a>
|
||||
</span>
|
||||
</div>
|
||||
<script>
|
||||
const p=new URLSearchParams(location.search);
|
||||
if(p.get('msg')){document.body.insertAdjacentHTML('afterbegin','<div style="background:#4caf50;color:#fff;padding:8px">'+p.get('msg')+'</div>');history.replaceState(null,'','/v2/app')}
|
||||
if(p.get('error')){document.body.insertAdjacentHTML('afterbegin','<div style="background:#f44336;color:#fff;padding:8px">'+p.get('error')+'</div>');history.replaceState(null,'','/v2/app')}
|
||||
</script>
|
||||
<p>Записей: <strong>${used}</strong> из ${limit}</p>
|
||||
<div class="add-form">
|
||||
<form method="POST" action="/v2/app/add">
|
||||
<input name="cidr" placeholder="x.x.x.x/xx" size="18" required>
|
||||
<input name="comment" placeholder="комментарий" size="30">
|
||||
<button>Добавить</button>
|
||||
</form>
|
||||
</div>
|
||||
<table>
|
||||
<tr><th>CIDR</th><th>Комментарий</th><th>Кто</th><th>Когда</th><th></th></tr>
|
||||
${rows || '<tr><td colspan="5">Нет записей</td></tr>'}
|
||||
</table>
|
||||
<p><a href="/v2/app?deleted=${includeDeleted ? '0' : '1'}">${includeDeleted ? 'Скрыть удалённые' : 'Показать удалённые'}</a></p>
|
||||
</body></html>`;
|
||||
}
|
||||
|
||||
module.exports = { createUserRouter };
|
||||
|
||||
Reference in New Issue
Block a user