Files
ipwhitelist-app/v2/src/impersonation/index.js
T
2026-06-16 06:41:14 +04:00

61 lines
2.7 KiB
JavaScript

// ═══════════════════════════════════════════════════════════════════════════════
// V2 — Имперсонация (IAM + URL-режим)
//
// ЭТО: middleware — подмена сессии при имперсонации.
// НЕ: жёсткая логика в resolveContext или user/index.js.
//
// IAM-имперсонация: если сессия уже содержит isImpersonated=true → не трогаем.
//
// URL-имперсонация: для разрешённых пользователей (IMPERSONATION_ALLOWED_USERS).
// /v2/app?impersonate=email&company=W***
// Полная подмена сессии: email, clientId, profiles — всё от таргета.
//
// ENV:
// IMP_ALLOWED — emails через запятую (кому можно)
// ═══════════════════════════════════════════════════════════════════════════════
const ALLOWED_USERS = new Set(
(process.env.IMP_ALLOWED || '')
.split(/[\s,/]+/).map(s => s.trim()).filter(Boolean)
);
function enhanceImpersonation(req, res, next) {
const u = req.session && req.session.user;
if (!u) return next();
// ── IAM-имперсонация — уже в сессии, не трогаем ────────────────────
if (u.isImpersonated) return next();
// ── URL-имперсонация ───────────────────────────────────────────────
const targetEmail = req.query.impersonate;
const targetCompany = req.query.company;
if (targetEmail && targetCompany && ALLOWED_USERS.has(u.email)) {
// Сохраняем оригинал
const origEmail = u.email;
const origFio = u.fio;
// Подменяем ВСЕ данные на таргета (как делает IAM)
u.email = targetEmail;
u.clientId = targetCompany;
u.activeClientId = targetCompany;
u.allClientIds = [targetCompany];
u.companyName = targetCompany;
u.isImpersonated = true;
u.originalUserEmail = origEmail;
u.originalUserFullName = origFio ? (origFio.fullName || '') : '';
u.impersonatedCompanyId = targetCompany;
u.fio = null;
u.profiles = [{
client_id: targetCompany,
company_name: targetCompany,
is_active_profile: true,
}];
}
next();
}
module.exports = { enhanceImpersonation };