Compare commits
71
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
24fb8cdc56 | ||
|
|
710dcfc7c9 | ||
|
|
c50ef814e2 | ||
|
|
30001062d4 | ||
|
|
92f0314a20 | ||
|
|
fa75f8317d | ||
|
|
90b6c509c0 | ||
|
|
102f4279dc | ||
|
|
b7e62f0468 | ||
|
|
7f8aae0d62 | ||
|
|
6899bc40d3 | ||
|
|
9f44281f9f | ||
|
|
e68e1a483c | ||
|
|
4cd1ab8c8e | ||
|
|
10b890437d | ||
|
|
b24cd75a9e | ||
|
|
df0dd73451 | ||
|
|
8f9fc4e3ee | ||
|
|
9e3ba1c97c | ||
|
|
eba1b4974e | ||
|
|
8deea87996 | ||
|
|
a6d64e1e6c | ||
|
|
795a41496f | ||
|
|
08abab6e36 | ||
|
|
0e1f34c913 | ||
|
|
24e0e39782 | ||
|
|
c4d592dcbe | ||
|
|
86a39c7881 | ||
|
|
f0743c6bfe | ||
|
|
c5cd577561 | ||
|
|
5941899c9c | ||
|
|
ecf6638683 | ||
|
|
e440700a72 | ||
|
|
b41af5649f | ||
|
|
bf72cb49fc | ||
|
|
235da375c4 | ||
|
|
6660cb3c77 | ||
|
|
ee0cf68fe3 | ||
|
|
3493d45065 | ||
|
|
e2aaf3f425 | ||
|
|
f215fa8e32 | ||
|
|
6b994d0938 | ||
|
|
08e20c10ac | ||
|
|
1b043713a9 | ||
|
|
799406df78 | ||
|
|
bde68c00a1 | ||
|
|
02abab93d7 | ||
|
|
2233d3f94d | ||
|
|
cb1e4fac22 | ||
|
|
dc1f629560 | ||
|
|
b640e9e8e7 | ||
|
|
afcfc1420e | ||
|
|
07356acadc | ||
|
|
b04ef35b13 | ||
|
|
394c778f46 | ||
|
|
f5ee0a36de | ||
|
|
8fe89f3a0a | ||
|
|
6bff095a67 | ||
|
|
9ca0d087de | ||
|
|
11c3817376 | ||
|
|
ebcdb1ccb1 | ||
|
|
eb3c17cd68 | ||
|
|
eb7788235f | ||
|
|
8ab0bb10ac | ||
|
|
2545bc97f1 | ||
|
|
f00b7f3e87 | ||
|
|
a31b3e61f2 | ||
|
|
2f151f4cdf | ||
|
|
2e89a71afa | ||
|
|
9eba8859cf | ||
|
|
7fa6b43562 |
@@ -0,0 +1,83 @@
|
|||||||
|
# IAM Impersonation API
|
||||||
|
|
||||||
|
> Источник: Swagger `https://auth-api-dev.ngcloud.ru/api/v1/documentation/`
|
||||||
|
> Дата: 2026-06-16
|
||||||
|
|
||||||
|
## Все эндпоинты имперсонации
|
||||||
|
|
||||||
|
| Метод | Путь | Описание |
|
||||||
|
|-------|------|----------|
|
||||||
|
| `POST` | `/api/v1/impersonation/start` | Начать имперсонацию |
|
||||||
|
| `POST` | `/api/v1/impersonation/end` | Завершить имперсонацию |
|
||||||
|
| `POST` | `/api/v1/impersonation/extend` | Продлить сессию имперсонации |
|
||||||
|
| `GET` | `/api/v1/impersonation/status` | Статус текущей имперсонации |
|
||||||
|
| `GET` | `/api/v1/impersonation/history` | История своих имперсонаций |
|
||||||
|
| `GET` | `/api/v1/impersonation/history/all` | История имперсонаций всех админов |
|
||||||
|
|
||||||
|
## Формат ImpersonationStartRequest
|
||||||
|
|
||||||
|
```json
|
||||||
|
{
|
||||||
|
"type": "user",
|
||||||
|
"entity_id": "UUID контакта (contactId из userInfo)",
|
||||||
|
"reason": "описание причины"
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
- `entity_id` — **UUID таргета** (кого имперсонируем), не свой
|
||||||
|
- `type` — всегда `"user"`
|
||||||
|
|
||||||
|
## curl-команды
|
||||||
|
|
||||||
|
### Начать имперсонацию
|
||||||
|
|
||||||
|
```bash
|
||||||
|
curl --http2 -X POST \
|
||||||
|
-H "Authorization: Bearer $TOKEN" \
|
||||||
|
-H "Content-Type: application/json" \
|
||||||
|
-H "Accept: application/json" \
|
||||||
|
"https://auth-api.ngcloud.ru/api/v1/impersonation/start" \
|
||||||
|
-d '{"type":"user","entity_id":"UUID_таргета","reason":"тест"}'
|
||||||
|
```
|
||||||
|
|
||||||
|
### Статус
|
||||||
|
|
||||||
|
```bash
|
||||||
|
curl --http2 \
|
||||||
|
-H "Authorization: Bearer $TOKEN" \
|
||||||
|
-H "Accept: application/json" \
|
||||||
|
"https://auth-api.ngcloud.ru/api/v1/impersonation/status"
|
||||||
|
```
|
||||||
|
|
||||||
|
### История
|
||||||
|
|
||||||
|
```bash
|
||||||
|
curl --http2 \
|
||||||
|
-H "Authorization: Bearer $TOKEN" \
|
||||||
|
-H "Accept: application/json" \
|
||||||
|
"https://auth-api.ngcloud.ru/api/v1/impersonation/history"
|
||||||
|
```
|
||||||
|
|
||||||
|
### Продлить
|
||||||
|
|
||||||
|
```bash
|
||||||
|
curl --http2 -X POST \
|
||||||
|
-H "Authorization: Bearer $TOKEN" \
|
||||||
|
-H "Accept: application/json" \
|
||||||
|
"https://auth-api.ngcloud.ru/api/v1/impersonation/extend"
|
||||||
|
```
|
||||||
|
|
||||||
|
### Завершить
|
||||||
|
|
||||||
|
```bash
|
||||||
|
curl --http2 -X POST \
|
||||||
|
-H "Authorization: Bearer $TOKEN" \
|
||||||
|
-H "Accept: application/json" \
|
||||||
|
"https://auth-api.ngcloud.ru/api/v1/impersonation/end"
|
||||||
|
```
|
||||||
|
|
||||||
|
## Примечания
|
||||||
|
|
||||||
|
- Требуется роль IAM-админа или право на объект `impersonation`
|
||||||
|
- `--http2` обязателен для обхода ddos-guard
|
||||||
|
- Стенды: `auth-api.ngcloud.ru` (prod), `auth-api-test.ngcloud.ru` (test), `auth-api-dev.ngcloud.ru` (dev)
|
||||||
@@ -0,0 +1,76 @@
|
|||||||
|
# Баг: переключение компании — таблица IP не обновляется
|
||||||
|
|
||||||
|
## Симптом
|
||||||
|
GET /v2/app?switchTo=WZ30001 → таблица показывает записи старой компании.
|
||||||
|
|
||||||
|
## Найденная причина №1 (основная)
|
||||||
|
Порядок кода в `v2/src/user/index.js`:
|
||||||
|
|
||||||
|
```js
|
||||||
|
// 1. clId = req.clientId ← resolveContext выставил СТАРЫЙ activeClientId
|
||||||
|
const clId = req.clientId;
|
||||||
|
|
||||||
|
// 2. crud.list() по СТАРОМУ clId — ещё до switchTo
|
||||||
|
const { entries, used, limit } = await crud.list(clId, includeDeleted);
|
||||||
|
|
||||||
|
// 3. Потом switchTo обновляет сессию и делает redirect
|
||||||
|
if (req.query.switchTo) {
|
||||||
|
req.session.user.activeClientId = targetId;
|
||||||
|
return req.session.save(() => res.redirect('/v2/app'));
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Итог: первый запрос с ?switchTo загружает записи СТАРОЙ компании.
|
||||||
|
Второй запрос (редирект /v2/app) должен уже использовать новый activeClientId — если ничто его не затирает.
|
||||||
|
|
||||||
|
## Найденная причина №2 (если ENV заданы)
|
||||||
|
`v2/src/impersonation/index.js` — при тестовом режиме (IMPERSONATION_TARGET задан):
|
||||||
|
|
||||||
|
```js
|
||||||
|
u.activeClientId = MAIN_COMPANY; // ← затирает то что записал switchTo
|
||||||
|
```
|
||||||
|
|
||||||
|
Middleware запускается при КАЖДОМ запросе (включая редирект после switchTo)
|
||||||
|
и сбрасывает activeClientId обратно в IMPERSONATION_COMPANY.
|
||||||
|
|
||||||
|
## Что проверить
|
||||||
|
```bash
|
||||||
|
echo $IMPERSONATION_COMPANY
|
||||||
|
echo $IMPERSONATION_TARGET
|
||||||
|
echo $IMPERSONATION_ORIGINAL
|
||||||
|
```
|
||||||
|
|
||||||
|
Если заданы → причина №2 (middleware затирает сессию).
|
||||||
|
Если не заданы → причина №1 (но тогда второй запрос после редиректа должен работать).
|
||||||
|
|
||||||
|
## Фикс причины №1
|
||||||
|
В `v2/src/user/index.js` — переставить проверку switchTo ПЕРЕД crud.list():
|
||||||
|
|
||||||
|
```js
|
||||||
|
// Сначала switchTo
|
||||||
|
if (req.query.switchTo) {
|
||||||
|
const targetId = req.query.switchTo;
|
||||||
|
const allowed = isAdmin || (req.profiles || []).find(p => p.client_id === targetId);
|
||||||
|
if (allowed) {
|
||||||
|
req.session.user.activeClientId = targetId;
|
||||||
|
return req.session.save(err => {
|
||||||
|
if (err) console.error('[switchTo] save error:', err.message);
|
||||||
|
res.redirect('/v2/app');
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Потом загружать записи
|
||||||
|
const { entries, used, limit } = await crud.list(clId, includeDeleted);
|
||||||
|
```
|
||||||
|
|
||||||
|
## Фикс причины №2
|
||||||
|
В `v2/src/impersonation/index.js` — не перезаписывать activeClientId если он уже есть:
|
||||||
|
|
||||||
|
```js
|
||||||
|
// Вместо:
|
||||||
|
u.activeClientId = MAIN_COMPANY;
|
||||||
|
|
||||||
|
// Сделать:
|
||||||
|
u.activeClientId = u.activeClientId || MAIN_COMPANY;
|
||||||
|
```
|
||||||
@@ -195,6 +195,10 @@ IAM (Identity & Access Management) — сервис авторизации эк
|
|||||||
| 04.06.2026 | **IAM API — источник компаний.** `GET /auth/user` → `profiles[]`. `isAdmin` из `userInfo.isAdmin`. Переключение через `POST /switch-profile`. |
|
| 04.06.2026 | **IAM API — источник компаний.** `GET /auth/user` → `profiles[]`. `isAdmin` из `userInfo.isAdmin`. Переключение через `POST /switch-profile`. |
|
||||||
| 04.06.2026 | ddos-guard: curl требует `--http2`, Node.js работает |
|
| 04.06.2026 | ddos-guard: curl требует `--http2`, Node.js работает |
|
||||||
|
|
||||||
|
| 16.06.2026 | **UI: кнопка Показать/Скрыть удалённые.** Вместо чекбокса — кнопка-переключатель. |
|
||||||
|
| 16.06.2026 | **UI: восстановление удалённых записей.** Кнопка ↺ у удалённых, `POST /restore/:id`. Лимит проверяется. Аудит: RESTORE. |
|
||||||
|
| 16.06.2026 | **UI: время МСК.** `toLocaleString('ru', {timeZone:'Europe/Moscow'})` + метка «МСК». |
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
## Легенда статусов
|
## Легенда статусов
|
||||||
|
|||||||
+1
-1
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "ipwhitelist",
|
"name": "ipwhitelist",
|
||||||
"version": "0.5.98",
|
"version": "0.5.150",
|
||||||
"description": "IP WhiteList microservice for cloud provider",
|
"description": "IP WhiteList microservice for cloud provider",
|
||||||
"main": "server.js",
|
"main": "server.js",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
|
|||||||
@@ -136,6 +136,8 @@ async function start() {
|
|||||||
// ── UI-слой: SSR через EJS, данные из /api/v1/* ───────────────────────────
|
// ── UI-слой: SSR через EJS, данные из /api/v1/* ───────────────────────────
|
||||||
// Монтируется ПОСЛЕ /api/v1/ — не перехватывает API-запросы.
|
// Монтируется ПОСЛЕ /api/v1/ — не перехватывает API-запросы.
|
||||||
// ── V2 — тестовый роутер (Keycloak → IAM → вывод) ─────────────────
|
// ── V2 — тестовый роутер (Keycloak → IAM → вывод) ─────────────────
|
||||||
|
// Редирект корня на V2
|
||||||
|
app.get('/', (req, res) => res.redirect('/v2/app'));
|
||||||
const { createV2Router } = require('./v2/server');
|
const { createV2Router } = require('./v2/server');
|
||||||
app.use('/v2', createV2Router());
|
app.use('/v2', createV2Router());
|
||||||
// Хранит Bearer token в сессии, рендерит те же views/*.ejs.
|
// Хранит Bearer token в сессии, рендерит те же views/*.ejs.
|
||||||
|
|||||||
+1
-1
@@ -13,7 +13,7 @@
|
|||||||
// ── IAM API ───────────────────────────────────────────────────────────────────
|
// ── IAM API ───────────────────────────────────────────────────────────────────
|
||||||
// URL IAM-сервиса для получения профилей пользователя (GET /api/v1/auth/user)
|
// URL IAM-сервиса для получения профилей пользователя (GET /api/v1/auth/user)
|
||||||
// и переключения активной компании (POST /api/v1/user/switch-profile).
|
// и переключения активной компании (POST /api/v1/user/switch-profile).
|
||||||
const IAM_API_URL = (process.env.IAM_API_URL || 'https://auth-api-dev.ngcloud.ru').replace(/\/$/, '');
|
const IAM_API_URL = (process.env.IAM_API_URL || 'https://auth-api.ngcloud.ru').replace(/\/$/, '');
|
||||||
|
|
||||||
// ── Мок-пользователи (только dev/staging) ─────────────────────────────────────
|
// ── Мок-пользователи (только dev/staging) ─────────────────────────────────────
|
||||||
// В продакшене этот список не используется — вход через Keycloak.
|
// В продакшене этот список не используется — вход через Keycloak.
|
||||||
|
|||||||
@@ -26,6 +26,7 @@ const CSP_DIRECTIVES = {
|
|||||||
defaultSrc: ["'self'"],
|
defaultSrc: ["'self'"],
|
||||||
// 'unsafe-inline' нужен пока стили и скрипты inline в EJS.
|
// 'unsafe-inline' нужен пока стили и скрипты inline в EJS.
|
||||||
scriptSrc: ["'self'", "'unsafe-inline'"],
|
scriptSrc: ["'self'", "'unsafe-inline'"],
|
||||||
|
scriptSrcAttr: ["'unsafe-inline'"], // для onchange/onclick в EJS
|
||||||
styleSrc: ["'self'", "'unsafe-inline'"],
|
styleSrc: ["'self'", "'unsafe-inline'"],
|
||||||
imgSrc: ["'self'", 'data:'], // data: для SVG-иконок
|
imgSrc: ["'self'", 'data:'], // data: для SVG-иконок
|
||||||
fontSrc: ["'self'"],
|
fontSrc: ["'self'"],
|
||||||
|
|||||||
+2
-1
@@ -74,6 +74,7 @@ function createRouter({ auth, doubleCsrfProtection, generateCsrfToken, authLimit
|
|||||||
isAdmin: iamData.isAdmin,
|
isAdmin: iamData.isAdmin,
|
||||||
isImpersonated: iamData.isImpersonated,
|
isImpersonated: iamData.isImpersonated,
|
||||||
impersonationType: iamData.impersonationType,
|
impersonationType: iamData.impersonationType,
|
||||||
|
impersonatedCompanyId: iamData.impersonatedCompanyId,
|
||||||
originalUserEmail: iamData.originalUserEmail,
|
originalUserEmail: iamData.originalUserEmail,
|
||||||
originalUserFullName: iamData.originalUserFullName,
|
originalUserFullName: iamData.originalUserFullName,
|
||||||
originalUserCompany: iamData.originalUserCompany,
|
originalUserCompany: iamData.originalUserCompany,
|
||||||
@@ -99,7 +100,7 @@ function createRouter({ auth, doubleCsrfProtection, generateCsrfToken, authLimit
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
const returnTo = safeLocal(req.session.oidcReturnTo) || '/';
|
const returnTo = '/v2/app';
|
||||||
delete req.session.oidcReturnTo;
|
delete req.session.oidcReturnTo;
|
||||||
res.redirect(returnTo);
|
res.redirect(returnTo);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
|
|||||||
@@ -0,0 +1,30 @@
|
|||||||
|
# V2 Unified Interface — v0.5.102 (2026-06-15)
|
||||||
|
|
||||||
|
**Что сделано:** объединение юзерского и админского интерфейсов в один `/v2/app`.
|
||||||
|
|
||||||
|
## Изменённые файлы
|
||||||
|
|
||||||
|
### `v2/src/user/index.js` — единый роутер
|
||||||
|
- GET `/` — для юзеров и админов
|
||||||
|
- Админ: dropdown = все компании из БД (`getAllCompanies()`), по умолчанию своя
|
||||||
|
- Юзер: dropdown = свои профили из IAM, по умолчанию активный
|
||||||
|
- `?switchTo=W***` — смена компании: админ → любая, юзер → только свои
|
||||||
|
- CRUD без изменений (add/edit/delete через `req.clientId`)
|
||||||
|
|
||||||
|
### `views/v2/user.ejs` — единый шаблон
|
||||||
|
- Дизайн из оригинала: лого Nubes, CSS-переменные, card-раскладка
|
||||||
|
- Хедер: лого | "IP WhiteList v{VERSION}" | email (админ) | Выйти (реальный юзер)
|
||||||
|
- Dropdown компаний + таблица IP с inline CRUD
|
||||||
|
- Статистика, форма добавления, поддержка удалённых записей
|
||||||
|
|
||||||
|
### `v2/server.js`
|
||||||
|
- `/v2/admin` → 302 на `/v2/app`
|
||||||
|
- `toggle-admin` → всегда редирект на `/v2/app`
|
||||||
|
- Убран импорт `createAdminRouter`
|
||||||
|
|
||||||
|
### Версии
|
||||||
|
- `v2/src/config/index.js`: 0.5.98 → 0.5.99
|
||||||
|
- `package.json`: 0.5.101 → 0.5.102
|
||||||
|
|
||||||
|
## Синтаксис
|
||||||
|
`node -c` — OK на всех изменённых файлах.
|
||||||
@@ -0,0 +1,53 @@
|
|||||||
|
# V2 Unified Architecture — v0.5.105 (2026-06-15)
|
||||||
|
|
||||||
|
## Как устроено
|
||||||
|
|
||||||
|
```
|
||||||
|
/v2/app — единый интерфейс
|
||||||
|
│
|
||||||
|
├── Юзер (isAdmin=false)
|
||||||
|
│ └── dropdown: свои компании из IAM (profiles[])
|
||||||
|
│
|
||||||
|
├── Админ (WZ01112, isAdmin=true)
|
||||||
|
│ ├── dropdown: все компании из БД
|
||||||
|
│ ├── свои помечены (личное)
|
||||||
|
│ └── email помечен (админ)
|
||||||
|
│
|
||||||
|
└── CRUD — одинаковый для обоих
|
||||||
|
└── crud.list/add/edit/remove(clientId)
|
||||||
|
```
|
||||||
|
|
||||||
|
## Слои
|
||||||
|
|
||||||
|
| Слой | Файл | Что |
|
||||||
|
|------|------|-----|
|
||||||
|
| CRUD API | `v2/src/crud/index.js` | Чистые функции, clientId → БД |
|
||||||
|
| SQL | `v2/src/db/queries.js` | Все запросы, транзакции |
|
||||||
|
| Роутер | `v2/src/user/index.js` | Express, сессия → crud |
|
||||||
|
| Шаблон | `views/v2/user.ejs` | EJS, единый для всех |
|
||||||
|
|
||||||
|
## Компании
|
||||||
|
|
||||||
|
- `clientId` (W-номер) → `company_id` (внутренний PK) через `getOrCreateCompany`
|
||||||
|
- По умолчанию: активный профиль из IAM (`is_active_profile=true`)
|
||||||
|
- Админ может переключиться на любую компанию (`?switchTo=W***`)
|
||||||
|
- Юзер — только на свои
|
||||||
|
|
||||||
|
## История версий (новые сверху)
|
||||||
|
|
||||||
|
- **0.5.139** — ширина столбцов: CIDR 125px, комментарий широкий, Правка вместо Редактирование
|
||||||
|
- **0.5.138** — CSP script-src-attr 'unsafe-inline' → onchange заработал
|
||||||
|
- **0.5.137** — onchange + console.log для проверки
|
||||||
|
- **0.5.136** — ↺ зелёная, deleted сохраняется после restore/delete
|
||||||
|
- **0.5.135** — UI таблицы: разделение столбцов, 💾, размеры
|
||||||
|
- **0.5.134** — восстановление записей (restore), кнопка удалённых, время МСК
|
||||||
|
- **0.5.133** — type=submit на кнопке удаления
|
||||||
|
- **0.5.132** — ADMIN_EMAIL в resolveContext для всех
|
||||||
|
- **0.5.131** — isAdmin при имперсонации по ADMIN_EMAIL
|
||||||
|
- **0.5.130** — имперсонация не сохраняет isAdmin от оригинала
|
||||||
|
- **0.5.129** — кнопка Выбрать, убран debug
|
||||||
|
- **0.5.127** — clId обновляется после switchTo (фикс бага)
|
||||||
|
- **0.5.105** — убран toggle Администратор
|
||||||
|
- **0.5.104** — (личное) у своих компаний в dropdown
|
||||||
|
- **0.5.103** — WZ01112: adminMode auto-on
|
||||||
|
- **0.5.102** — единый интерфейс /v2/app (юзер+админ)
|
||||||
+184
-2
@@ -50,10 +50,85 @@ function createV2Router() {
|
|||||||
res.send(debugPage(u, config.version));
|
res.send(debugPage(u, config.version));
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// ── GET /v2/iam_response — сырой ответ IAM ─────────────────────────
|
||||||
|
router.get('/iam_response', async (req, res) => {
|
||||||
|
const token = req.session && req.session.token;
|
||||||
|
if (!token) return res.send('<h2>Нет токена</h2><p><a href="/v2/login">Войти</a></p>');
|
||||||
|
try {
|
||||||
|
const mainAuth = require('../src/auth');
|
||||||
|
const iamData = await mainAuth.fetchIamUser(token);
|
||||||
|
res.set('Content-Type', 'text/html; charset=utf-8');
|
||||||
|
res.send(rawPage('IAM PROD', iamData.raw));
|
||||||
|
} catch (e) {
|
||||||
|
res.send('<h2>Ошибка IAM</h2><pre>' + e.message + '</pre>');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// ── GET /v2/iam_response_test — IAM test стенд ──────────────────────
|
||||||
|
router.get('/iam_response_test', async (req, res) => {
|
||||||
|
const token = req.session && req.session.token;
|
||||||
|
if (!token) return res.send('<h2>Нет токена</h2><p><a href="/v2/login">Войти</a></p>');
|
||||||
|
try {
|
||||||
|
const raw = await iamFetch(token, config.iamApiBase + '/auth/user');
|
||||||
|
res.set('Content-Type', 'text/html; charset=utf-8');
|
||||||
|
res.send(rawPage('IAM TEST', raw));
|
||||||
|
} catch (e) {
|
||||||
|
res.send('<h2>Ошибка IAM Test</h2><pre>' + e.message + '</pre>');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// ── GET /v2/iam_response_dev — IAM dev стенд ────────────────────────
|
||||||
|
router.get('/iam_response_dev', async (req, res) => {
|
||||||
|
const token = req.session && req.session.token;
|
||||||
|
if (!token) return res.send('<h2>Нет токена</h2><p><a href="/v2/login">Войти</a></p>');
|
||||||
|
try {
|
||||||
|
const raw = await iamFetch(token, config.iamApiBase + '/auth/user');
|
||||||
|
res.set('Content-Type', 'text/html; charset=utf-8');
|
||||||
|
res.send(rawPage('IAM DEV', raw));
|
||||||
|
} catch (e) {
|
||||||
|
res.send('<h2>Ошибка IAM Dev</h2><pre>' + e.message + '</pre>');
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// ── GET /v2/iam-gateway-test — сравнение auth-api vs lk-api-gateway ──
|
||||||
|
router.get('/iam-gateway-test', async (req, res) => {
|
||||||
|
const token = req.session && req.session.token;
|
||||||
|
if (!token) return res.send('<h2>Нет токена</h2><p><a href="/v2/login">Войти</a></p>');
|
||||||
|
|
||||||
|
const base = config.iamApiBase;
|
||||||
|
const tests = [
|
||||||
|
{
|
||||||
|
name: 'auth-api /auth/user',
|
||||||
|
url: base + '/auth/user',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'lk-api-gateway /iam/auth/user',
|
||||||
|
url: 'https://lk-api-gateway.ngcloud.ru/api/v1/iam/auth/user',
|
||||||
|
},
|
||||||
|
{
|
||||||
|
name: 'auth-api /impersonation/status',
|
||||||
|
url: base + '/impersonation/status',
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
const results = {};
|
||||||
|
for (const t of tests) {
|
||||||
|
try {
|
||||||
|
const data = await iamFetch(token, t.url);
|
||||||
|
results[t.name] = { ok: true, data };
|
||||||
|
} catch (e) {
|
||||||
|
results[t.name] = { ok: false, error: e.message };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
res.set('Content-Type', 'text/html; charset=utf-8');
|
||||||
|
res.send(iamComparePage(results));
|
||||||
|
});
|
||||||
|
|
||||||
// ── /v2/app — пользовательский CRUD (только с сессией) ──────────────
|
// ── /v2/app — пользовательский CRUD (только с сессией) ──────────────
|
||||||
router.use('/app', enhanceImpersonation, resolveContext, createUserRouter());
|
router.use('/app', enhanceImpersonation, resolveContext, createUserRouter());
|
||||||
|
|
||||||
// ── /v2/admin — админка (только для isAdmin=true) ────────────────────
|
// ── /v2/admin — админка: лимиты + аудит ──────────────────────────
|
||||||
router.use('/admin', enhanceImpersonation, resolveContext, createAdminRouter());
|
router.use('/admin', enhanceImpersonation, resolveContext, createAdminRouter());
|
||||||
|
|
||||||
// ── GET /v2/ — редирект на /v2/app ──────────────────────────────────
|
// ── GET /v2/ — редирект на /v2/app ──────────────────────────────────
|
||||||
@@ -71,11 +146,59 @@ function createV2Router() {
|
|||||||
router.use('/export', createExportRouter());
|
router.use('/export', createExportRouter());
|
||||||
|
|
||||||
// ── GET /v2/logout — редирект на основной выход ─────────────────────
|
// ── GET /v2/logout — редирект на основной выход ─────────────────────
|
||||||
router.get('/logout', (req, res) => res.redirect('/logout'));
|
router.get('/logout', (req, res) => {
|
||||||
|
const ua = (req.headers['user-agent'] || '').toLowerCase();
|
||||||
|
const isBrowser = ua.includes('mozilla') || ua.includes('chrome') || ua.includes('safari');
|
||||||
|
if (isBrowser) {
|
||||||
|
res.set('Content-Type', 'text/html; charset=utf-8');
|
||||||
|
return res.send('<!DOCTYPE html><html><head><meta charset="utf-8"><title>Выход</title>'
|
||||||
|
+ '<style>body{font-family:sans-serif;background:#111;color:#eee;padding:40px;text-align:center}'
|
||||||
|
+ 'h2{color:#4fc3f7}p{font-size:16px;margin:20px 0}'
|
||||||
|
+ '.btn{display:inline-block;padding:12px 24px;margin:0 10px;border-radius:6px;text-decoration:none;font-size:16px}'
|
||||||
|
+ '.btn-yes{background:#ef5350;color:#fff}.btn-no{background:#333;color:#eee}'
|
||||||
|
+ '</style></head><body>'
|
||||||
|
+ '<h2>Выход из приложения</h2>'
|
||||||
|
+ '<p>Выход завершит сессию во всех сервисах Nubes (Keycloak SSO).<br>Вы уверены?</p>'
|
||||||
|
+ '<a href="/logout" class="btn btn-yes">Да, выйти</a>'
|
||||||
|
+ '<a href="/v2/app" class="btn btn-no">Отмена</a>'
|
||||||
|
+ '</body></html>');
|
||||||
|
}
|
||||||
|
res.redirect('/logout');
|
||||||
|
});
|
||||||
|
|
||||||
return router;
|
return router;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// ── Хелпер: HTTP-запрос к IAM ────────────────────────────────────────────────
|
||||||
|
async function iamFetch(token, url) {
|
||||||
|
const https = require('https');
|
||||||
|
const u = new URL(url);
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
https.get({
|
||||||
|
hostname: u.hostname, port: 443, path: u.pathname,
|
||||||
|
headers: { Authorization: 'Bearer ' + token, Accept: 'application/json' },
|
||||||
|
}, res => {
|
||||||
|
let data = '';
|
||||||
|
res.on('data', c => data += c);
|
||||||
|
res.on('end', () => {
|
||||||
|
if (res.statusCode !== 200) return reject(new Error(res.statusCode + ': ' + data.slice(0, 200)));
|
||||||
|
try { resolve(JSON.parse(data)); } catch (e) { reject(e); }
|
||||||
|
});
|
||||||
|
}).on('error', reject);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function rawPage(title, data) {
|
||||||
|
return '<!DOCTYPE html>\n<html><head><meta charset="utf-8"><title>' + title + '</title>'
|
||||||
|
+ '<style>body{font-family:monospace;background:#111;color:#eee;padding:20px}'
|
||||||
|
+ 'pre{background:#1a1a2e;padding:15px;border-radius:8px;overflow-x:auto;font-size:13px}'
|
||||||
|
+ 'h2{color:#4fc3f7}a{color:#80cbc4}</style></head><body>'
|
||||||
|
+ '<h2>Сырой ответ ' + title + '</h2>'
|
||||||
|
+ '<pre>' + JSON.stringify(data, null, 2).replace(/</g, '<') + '</pre>'
|
||||||
|
+ '<p><a href="/v2/iam">← Сессия</a> | <a href="/v2/app">CRUD</a></p>'
|
||||||
|
+ '</body></html>';
|
||||||
|
}
|
||||||
|
|
||||||
function debugPage(u, version) {
|
function debugPage(u, version) {
|
||||||
return `<!DOCTYPE html>
|
return `<!DOCTYPE html>
|
||||||
<html><head><meta charset="utf-8"><title>V2 — IAM</title>
|
<html><head><meta charset="utf-8"><title>V2 — IAM</title>
|
||||||
@@ -92,4 +215,63 @@ function debugPage(u, version) {
|
|||||||
</body></html>`;
|
</body></html>`;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function iamComparePage(results) {
|
||||||
|
function fmt(data, depth) {
|
||||||
|
if (data === null || data === undefined) return '<span style="color:#888">null</span>';
|
||||||
|
if (typeof data === 'string') return '<span style="color:#ce93d8">"' + data.replace(/</g, '<') + '"</span>';
|
||||||
|
if (typeof data === 'number' || typeof data === 'boolean') return '<span style="color:#81c784">' + data + '</span>';
|
||||||
|
if (Array.isArray(data)) {
|
||||||
|
if (data.length === 0) return '<span style="color:#888">[]</span>';
|
||||||
|
let html = '<span style="color:#888">[</span><div style="padding-left:20px">';
|
||||||
|
for (const item of data) html += '<div>' + fmt(item, depth + 1) + ',</div>';
|
||||||
|
html += '</div><span style="color:#888">]</span>';
|
||||||
|
return html;
|
||||||
|
}
|
||||||
|
if (typeof data === 'object') {
|
||||||
|
let html = '<span style="color:#888">{</span><div style="padding-left:20px">';
|
||||||
|
for (const [k, v] of Object.entries(data)) {
|
||||||
|
html += '<div><span style="color:#82aaff">"' + k + '"</span>: ' + fmt(v, depth + 1) + '</div>';
|
||||||
|
}
|
||||||
|
html += '</div><span style="color:#888">}</span>';
|
||||||
|
return html;
|
||||||
|
}
|
||||||
|
return String(data).replace(/</g, '<');
|
||||||
|
}
|
||||||
|
|
||||||
|
let html = '<!DOCTYPE html><html><head><meta charset="utf-8"><title>IAM Impersonation</title>';
|
||||||
|
html += '<style>body{font-family:monospace;background:#111;color:#eee;padding:20px;font-size:14px}';
|
||||||
|
html += 'h2{color:#4fc3f7}.ok{color:#81c784}.err{color:#ef5350}';
|
||||||
|
html += '.card{background:#1a1a2e;border-radius:8px;padding:15px;margin-bottom:15px;overflow-x:auto}';
|
||||||
|
html += '.card-title{color:#b39ddb;font-size:18px;font-weight:bold;margin-bottom:10px}';
|
||||||
|
html += 'a{color:#80cbc4;text-decoration:none}a:hover{text-decoration:underline}';
|
||||||
|
html += '.nav{display:flex;gap:15px;margin-bottom:20px;flex-wrap:wrap}';
|
||||||
|
html += '.nav a{background:#1a1a2e;padding:8px 16px;border-radius:6px;font-size:14px}';
|
||||||
|
html += '</style></head><body>';
|
||||||
|
html += '<h2>🧪 IAM Impersonation — GET эндпоинты</h2>';
|
||||||
|
html += '<div class="nav">';
|
||||||
|
html += '<a href="/v2/iam">← Сессия</a>';
|
||||||
|
html += '<a href="/v2/app">CRUD</a>';
|
||||||
|
html += '<a href="/v2/admin">Админка</a>';
|
||||||
|
html += '<a href="/v2/iam_response">IAM PROD</a>';
|
||||||
|
html += '<a href="/v2/iam_response_test">IAM TEST</a>';
|
||||||
|
html += '<a href="/v2/iam_response_dev">IAM DEV</a>';
|
||||||
|
html += '</div>';
|
||||||
|
|
||||||
|
for (const [name, r] of Object.entries(results)) {
|
||||||
|
html += '<div class="card">';
|
||||||
|
html += '<div class="card-title">GET /impersonation/' + name + '</div>';
|
||||||
|
if (r.ok) {
|
||||||
|
html += '<div style="font-family:monospace;white-space:pre-wrap;tab-size:2">';
|
||||||
|
html += fmt(r.data, 0);
|
||||||
|
html += '</div>';
|
||||||
|
} else {
|
||||||
|
html += '<div class="err">❌ ' + r.error.replace(/</g, '<') + '</div>';
|
||||||
|
}
|
||||||
|
html += '</div>';
|
||||||
|
}
|
||||||
|
|
||||||
|
html += '</body></html>';
|
||||||
|
return html;
|
||||||
|
}
|
||||||
|
|
||||||
module.exports = { createV2Router };
|
module.exports = { createV2Router };
|
||||||
|
|||||||
+13
-24
@@ -1,33 +1,36 @@
|
|||||||
// ═══════════════════════════════════════════════════════════════════════════════
|
// ═══════════════════════════════════════════════════════════════════════════════
|
||||||
// V2 — Админка (Express + EJS)
|
// V2 — Админка: лимиты и аудит (Express + EJS)
|
||||||
//
|
//
|
||||||
// ЭТО: Express-роутер для админа, рендерит EJS-шаблоны.
|
// ЭТО: Express-роутер для админа.
|
||||||
// НЕ: доступно обычным юзерам (middleware: req.isAdmin).
|
// НЕ: доступно обычным юзерам (middleware: req.canAdmin).
|
||||||
//
|
//
|
||||||
// ШАБЛОНЫ:
|
// ШАБЛОНЫ:
|
||||||
// views/v2/admin.ejs — дашборд (companies, user, version)
|
// views/v2/admin.ejs — компании + лимиты
|
||||||
// views/v2/admin-audit.ejs — аудит (audit, company, version)
|
// views/v2/admin-audit.ejs — аудит
|
||||||
// views/v2/admin-entries.ejs — записи (entries, company, used, limit, ...)
|
|
||||||
// ═══════════════════════════════════════════════════════════════════════════════
|
// ═══════════════════════════════════════════════════════════════════════════════
|
||||||
|
|
||||||
const express = require('express');
|
const express = require('express');
|
||||||
const q = require('../db/queries');
|
const q = require('../db/queries');
|
||||||
const crud = require('../crud');
|
|
||||||
const config = require('../config');
|
const config = require('../config');
|
||||||
|
|
||||||
function createAdminRouter() {
|
function createAdminRouter() {
|
||||||
const router = express.Router();
|
const router = express.Router();
|
||||||
|
|
||||||
router.use((req, res, next) => {
|
router.use((req, res, next) => {
|
||||||
if (!req.isAdmin) return res.redirect('/v2/app');
|
if (!req.canAdmin) return res.redirect('/v2/app');
|
||||||
|
// user для шаблонов
|
||||||
|
req.adminUser = {
|
||||||
|
email: req.email,
|
||||||
|
fio: (req.session && req.session.user && req.session.user.fio) || null,
|
||||||
|
};
|
||||||
next();
|
next();
|
||||||
});
|
});
|
||||||
|
|
||||||
// ── GET / — дашборд ─────────────────────────────────────────────────
|
// ── GET / — дашборд: компании + лимиты ─────────────────────────────
|
||||||
router.get('/', async (req, res) => {
|
router.get('/', async (req, res) => {
|
||||||
try {
|
try {
|
||||||
const companies = await q.getAllCompanies();
|
const companies = await q.getAllCompanies();
|
||||||
res.render('v2/admin', { companies, user: req.user || {}, version: config.version });
|
res.render('v2/admin', { companies, user: req.adminUser, version: config.version });
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
res.status(500).send('<h2>Ошибка</h2><pre>' + e.message + '</pre>');
|
res.status(500).send('<h2>Ошибка</h2><pre>' + e.message + '</pre>');
|
||||||
}
|
}
|
||||||
@@ -58,20 +61,6 @@ function createAdminRouter() {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
// ── GET /entries ────────────────────────────────────────────────────
|
|
||||||
router.get('/entries', async (req, res) => {
|
|
||||||
try {
|
|
||||||
const companyId = parseInt(req.query.companyId);
|
|
||||||
const company = companyId ? await q.getCompanyById(companyId) : null;
|
|
||||||
if (!company) return res.redirect('/v2/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 });
|
|
||||||
} catch (e) {
|
|
||||||
res.status(500).send('<h2>Ошибка</h2><pre>' + e.message + '</pre>');
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
return router;
|
return router;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -4,18 +4,18 @@
|
|||||||
// ЭТО: все настройки в одном месте.
|
// ЭТО: все настройки в одном месте.
|
||||||
// ЗАЧЕМ: всё что может поменяться между средами — здесь, не размазано по коду.
|
// ЗАЧЕМ: всё что может поменяться между средами — здесь, не размазано по коду.
|
||||||
//
|
//
|
||||||
// ПРИОРИТЕТ: process.env (V2_*) → хардкод-умолчания.
|
// ПРИОРИТЕТ: process.env → хардкод-умолчания.
|
||||||
// Умолчания — для тестовой среды (VM KC на italo.kube5s.ru:8080).
|
|
||||||
// ═══════════════════════════════════════════════════════════════════════════════
|
// ═══════════════════════════════════════════════════════════════════════════════
|
||||||
|
|
||||||
module.exports = {
|
module.exports = {
|
||||||
version: '0.5.98',
|
version: '0.5.149',
|
||||||
|
|
||||||
// ── IAM ──────────────────────────────────────────────────────────────────
|
// ── IAM ──────────────────────────────────────────────────────────────────
|
||||||
iamUrl: process.env.V2_IAM_URL || 'https://auth-api.ngcloud.ru/api/v1/auth/user',
|
iamUrl: process.env.V2_IAM_URL || 'https://auth-api.ngcloud.ru/api/v1/auth/user',
|
||||||
|
iamApiBase: process.env.IAM_API_BASE || 'https://auth-api.ngcloud.ru/api/v1',
|
||||||
|
|
||||||
// ── OIDC (Keycloak) ──────────────────────────────────────────────────────
|
// ── OIDC (Keycloak) ──────────────────────────────────────────────────────
|
||||||
kcBaseUrl: process.env.V2_KC_BASE_URL || 'https://italo.kube5s.ru:8080/realms/ipwhitelist',
|
kcBaseUrl: process.env.V2_KC_BASE_URL || 'https://login.ngcloud.ru/realms/ipwhitelist',
|
||||||
kcClientId: process.env.V2_KC_CLIENT_ID || 'ipwhitelist-app',
|
kcClientId: process.env.V2_KC_CLIENT_ID || 'ipwhitelist-app',
|
||||||
kcClientSecret: process.env.V2_KC_CLIENT_SECRET || '',
|
kcClientSecret: process.env.V2_KC_CLIENT_SECRET || '',
|
||||||
appUrl: process.env.V2_APP_URL || 'https://whitelist.nodejsk8s.services.ngcloud.ru',
|
appUrl: process.env.V2_APP_URL || 'https://whitelist.nodejsk8s.services.ngcloud.ru',
|
||||||
|
|||||||
@@ -74,4 +74,11 @@ async function remove(entryId, clientId, email, impBy) {
|
|||||||
return q.deleteEntry(entryId, co.id, email, impBy);
|
return q.deleteEntry(entryId, co.id, email, impBy);
|
||||||
}
|
}
|
||||||
|
|
||||||
module.exports = { list, add, edit, remove };
|
// ── restore(entryId, clientId, email, impBy) → void ─────────────────────────
|
||||||
|
// Восстановление удалённой записи.
|
||||||
|
async function restore(entryId, clientId, email, impBy) {
|
||||||
|
const co = await resolve(clientId);
|
||||||
|
return q.restoreEntry(entryId, co.id, email, impBy);
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = { list, add, edit, remove, restore };
|
||||||
|
|||||||
+39
-1
@@ -177,6 +177,44 @@ async function deleteEntry(entryId, companyId, userEmail, impersonatedBy) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Восстановить удалённую запись (убрать deleted_at).
|
||||||
|
*/
|
||||||
|
async function restoreEntry(entryId, companyId, userEmail, impersonatedBy) {
|
||||||
|
const client = await pool.connect();
|
||||||
|
try {
|
||||||
|
await client.query('BEGIN');
|
||||||
|
|
||||||
|
const old = (await client.query(
|
||||||
|
'SELECT * FROM whitelist_entries WHERE id = $1 AND company_id = $2 AND deleted_at IS NOT NULL',
|
||||||
|
[entryId, companyId]
|
||||||
|
)).rows[0];
|
||||||
|
if (!old) throw new Error('Удалённая запись не найдена');
|
||||||
|
|
||||||
|
await client.query(
|
||||||
|
'UPDATE whitelist_entries SET deleted_by = NULL, deleted_at = NULL WHERE id = $1 AND company_id = $2',
|
||||||
|
[entryId, companyId]
|
||||||
|
);
|
||||||
|
await logAudit(userEmail, companyId, 'RESTORE', old.value_cidr, old.value_cidr, entryId, impersonatedBy, client);
|
||||||
|
|
||||||
|
// Проверить лимит
|
||||||
|
const company = (await client.query('SELECT * FROM companies WHERE id = $1', [companyId])).rows[0];
|
||||||
|
const limit = company.custom_limit != null ? company.custom_limit : (parseInt(process.env.DEFAULT_LIMIT, 10) || 15);
|
||||||
|
const cnt = (await client.query(
|
||||||
|
'SELECT COUNT(*)::int AS c FROM whitelist_entries WHERE company_id = $1 AND deleted_at IS NULL',
|
||||||
|
[companyId]
|
||||||
|
)).rows[0].c;
|
||||||
|
if (cnt > limit) throw new Error('Восстановление превысит лимит (' + limit + ')');
|
||||||
|
|
||||||
|
await client.query('COMMIT');
|
||||||
|
} catch (e) {
|
||||||
|
await client.query('ROLLBACK');
|
||||||
|
throw e;
|
||||||
|
} finally {
|
||||||
|
client.release();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
// ── Админ ─────────────────────────────────────────────────────────────────────
|
// ── Админ ─────────────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
async function getCompanyById(id) {
|
async function getCompanyById(id) {
|
||||||
@@ -241,7 +279,7 @@ async function getAudit(companyId = null) {
|
|||||||
|
|
||||||
module.exports = {
|
module.exports = {
|
||||||
getOrCreateCompany, getLimit,
|
getOrCreateCompany, getLimit,
|
||||||
listEntries, createEntry, updateEntry, deleteEntry,
|
listEntries, createEntry, updateEntry, deleteEntry, restoreEntry,
|
||||||
getExportCIDRs, getAudit,
|
getExportCIDRs, getAudit,
|
||||||
getCompanyById, getAllCompanies, setLimit,
|
getCompanyById, getAllCompanies, setLimit,
|
||||||
};
|
};
|
||||||
|
|||||||
+17
-1
@@ -46,7 +46,7 @@ async function ensureSchema(pool) {
|
|||||||
id SERIAL PRIMARY KEY,
|
id SERIAL PRIMARY KEY,
|
||||||
user_email VARCHAR(255) NOT NULL,
|
user_email VARCHAR(255) NOT NULL,
|
||||||
company_id INTEGER NOT NULL,
|
company_id INTEGER NOT NULL,
|
||||||
action VARCHAR(32) NOT NULL CHECK (action IN ('CREATE','UPDATE','DELETE')),
|
action VARCHAR(32) NOT NULL CHECK (action IN ('CREATE','UPDATE','DELETE','RESTORE')),
|
||||||
old_value TEXT,
|
old_value TEXT,
|
||||||
new_value TEXT,
|
new_value TEXT,
|
||||||
entry_id INTEGER,
|
entry_id INTEGER,
|
||||||
@@ -56,6 +56,22 @@ async function ensureSchema(pool) {
|
|||||||
|
|
||||||
CREATE INDEX IF NOT EXISTS idx_audit_log_company_time
|
CREATE INDEX IF NOT EXISTS idx_audit_log_company_time
|
||||||
ON audit_log(company_id, created_at DESC);
|
ON audit_log(company_id, created_at DESC);
|
||||||
|
|
||||||
|
-- Миграция: добавить RESTORE в CHECK (если ещё нет)
|
||||||
|
DO $$
|
||||||
|
DECLARE
|
||||||
|
cn text;
|
||||||
|
BEGIN
|
||||||
|
SELECT con.conname INTO cn
|
||||||
|
FROM pg_constraint con
|
||||||
|
JOIN pg_class rel ON rel.oid = con.conrelid
|
||||||
|
WHERE rel.relname = 'audit_log' AND con.contype = 'c';
|
||||||
|
IF cn IS NOT NULL THEN
|
||||||
|
EXECUTE 'ALTER TABLE audit_log DROP CONSTRAINT ' || cn;
|
||||||
|
END IF;
|
||||||
|
EXECUTE 'ALTER TABLE audit_log ADD CONSTRAINT audit_log_action_check CHECK (action IN (''CREATE'',''UPDATE'',''DELETE'',''RESTORE''))';
|
||||||
|
END;
|
||||||
|
$$;
|
||||||
`);
|
`);
|
||||||
|
|
||||||
console.log('[db] Schema ensured');
|
console.log('[db] Schema ensured');
|
||||||
|
|||||||
@@ -1,32 +1,60 @@
|
|||||||
// ═══════════════════════════════════════════════════════════════════════════════
|
// ═══════════════════════════════════════════════════════════════════════════════
|
||||||
// V2 — Расширение имперсонации (отдельный модуль)
|
// V2 — Имперсонация (IAM + URL-режим)
|
||||||
//
|
//
|
||||||
// ЭТО: middleware — добавляет дополнительные компании имперсонируемому юзеру.
|
// ЭТО: middleware — подмена сессии при имперсонации.
|
||||||
// НЕ: жёсткая логика в resolveContext или user/index.js.
|
// НЕ: жёсткая логика в resolveContext или user/index.js.
|
||||||
//
|
//
|
||||||
|
// IAM-имперсонация: если сессия уже содержит isImpersonated=true → не трогаем.
|
||||||
|
//
|
||||||
|
// URL-имперсонация: для разрешённых пользователей (IMPERSONATION_ALLOWED_USERS).
|
||||||
|
// /v2/app?impersonate=email&company=W***
|
||||||
|
// Полная подмена сессии: email, clientId, profiles — всё от таргета.
|
||||||
|
//
|
||||||
// ENV:
|
// ENV:
|
||||||
// IMPERSONATION_TARGET — email юзера, которому добавляем компании
|
// IMP_ALLOWED — emails через запятую (кому можно)
|
||||||
// IMPERSONATION_EXTRA_COMPANIES — W-номера через запятую (WZ01112,WZ03709)
|
|
||||||
// ═══════════════════════════════════════════════════════════════════════════════
|
// ═══════════════════════════════════════════════════════════════════════════════
|
||||||
|
|
||||||
const TARGET_EMAIL = process.env.IMPERSONATION_TARGET || '';
|
const ALLOWED_USERS = new Set(
|
||||||
const EXTRA_COMPANIES = (process.env.IMPERSONATION_EXTRA_COMPANIES || '')
|
(process.env.IMP_ALLOWED || '')
|
||||||
.split(',').map(s => s.trim()).filter(Boolean);
|
.split(/[\s,/]+/).map(s => s.trim()).filter(Boolean)
|
||||||
|
);
|
||||||
|
|
||||||
function enhanceImpersonation(req, res, next) {
|
function enhanceImpersonation(req, res, next) {
|
||||||
if (!TARGET_EMAIL) return next();
|
|
||||||
const u = req.session && req.session.user;
|
const u = req.session && req.session.user;
|
||||||
if (!u || u.email !== TARGET_EMAIL) return next();
|
if (!u) return next();
|
||||||
|
|
||||||
const current = u.allClientIds || [u.clientId || ''];
|
// ── IAM-имперсонация — уже в сессии, не трогаем ────────────────────
|
||||||
u.allClientIds = [...new Set([...current, ...EXTRA_COMPANIES])].filter(Boolean);
|
if (u.isImpersonated) return next();
|
||||||
|
|
||||||
if (!u.profiles) u.profiles = [];
|
// ── URL-имперсонация ───────────────────────────────────────────────
|
||||||
for (const cid of EXTRA_COMPANIES) {
|
const targetEmail = req.query.impersonate;
|
||||||
if (!u.profiles.find(p => p.client_id === cid))
|
const targetCompany = req.query.company;
|
||||||
u.profiles.push({ client_id: cid, company_name: cid, is_active_profile: false });
|
|
||||||
|
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();
|
next();
|
||||||
}
|
}
|
||||||
|
|
||||||
module.exports = { enhanceImpersonation, TARGET_EMAIL, EXTRA_COMPANIES };
|
module.exports = { enhanceImpersonation };
|
||||||
|
|||||||
+12
-5
@@ -37,13 +37,20 @@ function resolveContext(req, res, next) {
|
|||||||
// u.impersonatedCompanyId — W-номер компании
|
// u.impersonatedCompanyId — W-номер компании
|
||||||
const isImpersonated = !!(u.originalUserEmail && u.impersonatedCompanyId);
|
const isImpersonated = !!(u.originalUserEmail && u.impersonatedCompanyId);
|
||||||
|
|
||||||
req.email = isImpersonated ? u.originalUserEmail : (u.email || '');
|
req.email = u.email || '';
|
||||||
req.clientId = isImpersonated ? u.impersonatedCompanyId : (u.activeClientId || u.clientId || '');
|
// activeClientId может переопределять impersonatedCompanyId при switchTo
|
||||||
|
req.clientId = isImpersonated
|
||||||
|
? (u.activeClientId || u.impersonatedCompanyId || u.clientId || '')
|
||||||
|
: (u.activeClientId || u.clientId || '');
|
||||||
req.companyName = u.companyName || req.clientId;
|
req.companyName = u.companyName || req.clientId;
|
||||||
req.isAdmin = !!(u.isAdmin && u.adminMode);
|
// Админ: пользователь с WZ01112 — всегда админ
|
||||||
|
const allCids = u.allClientIds || [u.clientId || ''];
|
||||||
|
req.canAdmin = allCids.includes('WZ01112') || u.clientId === 'WZ01112' || !!u.isAdmin || u.email === (process.env.ADMIN_EMAIL || '');
|
||||||
|
req.adminMode = req.canAdmin;
|
||||||
|
req.isAdmin = req.canAdmin;
|
||||||
req.isImpersonated = isImpersonated;
|
req.isImpersonated = isImpersonated;
|
||||||
req.impersonatedBy = isImpersonated ? u.email : null;
|
req.impersonatedBy = isImpersonated ? u.originalUserEmail : null;
|
||||||
req.allClientIds = u.allClientIds || [req.clientId];
|
req.allClientIds = allCids;
|
||||||
req.profiles = u.profiles || [];
|
req.profiles = u.profiles || [];
|
||||||
|
|
||||||
next();
|
next();
|
||||||
|
|||||||
+74
-17
@@ -1,15 +1,22 @@
|
|||||||
// ═══════════════════════════════════════════════════════════════════════════════
|
// ═══════════════════════════════════════════════════════════════════════════════
|
||||||
// V2 — Фронтенд пользователя (Express + EJS)
|
// V2 — Единый фронтенд (Express + EJS) — юзеры и админы
|
||||||
//
|
//
|
||||||
// ЭТО: Express-роутер, рендерит EJS-шаблоны.
|
// ЭТО: Express-роутер, рендерит EJS-шаблон views/v2/user.ejs.
|
||||||
// НЕ: работа с БД (только через crud/).
|
// НЕ: работа с БД (только через crud/).
|
||||||
//
|
//
|
||||||
// ШАБЛОН: views/v2/user.ejs — данные: entries, limit, used, companies,
|
// ОДИН ИНТЕРФЕЙС для юзеров и админов:
|
||||||
// activeClientId, user, includeDeleted, version.
|
// - Юзер: dropdown = свои профили из IAM, CRUD внутри выбранной компании.
|
||||||
|
// - Админ: dropdown = все компании из БД, CRUD внутри выбранной.
|
||||||
|
// - По умолчанию: активный профиль (is_active_profile=true).
|
||||||
|
//
|
||||||
|
// ПЕРЕКЛЮЧЕНИЕ КОМПАНИИ: ?switchTo=W*** → обновляет activeClientId в сессии.
|
||||||
|
// - Юзер: только свои профили.
|
||||||
|
// - Админ: любая компания.
|
||||||
// ═══════════════════════════════════════════════════════════════════════════════
|
// ═══════════════════════════════════════════════════════════════════════════════
|
||||||
|
|
||||||
const express = require('express');
|
const express = require('express');
|
||||||
const crud = require('../crud');
|
const crud = require('../crud');
|
||||||
|
const q = require('../db/queries');
|
||||||
const config = require('../config');
|
const config = require('../config');
|
||||||
|
|
||||||
function createUserRouter() {
|
function createUserRouter() {
|
||||||
@@ -18,25 +25,63 @@ function createUserRouter() {
|
|||||||
// ── GET / — список записей + форма ──────────────────────────────────
|
// ── GET / — список записей + форма ──────────────────────────────────
|
||||||
router.get('/', async (req, res) => {
|
router.get('/', async (req, res) => {
|
||||||
try {
|
try {
|
||||||
const clId = req.clientId;
|
const isAdmin = req.canAdmin;
|
||||||
const allCompanies = req.profiles.length > 0
|
let clId = req.clientId;
|
||||||
? req.profiles
|
|
||||||
: [{ client_id: clId, company_name: req.companyName || clId }];
|
|
||||||
|
|
||||||
|
// ── Компании для dropdown ───────────────────────────────────────
|
||||||
|
let companies;
|
||||||
|
if (isAdmin) {
|
||||||
|
const all = await q.getAllCompanies();
|
||||||
|
const ownIds = new Set(req.allClientIds || []);
|
||||||
|
companies = all.map(c => ({
|
||||||
|
client_id: c.client_id,
|
||||||
|
name: c.name || c.client_id,
|
||||||
|
active_count: c.active_count,
|
||||||
|
isPersonal: ownIds.has(c.client_id),
|
||||||
|
}));
|
||||||
|
} else {
|
||||||
|
companies = (req.profiles && req.profiles.length > 0)
|
||||||
|
? req.profiles.map(p => ({
|
||||||
|
client_id: p.client_id,
|
||||||
|
name: p.company_name || p.client_id,
|
||||||
|
is_active: p.is_active_profile,
|
||||||
|
}))
|
||||||
|
: [{ client_id: clId, name: req.companyName || clId, is_active: true }];
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Переключение компании (до crud.list — не грузить зря) ────
|
||||||
|
let switchDebug = null;
|
||||||
|
if (req.query.switchTo) {
|
||||||
|
const targetId = req.query.switchTo;
|
||||||
|
const allowed = isAdmin || (req.profiles || []).find(p => p.client_id === targetId);
|
||||||
|
if (allowed) {
|
||||||
|
req.session.user.activeClientId = targetId;
|
||||||
|
clId = targetId;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ── Записи ──────────────────────────────────────────────────────
|
||||||
const includeDeleted = req.query.deleted === '1';
|
const includeDeleted = req.query.deleted === '1';
|
||||||
const { entries, used, limit } = await crud.list(clId, includeDeleted);
|
const { entries, used, limit } = await crud.list(clId, includeDeleted);
|
||||||
|
|
||||||
// Переключение компании
|
// ── Данные пользователя для шаблона ────────────────────────────
|
||||||
if (req.query.switchTo && allCompanies.find(c => c.client_id === req.query.switchTo)) {
|
const sessionUser = req.session && req.session.user ? req.session.user : {};
|
||||||
req.session.user.activeClientId = req.query.switchTo;
|
const templateUser = {
|
||||||
return res.redirect('/v2/app');
|
email: req.email,
|
||||||
}
|
fio: sessionUser.fio || null,
|
||||||
|
isAdmin: req.canAdmin || false,
|
||||||
|
adminMode: isAdmin,
|
||||||
|
isImpersonated: req.isImpersonated || false,
|
||||||
|
originalUserEmail: sessionUser.originalUserEmail || '',
|
||||||
|
originalUserFullName: sessionUser.originalUserFullName || '',
|
||||||
|
originalUserCompany: sessionUser.originalUserCompany || '',
|
||||||
|
};
|
||||||
|
|
||||||
res.render('v2/user', {
|
res.render('v2/user', {
|
||||||
entries, limit, used,
|
entries, limit, used,
|
||||||
companies: allCompanies,
|
companies,
|
||||||
activeClientId: clId,
|
activeClientId: clId,
|
||||||
user: req.user || {},
|
user: templateUser,
|
||||||
includeDeleted,
|
includeDeleted,
|
||||||
version: config.version,
|
version: config.version,
|
||||||
});
|
});
|
||||||
@@ -69,11 +114,23 @@ function createUserRouter() {
|
|||||||
|
|
||||||
// ── POST /delete/:id ────────────────────────────────────────────────
|
// ── POST /delete/:id ────────────────────────────────────────────────
|
||||||
router.post('/delete/:id', async (req, res) => {
|
router.post('/delete/:id', async (req, res) => {
|
||||||
|
const qs = (req.body && req.body.deleted === '1') ? '&deleted=1' : '';
|
||||||
try {
|
try {
|
||||||
await crud.remove(parseInt(req.params.id), req.clientId, req.email, req.impersonatedBy);
|
await crud.remove(parseInt(req.params.id), req.clientId, req.email, req.impersonatedBy);
|
||||||
res.redirect('/v2/app?msg=Удалено');
|
res.redirect('/v2/app?msg=Удалено' + qs);
|
||||||
} catch (e) {
|
} catch (e) {
|
||||||
res.redirect('/v2/app?error=' + encodeURIComponent(e.message));
|
res.redirect('/v2/app?error=' + encodeURIComponent(e.message) + qs);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
// ── POST /restore/:id ──────────────────────────────────────────────
|
||||||
|
router.post('/restore/:id', async (req, res) => {
|
||||||
|
const qs = (req.body && req.body.deleted === '1') ? '&deleted=1' : '';
|
||||||
|
try {
|
||||||
|
await crud.restore(parseInt(req.params.id), req.clientId, req.email, req.impersonatedBy);
|
||||||
|
res.redirect('/v2/app?msg=Восстановлено' + qs);
|
||||||
|
} catch (e) {
|
||||||
|
res.redirect('/v2/app?error=' + encodeURIComponent(e.message) + qs);
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
+97
-17
@@ -1,20 +1,95 @@
|
|||||||
<!DOCTYPE html>
|
<!DOCTYPE html>
|
||||||
<html><head><meta charset="utf-8"><title>Аудит — <%= company ? company.client_id : 'Все' %> — v<%= version %></title>
|
<html lang="ru">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8">
|
||||||
|
<title>Аудит — <%= company ? company.client_id : 'Все' %> — IP WhiteList v<%= version %></title>
|
||||||
|
<link rel="icon" href="/favicon.png" type="image/png">
|
||||||
<style>
|
<style>
|
||||||
body{font-family:sans-serif;max-width:1200px;margin:20px auto;color:#222}
|
:root {
|
||||||
table{width:100%;border-collapse:collapse;margin:10px 0}
|
--bg: #f5f5f5; --card: #ffffff; --text: #1a1a1a; --muted: #6b7280;
|
||||||
th,td{border:1px solid #ccc;padding:6px;text-align:left;font-size:13px}
|
--border: #d1d5db; --grey-light: #f3f4f6; --blue: #2563eb; --blue-h: #1d4ed8;
|
||||||
th{background:#263238;color:#fff}
|
--red: #dc2626; --green: #16a34a; --amber: #d97706;
|
||||||
.bar{display:flex;justify-content:space-between;align-items:center;background:#263238;color:#fff;padding:10px;margin-bottom:15px}
|
}
|
||||||
.bar a{color:#80cbc4}
|
* { box-sizing: border-box; margin: 0; padding: 0; }
|
||||||
</style></head><body>
|
body {
|
||||||
<div class="bar">
|
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
|
||||||
<span><strong>📋 Аудит</strong> <%= company ? company.client_id : 'Все компании' %></span>
|
background: var(--bg); color: var(--text); font-size: 14px; line-height: 1.5;
|
||||||
<span><a href="/v2/admin">← Админка</a> | <a href="/v2/app">Пользовательский</a></span>
|
}
|
||||||
</div>
|
.page { max-width: 1200px; margin: 1.5rem auto; padding: 0 1rem; }
|
||||||
|
.card {
|
||||||
|
background: var(--card); border: 1px solid var(--border);
|
||||||
|
border-radius: 12px; box-shadow: 0 1px 2px rgba(0,0,0,.04);
|
||||||
|
margin-bottom: 1rem; overflow: hidden;
|
||||||
|
}
|
||||||
|
.card-header {
|
||||||
|
background: var(--grey-light); padding: .75rem 1rem;
|
||||||
|
font-weight: 600; font-size: 1rem; border-bottom: 1px solid var(--border);
|
||||||
|
}
|
||||||
|
.btn {
|
||||||
|
display: inline-flex; align-items: center; gap: .35rem;
|
||||||
|
padding: .4rem .85rem; border: 1px solid var(--border); border-radius: 6px;
|
||||||
|
font-size: .82rem; font-weight: 500; background: #fff; cursor: pointer;
|
||||||
|
text-decoration: none; color: var(--text); transition: background .15s;
|
||||||
|
}
|
||||||
|
.btn:hover { background: var(--grey-light); }
|
||||||
|
.btn-sm { padding: .3rem .65rem; font-size: .78rem; }
|
||||||
|
.table-wrap { border: 1px solid var(--border); border-radius: 8px; overflow: hidden; }
|
||||||
|
table { width: 100%; border-collapse: collapse; font-size: .82rem; }
|
||||||
|
th {
|
||||||
|
text-align: left; padding: .5rem .75rem;
|
||||||
|
background: var(--grey-light); color: var(--muted);
|
||||||
|
font-weight: 500; font-size: .78rem; text-transform: uppercase; letter-spacing: .5px;
|
||||||
|
border-bottom: 1px solid var(--border); border-right: 1px solid var(--border);
|
||||||
|
}
|
||||||
|
th:last-child { border-right: none; }
|
||||||
|
td {
|
||||||
|
padding: .4rem .75rem; border-bottom: 1px solid var(--border);
|
||||||
|
border-right: 1px solid var(--border); vertical-align: middle;
|
||||||
|
}
|
||||||
|
td:last-child { border-right: none; }
|
||||||
|
tr:last-child td { border-bottom: none; }
|
||||||
|
tr:hover td { background: #f8fafc; }
|
||||||
|
.empty { text-align: center; color: var(--muted); padding: 2rem; }
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
|
||||||
|
<header style="background:#fff;border-bottom:1px solid var(--border);padding:0 1.5rem;height:48px;display:flex;align-items:center;gap:.75rem;font-size:.9rem;color:var(--muted);">
|
||||||
|
<svg width="130" height="28" viewBox="0 0 311 69" style="display:block;">
|
||||||
|
<g transform="translate(-330 -228)">
|
||||||
|
<path d="M348.061 246.203 332.42 246.203 330 256.661 336.75 256.661 336.794 295.573 336.794 296.585 336.795 296.585 347.25 296.585 347.25 263.611C347.25 259.78 350.368 256.663 354.2 256.663L376.489 256.793C380.322 256.793 383.44 259.912 383.44 263.743L383.44 296.717 393.896 296.717 393.896 263.743C393.896 254.144 386.087 246.338 376.495 246.338L354.196 246.204 348.061 246.221 348.061 246.203Z" fill="#001C34" fill-rule="evenodd"/>
|
||||||
|
<path d="M582.095 296.65 626.768 296.65C634.793 296.65 641 290.03 641 282.009 641 273.985 634.473 267.458 626.449 267.458L601.724 267.458C599.446 267.458 597.595 265.607 597.595 263.328L597.595 260.825C597.595 258.548 599.446 256.697 601.724 256.697L628.041 256.697 630.452 246.276 601.724 246.276C593.7 246.276 587.174 252.802 587.174 260.825L587.174 263.328C587.174 271.352 593.7 277.879 601.724 277.879L626.449 277.879C628.726 277.879 630.579 279.732 630.579 282.009 630.579 284.283 628.726 286.4 626.449 286.4L584.126 286.4 582.095 296.65Z" fill="#001C34" fill-rule="evenodd"/>
|
||||||
|
<path d="M564.549 246.347 537.193 246.347C529.027 246.347 522.385 252.989 522.385 261.156L522.385 279.521C522.385 288.916 530.028 296.557 539.422 296.557L576.846 296.557 579.196 286.401 539.422 286.401C535.775 286.401 532.805 283.172 532.805 279.521L532.748 278.028 567.684 278.028 579.354 277.959 579.354 268.958 579.354 261.156C579.354 252.989 572.712 246.347 564.549 246.347ZM568.935 267.54 532.805 267.54 532.805 261.156C532.805 258.737 534.774 256.767 537.193 256.767L564.549 256.767C566.966 256.767 568.935 258.737 568.935 261.156L568.935 267.54Z" fill="#001C34" fill-rule="evenodd"/>
|
||||||
|
<path d="M507.156 273.231 507.156 279.597C507.156 283.414 504.066 286.344 500.247 286.344L477.934 286.39C474.41 286.39 471.493 283.744 471.064 280.335L471.064 263.006C471.494 259.597 474.41 256.951 477.934 256.951L500.23 257.083C504.049 257.083 507.156 260.192 507.156 264.009L507.156 265.16 507.156 273.232ZM460.623 260.161 460.589 230.089 471.064 228.058 471.064 247.957C473.172 247.043 475.49 246.53 477.929 246.53L500.235 246.662C509.793 246.662 517.575 254.444 517.575 264.009L517.575 265.159 517.575 273.231 517.575 279.597C517.575 289.161 509.793 296.941 500.235 296.941L477.929 296.809C468.37 296.809 460.589 289.029 460.589 279.464L460.589 272.972 460.589 263.876 460.623 260.161Z" fill="#001C34" fill-rule="evenodd"/>
|
||||||
|
<path d="M445.037 271.59 445.037 279.317C445.037 283.134 441.93 286.241 438.111 286.241L416.092 286.11C412.273 286.11 409.166 283.002 409.166 279.185L409.166 276.635 409.222 276.644 409.222 244.013 398.748 246.044 398.752 249.955 398.748 249.957 398.748 279.184C398.748 288.749 406.529 296.529 416.087 296.529L438.116 296.661C447.674 296.661 455.456 288.881 455.456 279.316L455.456 276.639 455.482 276.643 455.482 244.013 445.008 246.043 445.037 271.589Z" fill="#001C34" fill-rule="evenodd"/>
|
||||||
|
</g>
|
||||||
|
</svg>
|
||||||
|
<span>|</span>
|
||||||
|
<span style="font-weight:500;color:var(--text);">Аудит: <%= company ? company.client_id : 'Все компании' %></span>
|
||||||
|
<span style="margin-left:auto;">
|
||||||
|
<a href="/v2/admin" class="btn btn-sm">← Лимиты</a>
|
||||||
|
</span>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
<div class="page">
|
||||||
|
<div class="card">
|
||||||
|
<div class="card-header">Журнал операций <span style="font-weight:400;font-size:.82rem;color:var(--muted);">(макс 500)</span></div>
|
||||||
|
<% if (audit.length === 0) { %>
|
||||||
|
<div class="empty">Нет записей</div>
|
||||||
|
<% } else { %>
|
||||||
|
<div class="table-wrap">
|
||||||
<table>
|
<table>
|
||||||
<tr><th>Дата</th><th>Действие</th><th>Кто</th><th>От имени</th><th>Компания</th><th>Значения</th></tr>
|
<thead>
|
||||||
<% if (audit.length === 0) { %><tr><td colspan="6">Нет записей</td></tr><% } %>
|
<tr>
|
||||||
|
<th>Дата</th>
|
||||||
|
<th>Действие</th>
|
||||||
|
<th>Кто</th>
|
||||||
|
<th>От имени</th>
|
||||||
|
<th>Компания</th>
|
||||||
|
<th>Значения</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
<% audit.forEach(function(a) { %>
|
<% audit.forEach(function(a) { %>
|
||||||
<tr>
|
<tr>
|
||||||
<td><%= new Date(a.created_at).toLocaleString('ru') %></td>
|
<td><%= new Date(a.created_at).toLocaleString('ru') %></td>
|
||||||
@@ -22,9 +97,14 @@
|
|||||||
<td><%= a.user_email %></td>
|
<td><%= a.user_email %></td>
|
||||||
<td><%= a.impersonated_by || '—' %></td>
|
<td><%= a.impersonated_by || '—' %></td>
|
||||||
<td><%= a.company_name || '—' %></td>
|
<td><%= a.company_name || '—' %></td>
|
||||||
<td><%= a.old_value || '—' %> → <%= a.new_value || '—' %></td>
|
<td><% if (a.old_value) { %><%= a.old_value %><% } else { %>—<% } %> → <% if (a.new_value) { %><%= a.new_value %><% } else { %>—<% } %></td>
|
||||||
</tr>
|
</tr>
|
||||||
<% }) %>
|
<% }) %>
|
||||||
|
</tbody>
|
||||||
</table>
|
</table>
|
||||||
<p>Показано: <%= audit.length %> (макс 500)</p>
|
</div>
|
||||||
</body></html>
|
<% } %>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
|
|||||||
+120
-28
@@ -1,47 +1,139 @@
|
|||||||
<!DOCTYPE html>
|
<!DOCTYPE html>
|
||||||
<html><head><meta charset="utf-8"><title>Admin — IP WhiteList v<%= version %></title>
|
<html lang="ru">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8">
|
||||||
|
<title>Лимиты и Аудит — IP WhiteList v<%= version %></title>
|
||||||
|
<link rel="icon" href="/favicon.png" type="image/png">
|
||||||
<style>
|
<style>
|
||||||
body{font-family:sans-serif;max-width:1100px;margin:20px auto;color:#222}
|
:root {
|
||||||
table{width:100%;border-collapse:collapse;margin:10px 0}
|
--bg: #f5f5f5; --card: #ffffff; --text: #1a1a1a; --muted: #6b7280;
|
||||||
th,td{border:1px solid #ccc;padding:6px;text-align:left}
|
--border: #d1d5db; --grey-light: #f3f4f6; --blue: #2563eb; --blue-h: #1d4ed8;
|
||||||
th{background:#263238;color:#fff}
|
--red: #dc2626; --green: #16a34a; --amber: #d97706;
|
||||||
.bar{display:flex;justify-content:space-between;align-items:center;background:#263238;color:#fff;padding:10px;margin-bottom:15px}
|
}
|
||||||
.bar a{color:#80cbc4}
|
* { box-sizing: border-box; margin: 0; padding: 0; }
|
||||||
button,input,select{padding:4px 8px}
|
body {
|
||||||
.msg{background:#4caf50;color:#fff;padding:8px;margin-bottom:10px}
|
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
|
||||||
.err{background:#f44336;color:#fff;padding:8px;margin-bottom:10px}
|
background: var(--bg); color: var(--text); font-size: 14px; line-height: 1.5;
|
||||||
</style></head><body>
|
}
|
||||||
<div class="bar">
|
.page { max-width: 1100px; margin: 1.5rem auto; padding: 0 1rem; }
|
||||||
<span><strong>🛡️ ADMIN</strong> v<%= version %></span>
|
.card {
|
||||||
<span><%= user.email || '—' %> | <a href="/v2/app">← Пользовательский</a> | <a href="/v2/logout">Выйти</a></span>
|
background: var(--card); border: 1px solid var(--border);
|
||||||
</div>
|
border-radius: 12px; box-shadow: 0 1px 2px rgba(0,0,0,.04);
|
||||||
|
margin-bottom: 1rem; overflow: hidden;
|
||||||
|
}
|
||||||
|
.card-header {
|
||||||
|
background: var(--grey-light); padding: .75rem 1rem;
|
||||||
|
font-weight: 600; font-size: 1rem; border-bottom: 1px solid var(--border);
|
||||||
|
}
|
||||||
|
.card-body { padding: 1rem; }
|
||||||
|
.alert { padding: .75rem 1rem; border-radius: 8px; margin-bottom: 1rem; font-size: .9rem; }
|
||||||
|
.alert-ok { background: #dcfce7; color: #166534; border: 1px solid #bbf7d0; }
|
||||||
|
.alert-err { background: #fecaca; color: #991b1b; border: 1px solid #fca5a5; }
|
||||||
|
.btn {
|
||||||
|
display: inline-flex; align-items: center; gap: .35rem;
|
||||||
|
padding: .4rem .85rem; border: 1px solid var(--border); border-radius: 6px;
|
||||||
|
font-size: .82rem; font-weight: 500; background: #fff; cursor: pointer;
|
||||||
|
text-decoration: none; color: var(--text); transition: background .15s;
|
||||||
|
}
|
||||||
|
.btn:hover { background: var(--grey-light); }
|
||||||
|
.btn-sm { padding: .3rem .65rem; font-size: .78rem; }
|
||||||
|
.btn-primary { background: var(--blue); color: #fff; border-color: var(--blue); }
|
||||||
|
.btn-primary:hover { background: var(--blue-h); }
|
||||||
|
.table-wrap { border: 1px solid var(--border); border-radius: 8px; overflow: hidden; }
|
||||||
|
table { width: 100%; border-collapse: collapse; font-size: .85rem; }
|
||||||
|
th {
|
||||||
|
text-align: left; padding: .5rem .75rem;
|
||||||
|
background: var(--grey-light); color: var(--muted);
|
||||||
|
font-weight: 500; font-size: .78rem; text-transform: uppercase; letter-spacing: .5px;
|
||||||
|
border-bottom: 1px solid var(--border); border-right: 1px solid var(--border);
|
||||||
|
}
|
||||||
|
th:last-child { border-right: none; }
|
||||||
|
td {
|
||||||
|
padding: .5rem .75rem; border-bottom: 1px solid var(--border);
|
||||||
|
border-right: 1px solid var(--border); vertical-align: middle;
|
||||||
|
}
|
||||||
|
td:last-child { border-right: none; }
|
||||||
|
tr:last-child td { border-bottom: none; }
|
||||||
|
tr:hover td { background: #f8fafc; }
|
||||||
|
code { background: #f1f5f9; padding: .15rem .4rem; border-radius: 3px; font-size: .9em; }
|
||||||
|
.empty { text-align: center; color: var(--muted); padding: 2rem; }
|
||||||
|
.limit-input {
|
||||||
|
width: 60px; padding: .3rem .5rem; border: 1px solid var(--border);
|
||||||
|
border-radius: 5px; font-size: .85rem; text-align: center;
|
||||||
|
}
|
||||||
|
.limit-input:focus { border-color: var(--blue); outline: none; box-shadow: 0 0 0 2px rgba(37,99,235,.1); }
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
|
||||||
|
<header style="background:#fff;border-bottom:1px solid var(--border);padding:0 1.5rem;height:48px;display:flex;align-items:center;gap:.75rem;font-size:.9rem;color:var(--muted);">
|
||||||
|
<svg width="130" height="28" viewBox="0 0 311 69" style="display:block;">
|
||||||
|
<g transform="translate(-330 -228)">
|
||||||
|
<path d="M348.061 246.203 332.42 246.203 330 256.661 336.75 256.661 336.794 295.573 336.794 296.585 336.795 296.585 347.25 296.585 347.25 263.611C347.25 259.78 350.368 256.663 354.2 256.663L376.489 256.793C380.322 256.793 383.44 259.912 383.44 263.743L383.44 296.717 393.896 296.717 393.896 263.743C393.896 254.144 386.087 246.338 376.495 246.338L354.196 246.204 348.061 246.221 348.061 246.203Z" fill="#001C34" fill-rule="evenodd"/>
|
||||||
|
<path d="M582.095 296.65 626.768 296.65C634.793 296.65 641 290.03 641 282.009 641 273.985 634.473 267.458 626.449 267.458L601.724 267.458C599.446 267.458 597.595 265.607 597.595 263.328L597.595 260.825C597.595 258.548 599.446 256.697 601.724 256.697L628.041 256.697 630.452 246.276 601.724 246.276C593.7 246.276 587.174 252.802 587.174 260.825L587.174 263.328C587.174 271.352 593.7 277.879 601.724 277.879L626.449 277.879C628.726 277.879 630.579 279.732 630.579 282.009 630.579 284.283 628.726 286.4 626.449 286.4L584.126 286.4 582.095 296.65Z" fill="#001C34" fill-rule="evenodd"/>
|
||||||
|
<path d="M564.549 246.347 537.193 246.347C529.027 246.347 522.385 252.989 522.385 261.156L522.385 279.521C522.385 288.916 530.028 296.557 539.422 296.557L576.846 296.557 579.196 286.401 539.422 286.401C535.775 286.401 532.805 283.172 532.805 279.521L532.748 278.028 567.684 278.028 579.354 277.959 579.354 268.958 579.354 261.156C579.354 252.989 572.712 246.347 564.549 246.347ZM568.935 267.54 532.805 267.54 532.805 261.156C532.805 258.737 534.774 256.767 537.193 256.767L564.549 256.767C566.966 256.767 568.935 258.737 568.935 261.156L568.935 267.54Z" fill="#001C34" fill-rule="evenodd"/>
|
||||||
|
<path d="M507.156 273.231 507.156 279.597C507.156 283.414 504.066 286.344 500.247 286.344L477.934 286.39C474.41 286.39 471.493 283.744 471.064 280.335L471.064 263.006C471.494 259.597 474.41 256.951 477.934 256.951L500.23 257.083C504.049 257.083 507.156 260.192 507.156 264.009L507.156 265.16 507.156 273.232ZM460.623 260.161 460.589 230.089 471.064 228.058 471.064 247.957C473.172 247.043 475.49 246.53 477.929 246.53L500.235 246.662C509.793 246.662 517.575 254.444 517.575 264.009L517.575 265.159 517.575 273.231 517.575 279.597C517.575 289.161 509.793 296.941 500.235 296.941L477.929 296.809C468.37 296.809 460.589 289.029 460.589 279.464L460.589 272.972 460.589 263.876 460.623 260.161Z" fill="#001C34" fill-rule="evenodd"/>
|
||||||
|
<path d="M445.037 271.59 445.037 279.317C445.037 283.134 441.93 286.241 438.111 286.241L416.092 286.11C412.273 286.11 409.166 283.002 409.166 279.185L409.166 276.635 409.222 276.644 409.222 244.013 398.748 246.044 398.752 249.955 398.748 249.957 398.748 279.184C398.748 288.749 406.529 296.529 416.087 296.529L438.116 296.661C447.674 296.661 455.456 288.881 455.456 279.316L455.456 276.639 455.482 276.643 455.482 244.013 445.008 246.043 445.037 271.589Z" fill="#001C34" fill-rule="evenodd"/>
|
||||||
|
</g>
|
||||||
|
</svg>
|
||||||
|
<span>|</span>
|
||||||
|
<span style="font-weight:500;color:var(--text);">Лимиты и Аудит</span>
|
||||||
|
<span style="margin-left:auto;display:flex;gap:.5rem;align-items:center;">
|
||||||
|
<span style="font-weight:500;color:var(--text);"><%= user.email %></span>
|
||||||
|
<a href="/v2/app" class="btn btn-sm">← Назад</a>
|
||||||
|
</span>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
<div class="page">
|
||||||
|
|
||||||
<script>
|
<script>
|
||||||
const p=new URLSearchParams(location.search);
|
var 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('msg')){document.write('<div class="alert alert-ok">'+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('error')){document.write('<div class="alert alert-err">'+p.get('error')+'</div>');history.replaceState(null,'','/v2/admin');}
|
||||||
</script>
|
</script>
|
||||||
<h2>Компании (<%= companies.length %>)</h2>
|
|
||||||
|
<div class="card">
|
||||||
|
<div class="card-header">Компании и лимиты <span style="font-weight:400;font-size:.82rem;color:var(--muted);">(дефолт: 15)</span></div>
|
||||||
|
<% if (companies.length === 0) { %>
|
||||||
|
<div class="empty">Нет компаний в системе</div>
|
||||||
|
<% } else { %>
|
||||||
|
<div class="table-wrap">
|
||||||
<table>
|
<table>
|
||||||
<tr><th>Компания</th><th>Client ID</th><th>Записей</th><th>Лимит</th><th></th><th>Новый лимит</th></tr>
|
<thead>
|
||||||
<% if (companies.length === 0) { %><tr><td colspan="6">Нет компаний</td></tr><% } %>
|
<tr>
|
||||||
|
<th>Компания</th>
|
||||||
|
<th>Client ID</th>
|
||||||
|
<th>Записей</th>
|
||||||
|
<th>Лимит</th>
|
||||||
|
<th></th>
|
||||||
|
<th>Новый лимит</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
<% companies.forEach(function(c) { %>
|
<% companies.forEach(function(c) { %>
|
||||||
<tr>
|
<tr>
|
||||||
<td><%= c.name || c.client_id %></td>
|
<td><strong><%= c.name || c.client_id %></strong></td>
|
||||||
<td><code><%= c.client_id %></code></td>
|
<td><code><%= c.client_id %></code></td>
|
||||||
<td><strong><%= c.active_count %></strong> / <%= c.custom_limit != null ? c.custom_limit : 15 %></td>
|
<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><%= c.custom_limit != null ? c.custom_limit : '—' %></td>
|
||||||
<td>
|
<td>
|
||||||
<a href="/v2/admin/audit?companyId=<%= c.id %>">аудит</a> |
|
<a href="/v2/admin/audit?companyId=<%= c.id %>" class="btn btn-sm">аудит</a>
|
||||||
<a href="/v2/admin/entries?companyId=<%= c.id %>">записи</a>
|
|
||||||
</td>
|
</td>
|
||||||
<td>
|
<td>
|
||||||
<form method="POST" action="/v2/admin/limit" style="display:inline">
|
<form method="POST" action="/v2/admin/limit" style="display:inline-flex;gap:.4rem;align-items:center;">
|
||||||
<input type="hidden" name="companyId" value="<%= c.id %>">
|
<input type="hidden" name="companyId" value="<%= c.id %>">
|
||||||
<input name="limit" value="<%= c.custom_limit || 15 %>" size="3">
|
<input class="limit-input" name="limit" type="number" min="1" value="<%= c.custom_limit || 15 %>">
|
||||||
<button>установить</button>
|
<button class="btn btn-sm btn-primary">установить</button>
|
||||||
</form>
|
</form>
|
||||||
</td>
|
</td>
|
||||||
</tr>
|
</tr>
|
||||||
<% }) %>
|
<% }) %>
|
||||||
|
</tbody>
|
||||||
</table>
|
</table>
|
||||||
</body></html>
|
</div>
|
||||||
|
<% } %>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
</div>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
|
|||||||
+253
-55
@@ -1,68 +1,266 @@
|
|||||||
<!DOCTYPE html>
|
<!DOCTYPE html>
|
||||||
<html><head><meta charset="utf-8"><title>V2 IP WhiteList</title>
|
<html lang="ru">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8">
|
||||||
|
<title>IP WhiteList v<%= version %></title>
|
||||||
|
<link rel="icon" href="/favicon.png" type="image/png">
|
||||||
<style>
|
<style>
|
||||||
body{font-family:sans-serif;max-width:960px;margin:20px auto;color:#222}
|
:root {
|
||||||
table{width:100%;border-collapse:collapse;margin:10px 0}
|
--bg: #f5f5f5; --card: #ffffff; --text: #1a1a1a; --muted: #6b7280;
|
||||||
th,td{border:1px solid #ccc;padding:6px;text-align:left}
|
--border: #d1d5db; --grey-light: #f3f4f6; --blue: #2563eb; --blue-h: #1d4ed8;
|
||||||
th{background:#f5f5f5}
|
--red: #dc2626; --red-h: #b91c1c; --green: #16a34a; --amber: #d97706;
|
||||||
.bar{display:flex;justify-content:space-between;align-items:center;background:#eee;padding:10px;margin-bottom:10px}
|
}
|
||||||
button,input,select{padding:4px 8px}
|
* { box-sizing: border-box; margin: 0; padding: 0; }
|
||||||
.add-form{background:#f0f8ff;padding:10px;margin:10px 0}
|
body {
|
||||||
</style></head><body>
|
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
|
||||||
<div class="bar">
|
background: var(--bg); color: var(--text); font-size: 14px; line-height: 1.5;
|
||||||
<span><strong>V2 IP WhiteList</strong> <small>v<%= version %></small></span>
|
}
|
||||||
<span><%= user.email %> <% if (user.isAdmin) { %>| <a href="/v2/admin">ADMIN</a><% } %></span>
|
.page { max-width: 1100px; margin: 1.5rem auto; padding: 0 1rem; }
|
||||||
<span>
|
|
||||||
<form method="GET" action="/v2/app" style="display:inline">
|
/* Cards */
|
||||||
<select name="switchTo" onchange="this.form.submit()">
|
.card {
|
||||||
|
background: var(--card); border: 1px solid var(--border);
|
||||||
|
border-radius: 12px; box-shadow: 0 1px 2px rgba(0,0,0,.04);
|
||||||
|
margin-bottom: 1rem; overflow: hidden;
|
||||||
|
}
|
||||||
|
.card-header {
|
||||||
|
background: var(--grey-light); padding: .75rem 1rem;
|
||||||
|
font-weight: 600; font-size: 1rem; border-bottom: 1px solid var(--border);
|
||||||
|
}
|
||||||
|
.card-body { padding: 1rem; }
|
||||||
|
|
||||||
|
/* Alerts */
|
||||||
|
.alert { padding: .75rem 1rem; border-radius: 8px; margin-bottom: 1rem; font-size: .9rem; }
|
||||||
|
.alert-ok { background: #dcfce7; color: #166534; border: 1px solid #bbf7d0; }
|
||||||
|
.alert-err { background: #fecaca; color: #991b1b; border: 1px solid #fca5a5; }
|
||||||
|
.alert-warn{ background: #fef3c7; color: #92400e; border: 1px solid #fde68a; }
|
||||||
|
|
||||||
|
/* Stats row */
|
||||||
|
.stats { display: flex; gap: 2rem; }
|
||||||
|
.stat { text-align: center; }
|
||||||
|
.stat .num { font-size: 1.6rem; font-weight: 700; }
|
||||||
|
.stat .lbl { font-size: .8rem; color: var(--muted); }
|
||||||
|
.stat.full .num { color: var(--red); }
|
||||||
|
|
||||||
|
/* Form */
|
||||||
|
.form-grid {
|
||||||
|
display: grid; grid-template-columns: 1fr 1fr auto; gap: .75rem 1rem; align-items: end;
|
||||||
|
}
|
||||||
|
.field { display: flex; flex-direction: column; gap: .25rem; }
|
||||||
|
.field label {
|
||||||
|
font-size: .8rem; font-weight: 500; color: var(--muted);
|
||||||
|
text-transform: uppercase; letter-spacing: .5px;
|
||||||
|
}
|
||||||
|
.field input {
|
||||||
|
padding: .5rem .75rem; border: 1px solid var(--border);
|
||||||
|
border-radius: 6px; font-size: .9rem; outline: none; transition: border .15s; background: #fff;
|
||||||
|
}
|
||||||
|
.field input:focus { border-color: var(--blue); box-shadow: 0 0 0 3px rgba(37,99,235,.1); }
|
||||||
|
|
||||||
|
/* Buttons */
|
||||||
|
.btn {
|
||||||
|
display: inline-flex; align-items: center; gap: .35rem;
|
||||||
|
padding: .5rem 1rem; border: 1px solid var(--border); border-radius: 6px;
|
||||||
|
font-size: .85rem; font-weight: 500; background: #fff; cursor: pointer;
|
||||||
|
transition: background .15s; white-space: nowrap; text-decoration: none; color: var(--text);
|
||||||
|
}
|
||||||
|
.btn:hover { background: var(--grey-light); }
|
||||||
|
.btn-sm { padding: .3rem .65rem; font-size: .78rem; }
|
||||||
|
.btn-primary { background: var(--blue); color: #fff; border-color: var(--blue); }
|
||||||
|
.btn-primary:hover { background: var(--blue-h); }
|
||||||
|
.btn-primary:disabled { background: #93c5fd; cursor: not-allowed; border-color: #93c5fd; }
|
||||||
|
.btn-danger { color: var(--red); border-color: var(--red); }
|
||||||
|
.btn-danger:hover { background: #fecaca; }
|
||||||
|
|
||||||
|
/* Table */
|
||||||
|
.table-wrap { border: 1px solid var(--border); border-radius: 8px; overflow: hidden; }
|
||||||
|
table { width: 100%; border-collapse: collapse; font-size: .85rem; }
|
||||||
|
th {
|
||||||
|
text-align: left; padding: .5rem .75rem;
|
||||||
|
background: var(--grey-light); color: var(--muted);
|
||||||
|
font-weight: 500; font-size: .8rem; text-transform: uppercase; letter-spacing: .5px;
|
||||||
|
border-bottom: 1px solid var(--border); border-right: 1px solid var(--border);
|
||||||
|
}
|
||||||
|
th:last-child { border-right: none; }
|
||||||
|
td {
|
||||||
|
padding: .5rem .75rem; border-bottom: 1px solid var(--border);
|
||||||
|
border-right: 1px solid var(--border); vertical-align: middle;
|
||||||
|
}
|
||||||
|
td:last-child { border-right: none; }
|
||||||
|
tr:last-child td { border-bottom: none; }
|
||||||
|
tr:hover td { background: #f8fafc; }
|
||||||
|
code { background: #f1f5f9; padding: .15rem .4rem; border-radius: 3px; font-size: .9em; }
|
||||||
|
.empty { text-align: center; color: var(--muted); padding: 2rem; }
|
||||||
|
|
||||||
|
/* Select */
|
||||||
|
select {
|
||||||
|
padding: .4rem .75rem; border: 1px solid var(--border); border-radius: 6px;
|
||||||
|
font-size: .85rem; background: #fff; outline: none; cursor: pointer;
|
||||||
|
}
|
||||||
|
select:focus { border-color: var(--blue); box-shadow: 0 0 0 2px rgba(37,99,235,.1); }
|
||||||
|
</style>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
|
||||||
|
<header style="background:#fff;border-bottom:1px solid var(--border);padding:0 1.5rem;height:48px;display:flex;align-items:center;gap:.75rem;font-size:.9rem;color:var(--muted);">
|
||||||
|
<svg width="130" height="28" viewBox="0 0 311 69" style="display:block;">
|
||||||
|
<g transform="translate(-330 -228)">
|
||||||
|
<path d="M348.061 246.203 332.42 246.203 330 256.661 336.75 256.661 336.794 295.573 336.794 296.585 336.795 296.585 347.25 296.585 347.25 263.611C347.25 259.78 350.368 256.663 354.2 256.663L376.489 256.793C380.322 256.793 383.44 259.912 383.44 263.743L383.44 296.717 393.896 296.717 393.896 263.743C393.896 254.144 386.087 246.338 376.495 246.338L354.196 246.204 348.061 246.221 348.061 246.203Z" fill="#001C34" fill-rule="evenodd"/>
|
||||||
|
<path d="M582.095 296.65 626.768 296.65C634.793 296.65 641 290.03 641 282.009 641 273.985 634.473 267.458 626.449 267.458L601.724 267.458C599.446 267.458 597.595 265.607 597.595 263.328L597.595 260.825C597.595 258.548 599.446 256.697 601.724 256.697L628.041 256.697 630.452 246.276 601.724 246.276C593.7 246.276 587.174 252.802 587.174 260.825L587.174 263.328C587.174 271.352 593.7 277.879 601.724 277.879L626.449 277.879C628.726 277.879 630.579 279.732 630.579 282.009 630.579 284.283 628.726 286.4 626.449 286.4L584.126 286.4 582.095 296.65Z" fill="#001C34" fill-rule="evenodd"/>
|
||||||
|
<path d="M564.549 246.347 537.193 246.347C529.027 246.347 522.385 252.989 522.385 261.156L522.385 279.521C522.385 288.916 530.028 296.557 539.422 296.557L576.846 296.557 579.196 286.401 539.422 286.401C535.775 286.401 532.805 283.172 532.805 279.521L532.748 278.028 567.684 278.028 579.354 277.959 579.354 268.958 579.354 261.156C579.354 252.989 572.712 246.347 564.549 246.347ZM568.935 267.54 532.805 267.54 532.805 261.156C532.805 258.737 534.774 256.767 537.193 256.767L564.549 256.767C566.966 256.767 568.935 258.737 568.935 261.156L568.935 267.54Z" fill="#001C34" fill-rule="evenodd"/>
|
||||||
|
<path d="M507.156 273.231 507.156 279.597C507.156 283.414 504.066 286.344 500.247 286.344L477.934 286.39C474.41 286.39 471.493 283.744 471.064 280.335L471.064 263.006C471.494 259.597 474.41 256.951 477.934 256.951L500.23 257.083C504.049 257.083 507.156 260.192 507.156 264.009L507.156 265.16 507.156 273.232ZM460.623 260.161 460.589 230.089 471.064 228.058 471.064 247.957C473.172 247.043 475.49 246.53 477.929 246.53L500.235 246.662C509.793 246.662 517.575 254.444 517.575 264.009L517.575 265.159 517.575 273.231 517.575 279.597C517.575 289.161 509.793 296.941 500.235 296.941L477.929 296.809C468.37 296.809 460.589 289.029 460.589 279.464L460.589 272.972 460.589 263.876 460.623 260.161Z" fill="#001C34" fill-rule="evenodd"/>
|
||||||
|
<path d="M445.037 271.59 445.037 279.317C445.037 283.134 441.93 286.241 438.111 286.241L416.092 286.11C412.273 286.11 409.166 283.002 409.166 279.185L409.166 276.635 409.222 276.644 409.222 244.013 398.748 246.044 398.752 249.955 398.748 249.957 398.748 279.184C398.748 288.749 406.529 296.529 416.087 296.529L438.116 296.661C447.674 296.661 455.456 288.881 455.456 279.316L455.456 276.639 455.482 276.643 455.482 244.013 445.008 246.043 445.037 271.589Z" fill="#001C34" fill-rule="evenodd"/>
|
||||||
|
</g>
|
||||||
|
</svg>
|
||||||
|
<span>|</span>
|
||||||
|
<span style="font-weight:500;color:var(--text);">IP WhiteList v<%= version %></span>
|
||||||
|
|
||||||
|
<span style="margin-left:auto;display:flex;gap:.5rem;align-items:center;">
|
||||||
|
<span style="font-weight:500;color:var(--text);"><%= user.email %></span>
|
||||||
|
<a href="/v2/logout" class="btn btn-sm">Выйти<% if (user.isImpersonated && user.originalUserEmail) { %> (<%= user.originalUserEmail %>)<% } %></a>
|
||||||
|
</span>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
<div class="page">
|
||||||
|
|
||||||
|
<script>
|
||||||
|
var p=new URLSearchParams(location.search);
|
||||||
|
if(p.get('msg')){document.write('<div class="alert alert-ok">'+p.get('msg')+'</div>');history.replaceState(null,'','/v2/app');}
|
||||||
|
if(p.get('error')){document.write('<div class="alert alert-err">'+p.get('error')+'</div>');history.replaceState(null,'','/v2/app');}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<% if (user.isImpersonated) { %>
|
||||||
|
<div class="alert alert-warn">
|
||||||
|
⚠️ Режим имперсонации — данные сохраняются от имени <strong><%= activeClientId %></strong>
|
||||||
|
<% if (user.originalUserEmail) { %> (вы: <%= user.originalUserEmail %>)<% } %>
|
||||||
|
</div>
|
||||||
|
<% } %>
|
||||||
|
|
||||||
|
<!-- Выбор компании -->
|
||||||
|
<div class="card">
|
||||||
|
<div class="card-body" style="padding:.75rem 1rem;">
|
||||||
|
<form method="GET" action="/v2/app" style="display:flex;align-items:center;gap:1rem;flex-wrap:wrap;">
|
||||||
|
<span style="font-size:.85rem;color:var(--muted);font-weight:500;">Компания:</span>
|
||||||
|
<select name="switchTo" onchange="console.log('onchange fired', this.value); this.form.submit()">
|
||||||
<% companies.forEach(function(c) { %>
|
<% companies.forEach(function(c) { %>
|
||||||
<option value="<%= c.client_id %>" <%= c.client_id === activeClientId ? 'selected' : '' %>><%= c.company_name || c.client_id %> (<%= c.client_id %>)</option>
|
<option value="<%= c.client_id %>" <%= c.client_id === activeClientId ? 'selected' : '' %>>
|
||||||
|
<%= c.name %> (<%= c.client_id %>)<% if (c.isPersonal) { %> (личное)<% } %><% if (c.active_count != null) { %> — <%= c.active_count %> зап.<% } %>
|
||||||
|
</option>
|
||||||
<% }) %>
|
<% }) %>
|
||||||
</select>
|
</select>
|
||||||
</form>
|
<a href="?deleted=<%= includeDeleted ? '0' : '1' %>" class="btn btn-sm"><%= includeDeleted ? 'Скрыть удалённые' : 'Показать удалённые' %></a>
|
||||||
<a href="/v2/logout">Выйти</a>
|
<% if (user.isAdmin) { %>
|
||||||
</span>
|
<span style="margin-left:auto;font-size:.8rem;color:var(--amber);">Режим: Администратор</span>
|
||||||
</div>
|
<a href="/v2/admin" class="btn btn-sm">Лимиты и Аудит</a>
|
||||||
<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>
|
|
||||||
<% if (entries.length === 0) { %>
|
|
||||||
<tr><td colspan="5">Нет записей</td></tr>
|
|
||||||
<% } %>
|
<% } %>
|
||||||
<% entries.forEach(function(e) { %>
|
|
||||||
<tr style="<%= e.deleted_at ? 'text-decoration:line-through;opacity:0.5' : '' %>">
|
|
||||||
<td><%= e.value_cidr %></td>
|
|
||||||
<td><%= e.comment || '' %></td>
|
|
||||||
<td><%= e.created_by %></td>
|
|
||||||
<td><%= new Date(e.created_at).toLocaleString('ru') %></td>
|
|
||||||
<td>
|
|
||||||
<% if (e.deleted_at) { %>
|
|
||||||
<span style="color:#888">удалено</span>
|
|
||||||
<% } else { %>
|
|
||||||
<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>
|
||||||
<form method="POST" action="/v2/app/delete/<%= e.id %>" style="display:inline">
|
</div>
|
||||||
<button onclick="return confirm('Удалить?')">удалить</button>
|
</div>
|
||||||
|
|
||||||
|
<!-- Статистика -->
|
||||||
|
<div class="card">
|
||||||
|
<div class="card-body">
|
||||||
|
<div class="stats">
|
||||||
|
<div class="stat<%= used >= limit ? ' full' : '' %>">
|
||||||
|
<div class="num"><%= used %> / <%= limit %></div>
|
||||||
|
<div class="lbl">записей</div>
|
||||||
|
</div>
|
||||||
|
<div class="stat">
|
||||||
|
<div class="num"><%= activeClientId %></div>
|
||||||
|
<div class="lbl">компания</div>
|
||||||
|
</div>
|
||||||
|
<div class="stat">
|
||||||
|
<div class="num"><%= user.email %></div>
|
||||||
|
<div class="lbl">пользователь</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Форма добавления -->
|
||||||
|
<div class="card">
|
||||||
|
<div class="card-header">Добавить адрес</div>
|
||||||
|
<div class="card-body">
|
||||||
|
<form method="POST" action="/v2/app/add">
|
||||||
|
<div class="form-grid">
|
||||||
|
<div class="field">
|
||||||
|
<label>IPv4 адрес или подсеть CIDR</label>
|
||||||
|
<input name="cidr" placeholder="Например: 203.0.113.10 или 203.0.113.0/24" maxlength="18" required <%= used >= limit ? 'disabled' : '' %>>
|
||||||
|
</div>
|
||||||
|
<div class="field">
|
||||||
|
<label>Комментарий</label>
|
||||||
|
<input name="comment" placeholder="Необязательно" maxlength="255">
|
||||||
|
</div>
|
||||||
|
<button class="btn btn-primary" type="submit" <%= used >= limit ? 'disabled' : '' %> style="align-self:end">
|
||||||
|
<%= used >= limit ? 'Лимит исчерпан' : 'Добавить' %>
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- Таблица -->
|
||||||
|
<div class="card">
|
||||||
|
<div class="card-header">Доверенные адреса</div>
|
||||||
|
<% if (entries.length === 0) { %>
|
||||||
|
<div class="empty">Нет добавленных адресов</div>
|
||||||
|
<% } else { %>
|
||||||
|
<div class="table-wrap">
|
||||||
|
<table>
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th style="width:1%;white-space:nowrap;">Адрес</th>
|
||||||
|
<th>Комментарий</th>
|
||||||
|
<th>Добавил</th>
|
||||||
|
<th style="font-size:.78rem;width:1%;">Добавлена</th>
|
||||||
|
<th style="text-align:center;white-space:nowrap;">Правка</th>
|
||||||
|
<th style="width:1%;"></th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
<% entries.forEach(function(e) { %>
|
||||||
|
<tr style="<%= e.deleted_at ? 'opacity:.5;text-decoration:line-through;' : '' %>">
|
||||||
|
<td style="white-space:nowrap;"><code><%= e.value_cidr %></code><% if (e.deleted_at) { %> <span style="font-size:.7rem;color:var(--red);">уд.</span><% } %></td>
|
||||||
|
<td><%= e.comment || '—' %></td>
|
||||||
|
<td style="white-space:nowrap;"><%= e.created_by %></td>
|
||||||
|
<td style="font-size:.72rem;line-height:1.2;"><%= new Date(e.created_at).toLocaleString('ru', {timeZone:'Europe/Moscow'}) %> МСК</td>
|
||||||
|
<td style="text-align:center;white-space:nowrap;">
|
||||||
|
<% if (!e.deleted_at) { %>
|
||||||
|
<form method="POST" action="/v2/app/edit/<%= e.id %>" style="display:inline;">
|
||||||
|
<input name="cidr" value="<%= e.value_cidr %>" size="18" style="width:125px;padding:.2rem .3rem;border:1px solid var(--border);border-radius:4px;font-size:.78rem;">
|
||||||
|
<input name="comment" value="<%= e.comment || '' %>" size="30" style="width:200px;padding:.2rem .3rem;border:1px solid var(--border);border-radius:4px;font-size:.78rem;">
|
||||||
|
<button class="btn btn-sm" title="Сохранить">💾</button>
|
||||||
|
</form>
|
||||||
|
<% } else { %>
|
||||||
|
<span style="color:var(--muted);font-size:.78rem;">удалена</span>
|
||||||
|
<% } %>
|
||||||
|
</td>
|
||||||
|
<td style="text-align:center;">
|
||||||
|
<% if (!e.deleted_at) { %>
|
||||||
|
<form method="POST" action="/v2/app/delete/<%= e.id %>" style="display:inline;">
|
||||||
|
<input type="hidden" name="deleted" value="<%= includeDeleted ? '1' : '0' %>">
|
||||||
|
<button type="submit" class="btn btn-sm btn-danger" onclick="return confirm('Удалить?')" title="Удалить">🗑️</button>
|
||||||
|
</form>
|
||||||
|
<% } else { %>
|
||||||
|
<form method="POST" action="/v2/app/restore/<%= e.id %>" style="display:inline;">
|
||||||
|
<input type="hidden" name="deleted" value="<%= includeDeleted ? '1' : '0' %>">
|
||||||
|
<button type="submit" class="btn btn-sm" title="Восстановить" style="color:var(--green);border-color:var(--green);">↺</button>
|
||||||
</form>
|
</form>
|
||||||
<% } %>
|
<% } %>
|
||||||
</td>
|
</td>
|
||||||
</tr>
|
</tr>
|
||||||
<% }) %>
|
<% }) %>
|
||||||
|
</tbody>
|
||||||
</table>
|
</table>
|
||||||
<p><a href="/v2/app?deleted=<%= includeDeleted ? '0' : '1' %>"><%= includeDeleted ? 'Скрыть удалённые' : 'Показать удалённые' %></a></p>
|
</div>
|
||||||
</body></html>
|
<% } %>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<footer style="display:flex;justify-content:space-between;align-items:center;padding:.5rem 1.5rem;font-size:.72rem;color:var(--muted);">
|
||||||
|
<span><% if (user.isAdmin) { %>Для вывода списка: <a href="/v2/export?view=1" style="color:var(--muted);"><%= 'https://whitelist.nodejsk8s.services.ngcloud.ru/export' %></a><% } %></span>
|
||||||
|
<span>v<%= version %></span>
|
||||||
|
</footer>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
|
|||||||
Reference in New Issue
Block a user