v2→main: интеграция — v2 как основной UI (/), старый UI закомментирован
This commit is contained in:
+1
-1
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "ipwhitelist",
|
||||
"version": "0.5.98",
|
||||
"version": "0.5.99",
|
||||
"description": "IP WhiteList microservice for cloud provider",
|
||||
"main": "server.js",
|
||||
"scripts": {
|
||||
|
||||
@@ -137,9 +137,10 @@ async function start() {
|
||||
// Монтируется ПОСЛЕ /api/v1/ — не перехватывает API-запросы.
|
||||
// ── V2 — тестовый роутер (Keycloak → IAM → вывод) ─────────────────
|
||||
const { createV2Router } = require('./v2/server');
|
||||
app.use('/v2', createV2Router());
|
||||
app.use('/', createV2Router());
|
||||
// Хранит Bearer token в сессии, рендерит те же views/*.ejs.
|
||||
app.use('/', createUiRouter({ auth, MOCK_USERS, authLimiter }));
|
||||
// ── Старый UI (заменён на v2) ────────────────────────────────────────
|
||||
// app.use('/', createUiRouter({ auth, MOCK_USERS, authLimiter }));
|
||||
|
||||
// ── Общий обработчик ошибок ───────────────────────────────────────────────
|
||||
// eslint-disable-next-line no-unused-vars
|
||||
|
||||
+13
-13
@@ -5,7 +5,7 @@
|
||||
// ЗАЧЕМ: единственная точка входа v2 в основное приложение.
|
||||
//
|
||||
// МОНТАЖ В ОСНОВНОМ server.js:
|
||||
// const { createV2Router } = require('./v2/server');
|
||||
// const { createV2Router } = require('./server');
|
||||
// app.use('/v2', createV2Router());
|
||||
//
|
||||
// ПОРЯДОК МАРШРУТОВ (важен!):
|
||||
@@ -38,39 +38,39 @@ function createV2Router() {
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
// ── GET /v2/login — редирект на основной вход (KC OIDC) ─────────────
|
||||
// ── GET /login-v2 — редирект на основной вход (KC OIDC) ─────────────
|
||||
router.get('/login', (req, res) => {
|
||||
res.redirect('/login?returnTo=' + encodeURIComponent('/v2/app'));
|
||||
res.redirect('/login?returnTo=' + encodeURIComponent('/app'));
|
||||
});
|
||||
|
||||
// ── GET /v2/iam — отладка: показать IAM-данные из сессии ────────────
|
||||
// ── GET /iam — отладка: показать IAM-данные из сессии ────────────
|
||||
router.get('/iam', (req, res) => {
|
||||
const u = req.session && req.session.user;
|
||||
if (!u) return res.send('<h2>Нет данных</h2><p><a href="/v2/login">Войти</a></p>');
|
||||
if (!u) return res.send('<h2>Нет данных</h2><p><a href="/login-v2">Войти</a></p>');
|
||||
res.send(debugPage(u, config.version));
|
||||
});
|
||||
|
||||
// ── /v2/app — пользовательский CRUD (только с сессией) ──────────────
|
||||
// ── /app — пользовательский CRUD (только с сессией) ──────────────
|
||||
router.use('/app', enhanceImpersonation, resolveContext, createUserRouter());
|
||||
|
||||
// ── /v2/admin — админка (только для isAdmin=true) ────────────────────
|
||||
// ── /admin — админка (только для isAdmin=true) ────────────────────
|
||||
router.use('/admin', enhanceImpersonation, resolveContext, createAdminRouter());
|
||||
|
||||
// ── GET /v2/ — редирект на /v2/app ──────────────────────────────────
|
||||
router.get('/', (req, res) => res.redirect('/v2/app'));
|
||||
// ── GET / — редирект на /app ──────────────────────────────────
|
||||
router.get('/', (req, res) => res.redirect('/app'));
|
||||
|
||||
// ── /v2/test — тестовый API (отключить: ENABLE_TEST_API=false) ──────
|
||||
// ── /test — тестовый API (отключить: ENABLE_TEST_API=false) ──────
|
||||
// Код остаётся, роутер не монтируется при ENABLE_TEST_API=false.
|
||||
if (process.env.ENABLE_TEST_API !== 'false') {
|
||||
const { createTestRouter } = require('./src/test');
|
||||
router.use('/test', createTestRouter());
|
||||
}
|
||||
|
||||
// ── /v2/export — выгрузка CIDR (публичный, без авторизации) ──────
|
||||
// ── /export — выгрузка CIDR (публичный, без авторизации) ──────
|
||||
const { createExportRouter } = require('./src/export');
|
||||
router.use('/export', createExportRouter());
|
||||
|
||||
// ── GET /v2/logout — редирект на основной выход ─────────────────────
|
||||
// ── GET /logout — редирект на основной выход ─────────────────────
|
||||
router.get('/logout', (req, res) => res.redirect('/logout'));
|
||||
|
||||
return router;
|
||||
@@ -88,7 +88,7 @@ function debugPage(u, version) {
|
||||
<p><span class="label">ФИО:</span> ${(u.fio && u.fio.fullName) || u.fio || '—'}</p>
|
||||
<p><span class="label">Компаний:</span> ${u.allClientIds ? u.allClientIds.length : 0} — ${(u.allClientIds || []).join(', ')}</p>
|
||||
<hr><pre>${JSON.stringify(u, null, 2)}</pre>
|
||||
<p><a href="/v2/logout">Выйти</a> | <a href="/v2/app">CRUD</a> | <a href="/v2/admin">Админка</a></p>
|
||||
<p><a href="/logout">Выйти</a> | <a href="/app">CRUD</a> | <a href="/admin">Админка</a></p>
|
||||
</body></html>`;
|
||||
}
|
||||
|
||||
|
||||
@@ -5,9 +5,9 @@
|
||||
// НЕ: доступно обычным юзерам (middleware: req.isAdmin).
|
||||
//
|
||||
// ШАБЛОНЫ:
|
||||
// views/v2/admin.ejs — дашборд (companies, user, version)
|
||||
// views/v2/admin-audit.ejs — аудит (audit, company, version)
|
||||
// views/v2/admin-entries.ejs — записи (entries, company, used, limit, ...)
|
||||
// views/admin.ejs — дашборд (companies, user, version)
|
||||
// views/admin-audit.ejs — аудит (audit, company, version)
|
||||
// views/admin-entries.ejs — записи (entries, company, used, limit, ...)
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
const express = require('express');
|
||||
@@ -19,7 +19,7 @@ function createAdminRouter() {
|
||||
const router = express.Router();
|
||||
|
||||
router.use((req, res, next) => {
|
||||
if (!req.isAdmin) return res.redirect('/v2/app');
|
||||
if (!req.isAdmin) return res.redirect('/app');
|
||||
next();
|
||||
});
|
||||
|
||||
@@ -52,9 +52,9 @@ function createAdminRouter() {
|
||||
const newLimit = parseInt(req.body.limit);
|
||||
if (!companyId || !newLimit || newLimit < 1) throw new Error('Неверные параметры');
|
||||
await q.setLimit(companyId, newLimit);
|
||||
res.redirect('/v2/admin?msg=' + encodeURIComponent('Лимит установлен: ' + newLimit));
|
||||
res.redirect('/admin?msg=' + encodeURIComponent('Лимит установлен: ' + newLimit));
|
||||
} catch (e) {
|
||||
res.redirect('/v2/admin?error=' + encodeURIComponent(e.message));
|
||||
res.redirect('/admin?error=' + encodeURIComponent(e.message));
|
||||
}
|
||||
});
|
||||
|
||||
@@ -63,7 +63,7 @@ function createAdminRouter() {
|
||||
try {
|
||||
const companyId = parseInt(req.query.companyId);
|
||||
const company = companyId ? await q.getCompanyById(companyId) : null;
|
||||
if (!company) return res.redirect('/v2/admin');
|
||||
if (!company) return res.redirect('/admin');
|
||||
const includeDeleted = req.query.deleted === '1';
|
||||
const { entries, used, limit } = await crud.list(company.client_id, includeDeleted);
|
||||
res.render('v2/admin-entries', { entries, company, used, limit, includeDeleted, version: config.version });
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
// ═══════════════════════════════════════════════════════════════════════════════
|
||||
|
||||
module.exports = {
|
||||
version: '0.5.98',
|
||||
version: '0.5.99',
|
||||
|
||||
// ── IAM ──────────────────────────────────────────────────────────────────
|
||||
iamUrl: process.env.V2_IAM_URL || 'https://auth-api.ngcloud.ru/api/v1/auth/user',
|
||||
|
||||
@@ -30,7 +30,7 @@ function resolveContext(req, res, next) {
|
||||
const u = req.session && req.session.user;
|
||||
|
||||
// Нет сессии — нет доступа
|
||||
if (!u) return res.redirect('/v2/login');
|
||||
if (!u) return res.redirect('/login');
|
||||
|
||||
// Имперсонация: админ действует от имени компании
|
||||
// u.originalUserEmail — реальный админ
|
||||
|
||||
@@ -29,7 +29,7 @@ function createUserRouter() {
|
||||
// Переключение компании
|
||||
if (req.query.switchTo && allCompanies.find(c => c.client_id === req.query.switchTo)) {
|
||||
req.session.user.activeClientId = req.query.switchTo;
|
||||
return res.redirect('/v2/app');
|
||||
return res.redirect('/app');
|
||||
}
|
||||
|
||||
res.render('v2/user', {
|
||||
@@ -41,7 +41,7 @@ function createUserRouter() {
|
||||
version: config.version,
|
||||
});
|
||||
} catch (e) {
|
||||
res.status(500).send('<h2>Ошибка</h2><pre>' + e.message + '</pre><a href="/v2/app">Назад</a>');
|
||||
res.status(500).send('<h2>Ошибка</h2><pre>' + e.message + '</pre><a href="/app">Назад</a>');
|
||||
}
|
||||
});
|
||||
|
||||
@@ -50,9 +50,9 @@ function createUserRouter() {
|
||||
try {
|
||||
const result = await crud.add(req.clientId, req.body.cidr || '', req.body.comment || '', req.email, req.impersonatedBy);
|
||||
const msg = result.wasNormalized ? 'Добавлено (адрес нормализован)' : 'Добавлено';
|
||||
res.redirect('/v2/app?msg=' + encodeURIComponent(msg));
|
||||
res.redirect('/app?msg=' + encodeURIComponent(msg));
|
||||
} catch (e) {
|
||||
res.redirect('/v2/app?error=' + encodeURIComponent(e.message));
|
||||
res.redirect('/app?error=' + encodeURIComponent(e.message));
|
||||
}
|
||||
});
|
||||
|
||||
@@ -61,9 +61,9 @@ function createUserRouter() {
|
||||
try {
|
||||
const result = await crud.edit(parseInt(req.params.id), req.clientId, req.body.cidr || '', req.body.comment || '', req.email, req.impersonatedBy);
|
||||
const msg = result.wasNormalized ? 'Изменено (адрес нормализован)' : 'Изменено';
|
||||
res.redirect('/v2/app?msg=' + encodeURIComponent(msg));
|
||||
res.redirect('/app?msg=' + encodeURIComponent(msg));
|
||||
} catch (e) {
|
||||
res.redirect('/v2/app?error=' + encodeURIComponent(e.message));
|
||||
res.redirect('/app?error=' + encodeURIComponent(e.message));
|
||||
}
|
||||
});
|
||||
|
||||
@@ -71,9 +71,9 @@ function createUserRouter() {
|
||||
router.post('/delete/:id', async (req, res) => {
|
||||
try {
|
||||
await crud.remove(parseInt(req.params.id), req.clientId, req.email, req.impersonatedBy);
|
||||
res.redirect('/v2/app?msg=Удалено');
|
||||
res.redirect('/app?msg=Удалено');
|
||||
} catch (e) {
|
||||
res.redirect('/v2/app?error=' + encodeURIComponent(e.message));
|
||||
res.redirect('/app?error=' + encodeURIComponent(e.message));
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
</style></head><body>
|
||||
<div class="bar">
|
||||
<span><strong>📋 Аудит</strong> <%= company ? company.client_id : 'Все компании' %></span>
|
||||
<span><a href="/v2/admin">← Админка</a> | <a href="/v2/app">Пользовательский</a></span>
|
||||
<span><a href="/admin">← Админка</a> | <a href="/app">Пользовательский</a></span>
|
||||
</div>
|
||||
<table>
|
||||
<tr><th>Дата</th><th>Действие</th><th>Кто</th><th>От имени</th><th>Компания</th><th>Значения</th></tr>
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
</style></head><body>
|
||||
<div class="bar">
|
||||
<span><strong>📋 Записи</strong> <%= company.client_id %> — <%= company.name || company.client_id %></span>
|
||||
<span><a href="/v2/admin">← Админка</a></span>
|
||||
<span><a href="/admin">← Админка</a></span>
|
||||
</div>
|
||||
<p>Записей: <strong><%= used %></strong> из <%= limit %> <%= includeDeleted ? '(с удалёнными: ' + entries.length + ')' : '' %></p>
|
||||
<table>
|
||||
|
||||
+6
-6
@@ -13,12 +13,12 @@
|
||||
</style></head><body>
|
||||
<div class="bar">
|
||||
<span><strong>🛡️ ADMIN</strong> v<%= version %></span>
|
||||
<span><%= user.email || '—' %> | <a href="/v2/app">← Пользовательский</a> | <a href="/v2/logout">Выйти</a></span>
|
||||
<span><%= user.email || '—' %> | <a href="/app">← Пользовательский</a> | <a href="/logout">Выйти</a></span>
|
||||
</div>
|
||||
<script>
|
||||
const p=new URLSearchParams(location.search);
|
||||
if(p.get('msg')){document.write('<div class="msg">'+p.get('msg')+'</div>');history.replaceState(null,'','/v2/admin');}
|
||||
if(p.get('error')){document.write('<div class="err">'+p.get('error')+'</div>');history.replaceState(null,'','/v2/admin');}
|
||||
if(p.get('msg')){document.write('<div class="msg">'+p.get('msg')+'</div>');history.replaceState(null,'','/admin');}
|
||||
if(p.get('error')){document.write('<div class="err">'+p.get('error')+'</div>');history.replaceState(null,'','/admin');}
|
||||
</script>
|
||||
<h2>Компании (<%= companies.length %>)</h2>
|
||||
<table>
|
||||
@@ -31,11 +31,11 @@
|
||||
<td><strong><%= c.active_count %></strong> / <%= c.custom_limit != null ? c.custom_limit : 15 %></td>
|
||||
<td><%= c.custom_limit != null ? c.custom_limit : '—' %></td>
|
||||
<td>
|
||||
<a href="/v2/admin/audit?companyId=<%= c.id %>">аудит</a> |
|
||||
<a href="/v2/admin/entries?companyId=<%= c.id %>">записи</a>
|
||||
<a href="/admin/audit?companyId=<%= c.id %>">аудит</a> |
|
||||
<a href="/admin/entries?companyId=<%= c.id %>">записи</a>
|
||||
</td>
|
||||
<td>
|
||||
<form method="POST" action="/v2/admin/limit" style="display:inline">
|
||||
<form method="POST" action="/admin/limit" style="display:inline">
|
||||
<input type="hidden" name="companyId" value="<%= c.id %>">
|
||||
<input name="limit" value="<%= c.custom_limit || 15 %>" size="3">
|
||||
<button>установить</button>
|
||||
|
||||
+9
-9
@@ -11,26 +11,26 @@
|
||||
</style></head><body>
|
||||
<div class="bar">
|
||||
<span><strong>V2 IP WhiteList</strong> <small>v<%= version %></small></span>
|
||||
<span><%= user.email %> <% if (user.isAdmin) { %>| <a href="/v2/admin">ADMIN</a><% } %></span>
|
||||
<span><%= user.email %> <% if (user.isAdmin) { %>| <a href="/admin">ADMIN</a><% } %></span>
|
||||
<span>
|
||||
<form method="GET" action="/v2/app" style="display:inline">
|
||||
<form method="GET" action="/app" style="display:inline">
|
||||
<select name="switchTo" onchange="this.form.submit()">
|
||||
<% companies.forEach(function(c) { %>
|
||||
<option value="<%= c.client_id %>" <%= c.client_id === activeClientId ? 'selected' : '' %>><%= c.company_name || c.client_id %> (<%= c.client_id %>)</option>
|
||||
<% }) %>
|
||||
</select>
|
||||
</form>
|
||||
<a href="/v2/logout">Выйти</a>
|
||||
<a href="/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')}
|
||||
if(p.get('msg')){document.body.insertAdjacentHTML('afterbegin','<div style="background:#4caf50;color:#fff;padding:8px">'+p.get('msg')+'</div>');history.replaceState(null,'','/app')}
|
||||
if(p.get('error')){document.body.insertAdjacentHTML('afterbegin','<div style="background:#f44336;color:#fff;padding:8px">'+p.get('error')+'</div>');history.replaceState(null,'','/app')}
|
||||
</script>
|
||||
<p>Записей: <strong><%= used %></strong> из <%= limit %></p>
|
||||
<div class="add-form">
|
||||
<form method="POST" action="/v2/app/add">
|
||||
<form method="POST" action="/app/add">
|
||||
<input name="cidr" placeholder="x.x.x.x/xx" size="18" required>
|
||||
<input name="comment" placeholder="комментарий" size="30">
|
||||
<button>Добавить</button>
|
||||
@@ -51,12 +51,12 @@
|
||||
<% if (e.deleted_at) { %>
|
||||
<span style="color:#888">удалено</span>
|
||||
<% } else { %>
|
||||
<form method="POST" action="/v2/app/edit/<%= e.id %>" style="display:inline">
|
||||
<form method="POST" action="/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">
|
||||
<form method="POST" action="/app/delete/<%= e.id %>" style="display:inline">
|
||||
<button onclick="return confirm('Удалить?')">удалить</button>
|
||||
</form>
|
||||
<% } %>
|
||||
@@ -64,5 +64,5 @@
|
||||
</tr>
|
||||
<% }) %>
|
||||
</table>
|
||||
<p><a href="/v2/app?deleted=<%= includeDeleted ? '0' : '1' %>"><%= includeDeleted ? 'Скрыть удалённые' : 'Показать удалённые' %></a></p>
|
||||
<p><a href="/app?deleted=<%= includeDeleted ? '0' : '1' %>"><%= includeDeleted ? 'Скрыть удалённые' : 'Показать удалённые' %></a></p>
|
||||
</body></html>
|
||||
|
||||
Reference in New Issue
Block a user