v2: убраны v2_ префиксы сессии — user/adminMode/token как в основном коде

This commit is contained in:
2026-06-12 21:13:15 +04:00
parent 287d196eaf
commit d3b753e6bd
7 changed files with 35 additions and 35 deletions
+1 -1
View File
@@ -1,6 +1,6 @@
{ {
"name": "ipwhitelist", "name": "ipwhitelist",
"version": "0.5.77", "version": "0.5.78",
"description": "IP WhiteList microservice for cloud provider", "description": "IP WhiteList microservice for cloud provider",
"main": "server.js", "main": "server.js",
"scripts": { "scripts": {
+3 -3
View File
@@ -10,9 +10,9 @@ function createAdminRouter() {
router.get('/', (req, res) => { router.get('/', (req, res) => {
res.send(`<h2>Admin panel</h2> res.send(`<h2>Admin panel</h2>
<p>email: ${req.v2_email}</p> <p>email: ${req.email}</p>
<p>clientId: ${req.v2_clientId}</p> <p>clientId: ${req.clientId}</p>
<p>Все компании: ${(req.v2_allClientIds || []).join(', ') || '—'}</p> <p>Все компании: ${(req.allClientIds || []).join(', ') || '—'}</p>
<p><a href="/v2/app">Пользовательский CRUD</a> | <a href="/v2/logout">Выйти</a></p> <p><a href="/v2/app">Пользовательский CRUD</a> | <a href="/v2/logout">Выйти</a></p>
`); `);
}); });
+1 -1
View File
@@ -6,7 +6,7 @@
// ═══════════════════════════════════════════════════════════════════════════════ // ═══════════════════════════════════════════════════════════════════════════════
module.exports = { module.exports = {
version: '0.5.77', version: '0.5.78',
iamUrl: process.env.V2_IAM_API_URL || 'https://auth-api.ngcloud.ru', iamUrl: process.env.V2_IAM_API_URL || 'https://auth-api.ngcloud.ru',
appUrl: process.env.V2_APP_URL || 'https://whitelist.nodejsk8s.services.ngcloud.ru', appUrl: process.env.V2_APP_URL || 'https://whitelist.nodejsk8s.services.ngcloud.ru',
}; };
+5 -5
View File
@@ -16,17 +16,17 @@ function createCrudRouter() {
// ── middleware: только для залогиненных ───────────────────────────────── // ── middleware: только для залогиненных ─────────────────────────────────
router.use((req, res, next) => { router.use((req, res, next) => {
if (!req.session.v2_user) return res.redirect('/v2/login'); if (!req.session.user) return res.redirect('/v2/login');
next(); next();
}); });
// ── helpers ────────────────────────────────────────────────────────────── // ── helpers ──────────────────────────────────────────────────────────────
function user(req) { return req.session.v2_user; } function user(req) { return req.session.user; }
function token(req) { return req.session.v2_token; } function token(req) { return req.session.token; }
// activeClientId — текущая выбранная компания // activeClientId — текущая выбранная компания
function activeClientId(req) { function activeClientId(req) {
return req.session.v2_user.activeClientId || req.session.v2_user.clientId; return req.session.user.activeClientId || req.session.user.clientId;
} }
// Список компаний для выпадающего списка // Список компаний для выпадающего списка
@@ -51,7 +51,7 @@ function createCrudRouter() {
const switchTo = req.query.switchTo; const switchTo = req.query.switchTo;
if (switchTo && allCompanies.find(c => c.client_id === switchTo)) { if (switchTo && allCompanies.find(c => c.client_id === switchTo)) {
req.session.v2_user.activeClientId = switchTo; req.session.user.activeClientId = switchTo;
return res.redirect('/v2/app'); return res.redirect('/v2/app');
} }
+3 -3
View File
@@ -8,10 +8,10 @@
* Вызывается перед всеми маршрутами v2. * Вызывается перед всеми маршрутами v2.
*/ */
function resolveContext(req, res, next) { function resolveContext(req, res, next) {
let u = req.session && req.session.v2_user; const u = req.session && req.session.user;
if (!u) return res.redirect('/v2/login'); if (!u) return res.redirect('/v2/login');
const isAdmin = !!(u.isAdmin && req.session.v2_adminMode); const isAdmin = !!(u.isAdmin && req.session.adminMode);
const isImpersonated = !!u.isImpersonated; const isImpersonated = !!u.isImpersonated;
// Контекст для CRUD // Контекст для CRUD
@@ -20,7 +20,7 @@ function resolveContext(req, res, next) {
req.v2_isAdmin = isAdmin; req.v2_isAdmin = isAdmin;
req.v2_isImpersonated = isImpersonated; req.v2_isImpersonated = isImpersonated;
req.v2_impersonatedBy = isImpersonated ? u.email : null; // кто реально (для аудита) req.v2_impersonatedBy = isImpersonated ? u.email : null; // кто реально (для аудита)
req.v2_user = u; req.user = u;
req.v2_allClientIds = u.allClientIds || []; req.v2_allClientIds = u.allClientIds || [];
req.v2_profiles = u.profiles || []; req.v2_profiles = u.profiles || [];
req.v2_companyName = u.companyName || u.clientId; req.v2_companyName = u.companyName || u.clientId;
+10 -10
View File
@@ -21,41 +21,41 @@ function t(name, session, expected) {
} }
t('нет сессии', {}, { _redirect: '/v2/login' }); t('нет сессии', {}, { _redirect: '/v2/login' });
t('нет v2_user', { v2_user: null }, { _redirect: '/v2/login' }); t('нет user', { user: null }, { _redirect: '/v2/login' });
t('обычный юзер 1 компания', { v2_user: { t('обычный юзер 1 компания', { user: {
email: 'u@t.ru', clientId: 'WZ03709', activeClientId: 'WZ03709', email: 'u@t.ru', clientId: 'WZ03709', activeClientId: 'WZ03709',
allClientIds: ['WZ03709'], companyName: 'test', isAdmin: false, profiles: [] allClientIds: ['WZ03709'], companyName: 'test', isAdmin: false, profiles: []
}}, { 'v2_email': 'u@t.ru', 'v2_clientId': 'WZ03709', 'v2_isAdmin': false, 'v2_isImpersonated': false, 'v2_impersonatedBy': null }); }}, { 'v2_email': 'u@t.ru', 'v2_clientId': 'WZ03709', 'v2_isAdmin': false, 'v2_isImpersonated': false, 'v2_impersonatedBy': null });
t('юзер 2 компании', { v2_user: { t('юзер 2 компании', { user: {
email: 'm@t.ru', clientId: 'WZ88888', activeClientId: 'WZ77777', email: 'm@t.ru', clientId: 'WZ88888', activeClientId: 'WZ77777',
allClientIds: ['WZ88888','WZ77777'], companyName: 'AB', isAdmin: false, profiles: [] allClientIds: ['WZ88888','WZ77777'], companyName: 'AB', isAdmin: false, profiles: []
}}, { 'v2_email': 'm@t.ru', 'v2_clientId': 'WZ77777', 'v2_allClientIds': ['WZ88888','WZ77777'] }); }}, { 'v2_email': 'm@t.ru', 'v2_clientId': 'WZ77777', 'v2_allClientIds': ['WZ88888','WZ77777'] });
t('админ adminMode', { v2_user: { t('админ adminMode', { user: {
email: 'a@t.ru', clientId: 'WZ01112', activeClientId: 'WZ01112', email: 'a@t.ru', clientId: 'WZ01112', activeClientId: 'WZ01112',
allClientIds: ['WZ01112'], isAdmin: true, profiles: [] allClientIds: ['WZ01112'], isAdmin: true, profiles: []
}, v2_adminMode: true }, { 'v2_email': 'a@t.ru', 'v2_clientId': 'WZ01112', 'v2_isAdmin': true }); }, adminMode: true }, { 'v2_email': 'a@t.ru', 'v2_clientId': 'WZ01112', 'v2_isAdmin': true });
t('админ без adminMode', { v2_user: { t('админ без adminMode', { user: {
email: 'a@t.ru', clientId: 'WZ01112', activeClientId: 'WZ01112', email: 'a@t.ru', clientId: 'WZ01112', activeClientId: 'WZ01112',
allClientIds: ['WZ01112'], isAdmin: true, profiles: [] allClientIds: ['WZ01112'], isAdmin: true, profiles: []
} }, { 'v2_email': 'a@t.ru', 'v2_clientId': 'WZ01112', 'v2_isAdmin': false }); } }, { 'v2_email': 'a@t.ru', 'v2_clientId': 'WZ01112', 'v2_isAdmin': false });
t('имперсонация', { v2_user: { t('имперсонация', { user: {
email: 'admin@t.ru', clientId: 'WZ01112', activeClientId: 'WZ01112', email: 'admin@t.ru', clientId: 'WZ01112', activeClientId: 'WZ01112',
allClientIds: ['WZ01112','WZ03709'], isAdmin: true, isImpersonated: true, allClientIds: ['WZ01112','WZ03709'], isAdmin: true, isImpersonated: true,
originalUserEmail: 'real@t.ru', impersonatedCompanyId: 'WZ03709', profiles: [] originalUserEmail: 'real@t.ru', impersonatedCompanyId: 'WZ03709', profiles: []
}, v2_adminMode: true }, { 'v2_email': 'real@t.ru', 'v2_clientId': 'WZ03709', 'v2_isImpersonated': true, 'v2_impersonatedBy': 'admin@t.ru' }); }, adminMode: true }, { 'v2_email': 'real@t.ru', 'v2_clientId': 'WZ03709', 'v2_isImpersonated': true, 'v2_impersonatedBy': 'admin@t.ru' });
t('имперс. без origEmail', { v2_user: { t('имперс. без origEmail', { user: {
email: 'x@t.ru', clientId: 'WZ01112', activeClientId: 'WZ01112', email: 'x@t.ru', clientId: 'WZ01112', activeClientId: 'WZ01112',
allClientIds: ['WZ01112'], isAdmin: true, isImpersonated: true, allClientIds: ['WZ01112'], isAdmin: true, isImpersonated: true,
originalUserEmail: '', impersonatedCompanyId: '', profiles: [] originalUserEmail: '', impersonatedCompanyId: '', profiles: []
} }, { 'v2_email': 'x@t.ru', 'v2_clientId': 'WZ01112', 'v2_impersonatedBy': 'x@t.ru' }); } }, { 'v2_email': 'x@t.ru', 'v2_clientId': 'WZ01112', 'v2_impersonatedBy': 'x@t.ru' });
t('без activeClientId', { v2_user: { t('без activeClientId', { user: {
email: 'y@t.ru', clientId: 'WZ03709', allClientIds: ['WZ03709'], email: 'y@t.ru', clientId: 'WZ03709', allClientIds: ['WZ03709'],
isAdmin: false, profiles: [] isAdmin: false, profiles: []
} }, { 'v2_email': 'y@t.ru', 'v2_clientId': 'WZ03709' }); } }, { 'v2_email': 'y@t.ru', 'v2_clientId': 'WZ03709' });
+12 -12
View File
@@ -13,10 +13,10 @@ function createUserRouter() {
// ── GET / — главная: список записей + форма ──────────────────────────── // ── GET / — главная: список записей + форма ────────────────────────────
router.get('/', async (req, res) => { router.get('/', async (req, res) => {
try { try {
const clId = req.v2_clientId; const clId = req.clientId;
const allCompanies = req.v2_profiles.length > 0 const allCompanies = req.profiles.length > 0
? req.v2_profiles ? req.profiles
: [{ client_id: clId, company_name: req.v2_companyName || clId }]; : [{ client_id: clId, company_name: req.companyName || clId }];
const company = await q.getOrCreateCompany(clId, allCompanies.find(c => c.client_id === clId)?.company_name || clId); const company = await q.getOrCreateCompany(clId, allCompanies.find(c => c.client_id === clId)?.company_name || clId);
const includeDeleted = req.query.deleted === '1'; const includeDeleted = req.query.deleted === '1';
@@ -26,11 +26,11 @@ function createUserRouter() {
// Переключение компании // Переключение компании
if (req.query.switchTo && allCompanies.find(c => c.client_id === req.query.switchTo)) { if (req.query.switchTo && allCompanies.find(c => c.client_id === req.query.switchTo)) {
req.session.v2_user.activeClientId = req.query.switchTo; req.session.user.activeClientId = req.query.switchTo;
return res.redirect('/v2/app'); return res.redirect('/v2/app');
} }
res.send(renderPage({ entries, company, limit, used, allCompanies, clId, user: req.v2_user, includeDeleted })); res.send(renderPage({ entries, company, limit, used, allCompanies, clId, user: req.user, includeDeleted }));
} catch (e) { } 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="/v2/app">Назад</a>');
} }
@@ -39,9 +39,9 @@ function createUserRouter() {
// ── POST /add ─────────────────────────────────────────────────────────── // ── POST /add ───────────────────────────────────────────────────────────
router.post('/add', async (req, res) => { router.post('/add', async (req, res) => {
try { try {
const clId = req.v2_clientId; const clId = req.clientId;
const company = await q.getOrCreateCompany(clId, clId); 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 result = await q.createEntry(company.id, req.body.cidr || '', req.body.comment || '', req.email, req.impersonatedBy);
const msg = result.wasNormalized ? 'Добавлено (адрес нормализован)' : 'Добавлено'; const msg = result.wasNormalized ? 'Добавлено (адрес нормализован)' : 'Добавлено';
res.redirect('/v2/app?msg=' + encodeURIComponent(msg)); res.redirect('/v2/app?msg=' + encodeURIComponent(msg));
} catch (e) { } catch (e) {
@@ -52,9 +52,9 @@ function createUserRouter() {
// ── POST /edit/:id ────────────────────────────────────────────────────── // ── POST /edit/:id ──────────────────────────────────────────────────────
router.post('/edit/:id', async (req, res) => { router.post('/edit/:id', async (req, res) => {
try { try {
const clId = req.v2_clientId; const clId = req.clientId;
const company = await q.getOrCreateCompany(clId, clId); 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 result = await q.updateEntry(parseInt(req.params.id), company.id, req.body.cidr || '', req.body.comment || '', req.email, req.impersonatedBy);
const msg = result.wasNormalized ? 'Изменено (адрес нормализован)' : 'Изменено'; const msg = result.wasNormalized ? 'Изменено (адрес нормализован)' : 'Изменено';
res.redirect('/v2/app?msg=' + encodeURIComponent(msg)); res.redirect('/v2/app?msg=' + encodeURIComponent(msg));
} catch (e) { } catch (e) {
@@ -65,9 +65,9 @@ function createUserRouter() {
// ── POST /delete/:id ──────────────────────────────────────────────────── // ── POST /delete/:id ────────────────────────────────────────────────────
router.post('/delete/:id', async (req, res) => { router.post('/delete/:id', async (req, res) => {
try { try {
const clId = req.v2_clientId; const clId = req.clientId;
const company = await q.getOrCreateCompany(clId, clId); const company = await q.getOrCreateCompany(clId, clId);
await q.deleteEntry(parseInt(req.params.id), company.id, req.v2_email, req.v2_impersonatedBy); await q.deleteEntry(parseInt(req.params.id), company.id, req.email, req.impersonatedBy);
res.redirect('/v2/app?msg=Удалено'); res.redirect('/v2/app?msg=Удалено');
} catch (e) { } catch (e) {
res.redirect('/v2/app?error=' + encodeURIComponent(e.message)); res.redirect('/v2/app?error=' + encodeURIComponent(e.message));