ФУНКЦИИ - МЕЖПРОЕКТНАЯ КОММУНИКАЦИЯ: Launcher control plane и доступы
This commit is contained in:
parent
de0a0d2948
commit
b221ccb83e
File diff suppressed because it is too large
Load Diff
Binary file not shown.
|
After Width: | Height: | Size: 602 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 308 KiB |
|
|
@ -0,0 +1,236 @@
|
|||
import { existsSync, readFileSync } from "node:fs";
|
||||
import { mkdir, writeFile } from "node:fs/promises";
|
||||
import { dirname, join } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
|
||||
const projectRoot = dirname(dirname(fileURLToPath(import.meta.url)));
|
||||
const publicDataPath = join(projectRoot, "public", "storage", "launcher-data.json");
|
||||
const distDataPath = join(projectRoot, "dist", "storage", "launcher-data.json");
|
||||
|
||||
const now = new Date().toISOString();
|
||||
const existingData = readJson(publicDataPath);
|
||||
const services = Array.isArray(existingData.services) ? existingData.services : [];
|
||||
const existingUsersByEmail = new Map(
|
||||
(Array.isArray(existingData.users) ? existingData.users : []).map((user) => [String(user.email || "").toLowerCase(), user])
|
||||
);
|
||||
const dcTouchAuthentikUserId = existingUsersByEmail.get("dcctouch@gmail.com")?.authentikUserId ?? null;
|
||||
const silverPsihAuthentikUserId = existingUsersByEmail.get("silver_psih@yahoo.com")?.authentikUserId ?? null;
|
||||
|
||||
const liveData = {
|
||||
...existingData,
|
||||
clients: [
|
||||
{
|
||||
id: "client_romashka",
|
||||
type: "company",
|
||||
name: "DCTOUCH",
|
||||
legalName: "ООО ДИСИТАЧ",
|
||||
status: "active",
|
||||
contractStartsAt: "2026-05-04T00:00:00.000Z",
|
||||
contractEndsAt: null,
|
||||
paidUntil: null,
|
||||
demoEndsAt: null,
|
||||
contactName: "DC Touch",
|
||||
contactEmail: "dcctouch@gmail.com",
|
||||
notes: "Live-клиент NODE.DC для первичной проверки control-plane, SSO и доступа к сервисам.",
|
||||
createdAt: "2026-05-04T00:00:00.000Z",
|
||||
updatedAt: now,
|
||||
},
|
||||
],
|
||||
users: [
|
||||
{
|
||||
id: "user_root",
|
||||
authentikUserId: dcTouchAuthentikUserId,
|
||||
name: "DC Touch",
|
||||
email: "dcctouch@gmail.com",
|
||||
phone: null,
|
||||
position: "NODE.DC Super Admin",
|
||||
notes: "Главный супер-администратор NODE.DC. Authentik-пользователь уже создан в dev-контуре.",
|
||||
avatarUrl: null,
|
||||
globalStatus: "active",
|
||||
createdAt: "2026-05-04T00:00:00.000Z",
|
||||
updatedAt: now,
|
||||
},
|
||||
{
|
||||
id: "user_silver_psih",
|
||||
authentikUserId: silverPsihAuthentikUserId,
|
||||
name: "Silver Psy",
|
||||
email: "silver_psih@yahoo.com",
|
||||
phone: null,
|
||||
position: "Manager",
|
||||
notes: "Живой пользователь из Plane. Требует создания/синхронизации в Authentik через Launcher flow.",
|
||||
avatarUrl: null,
|
||||
globalStatus: "active",
|
||||
createdAt: "2026-05-04T00:00:00.000Z",
|
||||
updatedAt: now,
|
||||
},
|
||||
],
|
||||
memberships: [
|
||||
{
|
||||
id: "mem_dc_touch_dctouch",
|
||||
clientId: "client_romashka",
|
||||
userId: "user_root",
|
||||
role: "client_owner",
|
||||
status: "active",
|
||||
createdAt: "2026-05-04T00:00:00.000Z",
|
||||
updatedAt: now,
|
||||
},
|
||||
{
|
||||
id: "mem_silver_psih_dctouch",
|
||||
clientId: "client_romashka",
|
||||
userId: "user_silver_psih",
|
||||
role: "member",
|
||||
status: "active",
|
||||
createdAt: "2026-05-04T00:00:00.000Z",
|
||||
updatedAt: now,
|
||||
},
|
||||
],
|
||||
groups: [
|
||||
{
|
||||
id: "group_dctouch_admins",
|
||||
clientId: "client_romashka",
|
||||
name: "Администраторы",
|
||||
description: "Администраторы клиента и владельцы платформенного доступа.",
|
||||
memberIds: ["user_root"],
|
||||
createdAt: "2026-05-04T00:00:00.000Z",
|
||||
updatedAt: now,
|
||||
},
|
||||
{
|
||||
id: "group_dctouch_managers",
|
||||
clientId: "client_romashka",
|
||||
name: "Менеджеры",
|
||||
description: "Рабочая группа менеджеров с доступом к операционному контуру.",
|
||||
memberIds: ["user_silver_psih"],
|
||||
createdAt: "2026-05-04T00:00:00.000Z",
|
||||
updatedAt: now,
|
||||
},
|
||||
],
|
||||
grants: [
|
||||
{
|
||||
id: "grant_dctouch_task_admins",
|
||||
serviceId: "service_task_manager",
|
||||
targetType: "group",
|
||||
targetId: "group_dctouch_admins",
|
||||
appRole: "admin",
|
||||
status: "active",
|
||||
createdAt: "2026-05-04T00:00:00.000Z",
|
||||
updatedAt: now,
|
||||
},
|
||||
{
|
||||
id: "grant_dctouch_task_managers",
|
||||
serviceId: "service_task_manager",
|
||||
targetType: "group",
|
||||
targetId: "group_dctouch_managers",
|
||||
appRole: "member",
|
||||
status: "active",
|
||||
createdAt: "2026-05-04T00:00:00.000Z",
|
||||
updatedAt: now,
|
||||
},
|
||||
{
|
||||
id: "grant_dctouch_nodedc_admins",
|
||||
serviceId: "service_nodedc",
|
||||
targetType: "group",
|
||||
targetId: "group_dctouch_admins",
|
||||
appRole: "admin",
|
||||
status: "active",
|
||||
createdAt: "2026-05-04T00:00:00.000Z",
|
||||
updatedAt: now,
|
||||
},
|
||||
],
|
||||
exceptions: [],
|
||||
invites: [],
|
||||
syncStatuses: [
|
||||
{
|
||||
id: "sync_dctouch_client_authentik",
|
||||
objectId: "client_romashka",
|
||||
objectName: "DCTOUCH",
|
||||
objectType: "client",
|
||||
target: "authentik",
|
||||
state: "synced",
|
||||
lastSyncAt: now,
|
||||
error: null,
|
||||
updatedAt: now,
|
||||
},
|
||||
{
|
||||
id: "sync_dc_touch_authentik",
|
||||
objectId: "user_root",
|
||||
objectName: "dcctouch@gmail.com",
|
||||
objectType: "user",
|
||||
target: "authentik",
|
||||
state: dcTouchAuthentikUserId ? "synced" : "pending",
|
||||
lastSyncAt: dcTouchAuthentikUserId ? now : null,
|
||||
error: dcTouchAuthentikUserId ? null : "Пользователь есть в Authentik, но Launcher seed ещё не содержит Authentik UUID.",
|
||||
updatedAt: now,
|
||||
},
|
||||
{
|
||||
id: "sync_silver_psih_authentik",
|
||||
objectId: "user_silver_psih",
|
||||
objectName: "silver_psih@yahoo.com",
|
||||
objectType: "user",
|
||||
target: "authentik",
|
||||
state: silverPsihAuthentikUserId ? "synced" : "pending",
|
||||
lastSyncAt: silverPsihAuthentikUserId ? now : null,
|
||||
error: silverPsihAuthentikUserId
|
||||
? null
|
||||
: "Пользователь найден в Plane, но ещё не создан в Authentik через Launcher invite/sync flow.",
|
||||
updatedAt: now,
|
||||
},
|
||||
{
|
||||
id: "sync_dctouch_groups_authentik",
|
||||
objectId: "client_romashka:groups",
|
||||
objectName: "DCTOUCH groups",
|
||||
objectType: "group",
|
||||
target: "authentik",
|
||||
state: "pending",
|
||||
lastSyncAt: null,
|
||||
error: null,
|
||||
updatedAt: now,
|
||||
},
|
||||
{
|
||||
id: "sync_task_manager_authentik",
|
||||
objectId: "service_task_manager",
|
||||
objectName: "OPERATIONAL CORE",
|
||||
objectType: "service",
|
||||
target: "authentik",
|
||||
state: "synced",
|
||||
lastSyncAt: now,
|
||||
error: null,
|
||||
updatedAt: now,
|
||||
},
|
||||
],
|
||||
auditEvents: [
|
||||
{
|
||||
id: "audit_live_seed_control_plane",
|
||||
at: now,
|
||||
actorUserId: "system",
|
||||
actorName: "NODE.DC seed",
|
||||
action: "Применён live seed control-plane",
|
||||
objectType: "control_plane",
|
||||
objectName: "Launcher users and access",
|
||||
clientId: "client_romashka",
|
||||
result: "success",
|
||||
details: "Demo-участники удалены из runtime storage. Оставлены dcctouch@gmail.com и silver_psih@yahoo.com.",
|
||||
},
|
||||
],
|
||||
services,
|
||||
};
|
||||
|
||||
await writeJson(publicDataPath, liveData);
|
||||
|
||||
if (existsSync(join(projectRoot, "dist"))) {
|
||||
await writeJson(distDataPath, liveData);
|
||||
}
|
||||
|
||||
console.log(`Seeded ${liveData.users.length} users, ${liveData.clients.length} client, ${liveData.groups.length} groups.`);
|
||||
|
||||
function readJson(path) {
|
||||
if (!existsSync(path)) {
|
||||
return {};
|
||||
}
|
||||
|
||||
return JSON.parse(readFileSync(path, "utf8"));
|
||||
}
|
||||
|
||||
async function writeJson(path, data) {
|
||||
await mkdir(dirname(path), { recursive: true });
|
||||
await writeFile(path, `${JSON.stringify(data, null, 2)}\n`, "utf8");
|
||||
}
|
||||
|
|
@ -0,0 +1,305 @@
|
|||
import { randomBytes } from "node:crypto";
|
||||
|
||||
const platformGroups = {
|
||||
superadmin: "nodedc:superadmin",
|
||||
launcherAdmin: "nodedc:launcher:admin",
|
||||
launcherUser: "nodedc:launcher:user",
|
||||
taskManagerAdmin: "nodedc:taskmanager:admin",
|
||||
taskManagerUser: "nodedc:taskmanager:user",
|
||||
};
|
||||
|
||||
export function createAuthentikSyncClient({ baseUrl, token }) {
|
||||
const normalizedBaseUrl = String(baseUrl || "").replace(/\/$/, "");
|
||||
|
||||
function isConfigured() {
|
||||
return Boolean(normalizedBaseUrl && token);
|
||||
}
|
||||
|
||||
async function provisionUser({ data, userId, password, generatePassword = false }) {
|
||||
ensureConfigured();
|
||||
|
||||
const user = findById(data.users, userId, "user");
|
||||
const requiredGroups = resolveRequiredGroups(data, user);
|
||||
const groups = await ensureGroups(requiredGroups);
|
||||
const existingUser = await findUserByIdOrEmail(user.authentikUserId, user.email);
|
||||
const temporaryPassword = password || (generatePassword && !existingUser ? generatePasswordValue() : null);
|
||||
const payload = {
|
||||
username: user.email.toLowerCase(),
|
||||
email: user.email.toLowerCase(),
|
||||
name: user.name,
|
||||
is_active: user.globalStatus === "active",
|
||||
type: "internal",
|
||||
groups: groups.map((group) => group.pk),
|
||||
attributes: {
|
||||
nodedc_user_id: user.id,
|
||||
nodedc_source: "launcher-control-plane",
|
||||
picture: user.avatarUrl || undefined,
|
||||
avatar_url: user.avatarUrl || undefined,
|
||||
},
|
||||
};
|
||||
const authentikUser = existingUser
|
||||
? await requestJson(`/api/v3/core/users/${encodeURIComponent(existingUser.pk)}/`, {
|
||||
method: "PATCH",
|
||||
body: JSON.stringify(payload),
|
||||
})
|
||||
: await requestJson("/api/v3/core/users/", {
|
||||
method: "POST",
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
|
||||
if (temporaryPassword) {
|
||||
await setPassword(authentikUser.pk, temporaryPassword);
|
||||
}
|
||||
|
||||
return {
|
||||
authentikUserId: String(authentikUser.uuid || authentikUser.uid || authentikUser.pk),
|
||||
authentikPk: authentikUser.pk,
|
||||
email: authentikUser.email,
|
||||
name: authentikUser.name,
|
||||
groups: requiredGroups,
|
||||
created: !existingUser,
|
||||
temporaryPassword,
|
||||
};
|
||||
}
|
||||
|
||||
async function findUserByIdOrEmail(authentikUserId, email) {
|
||||
if (authentikUserId) {
|
||||
const payload = await requestJson(`/api/v3/core/users/?search=${encodeURIComponent(authentikUserId)}`);
|
||||
const users = Array.isArray(payload.results) ? payload.results : [];
|
||||
const existingUser = users.find((user) => {
|
||||
const identifiers = [user.uuid, user.uid, user.pk].map((value) => String(value || ""));
|
||||
return identifiers.includes(String(authentikUserId));
|
||||
});
|
||||
|
||||
if (existingUser) {
|
||||
return existingUser;
|
||||
}
|
||||
}
|
||||
|
||||
const payload = await requestJson(`/api/v3/core/users/?search=${encodeURIComponent(email)}`);
|
||||
const users = Array.isArray(payload.results) ? payload.results : [];
|
||||
return users.find((user) => String(user.email || "").toLowerCase() === email.toLowerCase()) ?? null;
|
||||
}
|
||||
|
||||
async function ensureGroups(groupNames) {
|
||||
const groups = [];
|
||||
|
||||
for (const groupName of groupNames) {
|
||||
groups.push(await ensureGroup(groupName));
|
||||
}
|
||||
|
||||
return groups;
|
||||
}
|
||||
|
||||
async function ensureGroup(groupName) {
|
||||
const payload = await requestJson(`/api/v3/core/groups/?search=${encodeURIComponent(groupName)}`);
|
||||
const groups = Array.isArray(payload.results) ? payload.results : [];
|
||||
const existingGroup = groups.find((group) => group.name === groupName);
|
||||
|
||||
if (existingGroup) {
|
||||
return existingGroup;
|
||||
}
|
||||
|
||||
return requestJson("/api/v3/core/groups/", {
|
||||
method: "POST",
|
||||
body: JSON.stringify({
|
||||
name: groupName,
|
||||
is_superuser: false,
|
||||
attributes: {
|
||||
nodedc_source: "launcher-control-plane",
|
||||
},
|
||||
}),
|
||||
});
|
||||
}
|
||||
|
||||
async function setPassword(userPk, password) {
|
||||
await requestJson(`/api/v3/core/users/${encodeURIComponent(userPk)}/set_password/`, {
|
||||
method: "POST",
|
||||
body: JSON.stringify({ password }),
|
||||
});
|
||||
}
|
||||
|
||||
async function requestJson(path, init = {}) {
|
||||
ensureConfigured();
|
||||
|
||||
const headers = new Headers(init.headers);
|
||||
headers.set("Authorization", `Bearer ${token}`);
|
||||
headers.set("Accept", "application/json");
|
||||
|
||||
if (init.body && !headers.has("Content-Type")) {
|
||||
headers.set("Content-Type", "application/json");
|
||||
}
|
||||
|
||||
const response = await fetch(`${normalizedBaseUrl}${path}`, {
|
||||
...init,
|
||||
headers,
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const errorText = await response.text();
|
||||
throw new Error(`Authentik API ${path} failed: HTTP ${response.status} ${errorText}`);
|
||||
}
|
||||
|
||||
return response.status === 204 ? null : response.json();
|
||||
}
|
||||
|
||||
function ensureConfigured() {
|
||||
if (!isConfigured()) {
|
||||
throw new Error("Authentik API is not configured. Set AUTHENTIK_BOOTSTRAP_TOKEN or NODEDC_AUTHENTIK_SERVICE_TOKEN server-side.");
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
isConfigured,
|
||||
provisionUser,
|
||||
};
|
||||
}
|
||||
|
||||
export function resolveRequiredGroups(data, user) {
|
||||
const groupNames = new Set();
|
||||
|
||||
if (user.globalStatus !== "active") {
|
||||
return [];
|
||||
}
|
||||
|
||||
groupNames.add(platformGroups.launcherUser);
|
||||
|
||||
if (user.id === "user_root") {
|
||||
groupNames.add(platformGroups.superadmin);
|
||||
groupNames.add(platformGroups.launcherAdmin);
|
||||
groupNames.add(platformGroups.taskManagerAdmin);
|
||||
groupNames.add(platformGroups.taskManagerUser);
|
||||
return [...groupNames];
|
||||
}
|
||||
|
||||
for (const client of data.clients) {
|
||||
const membership = getRuntimeMembership(data, user.id, client.id);
|
||||
|
||||
if (membership.status !== "active") {
|
||||
continue;
|
||||
}
|
||||
|
||||
const userGroups = getUserGroups(data, user.id, client.id);
|
||||
|
||||
for (const service of data.services) {
|
||||
const access = computeEffectiveAccess(data, { client, user, membership, userGroups, service });
|
||||
|
||||
if (!access.allowed) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (service.slug === "task-manager") {
|
||||
groupNames.add(platformGroups.taskManagerUser);
|
||||
|
||||
if (access.appRole === "admin" || access.appRole === "owner") {
|
||||
groupNames.add(platformGroups.taskManagerAdmin);
|
||||
}
|
||||
} else if (service.authentikGroupName) {
|
||||
groupNames.add(service.authentikGroupName);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return [...groupNames];
|
||||
}
|
||||
|
||||
function generatePasswordValue() {
|
||||
return `NDC-${randomBytes(15).toString("base64url")}`;
|
||||
}
|
||||
|
||||
function computeEffectiveAccess(data, { client, user, membership, userGroups, service }) {
|
||||
if (client.status === "suspended" || client.status === "expired") {
|
||||
return { allowed: false };
|
||||
}
|
||||
|
||||
if (user.globalStatus === "blocked" || membership.status === "disabled") {
|
||||
return { allowed: false };
|
||||
}
|
||||
|
||||
if (service.status === "disabled" || service.status === "hidden") {
|
||||
return { allowed: false };
|
||||
}
|
||||
|
||||
const deny = data.exceptions.find(
|
||||
(exception) => exception.serviceId === service.id && exception.userId === user.id && exception.type === "deny"
|
||||
);
|
||||
|
||||
if (deny) {
|
||||
return { allowed: false };
|
||||
}
|
||||
|
||||
const allow = data.exceptions.find(
|
||||
(exception) => exception.serviceId === service.id && exception.userId === user.id && exception.type === "allow"
|
||||
);
|
||||
|
||||
if (allow) {
|
||||
return { allowed: true };
|
||||
}
|
||||
|
||||
const userGrant = data.grants.find(
|
||||
(grant) =>
|
||||
grant.serviceId === service.id &&
|
||||
grant.targetType === "user" &&
|
||||
grant.targetId === user.id &&
|
||||
grant.status === "active"
|
||||
);
|
||||
|
||||
if (userGrant) {
|
||||
return { allowed: true, appRole: userGrant.appRole };
|
||||
}
|
||||
|
||||
const groupIds = userGroups.map((group) => group.id);
|
||||
const groupGrant = data.grants.find(
|
||||
(grant) =>
|
||||
grant.serviceId === service.id &&
|
||||
grant.targetType === "group" &&
|
||||
groupIds.includes(grant.targetId) &&
|
||||
grant.status === "active"
|
||||
);
|
||||
|
||||
if (groupGrant) {
|
||||
return { allowed: true, appRole: groupGrant.appRole };
|
||||
}
|
||||
|
||||
const clientGrant = data.grants.find(
|
||||
(grant) =>
|
||||
grant.serviceId === service.id &&
|
||||
grant.targetType === "client" &&
|
||||
grant.targetId === client.id &&
|
||||
grant.status === "active"
|
||||
);
|
||||
|
||||
if (clientGrant) {
|
||||
return { allowed: true, appRole: clientGrant.appRole };
|
||||
}
|
||||
|
||||
return { allowed: false };
|
||||
}
|
||||
|
||||
function getRuntimeMembership(data, userId, clientId) {
|
||||
return (
|
||||
data.memberships.find((membership) => membership.userId === userId && membership.clientId === clientId) ?? {
|
||||
id: `missing_${clientId}_${userId}`,
|
||||
clientId,
|
||||
userId,
|
||||
role: "member",
|
||||
status: "disabled",
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
function getUserGroups(data, userId, clientId) {
|
||||
return data.groups.filter((group) => group.clientId === clientId && group.memberIds.includes(userId));
|
||||
}
|
||||
|
||||
function findById(items, id, label) {
|
||||
const item = items.find((candidate) => candidate.id === id);
|
||||
|
||||
if (!item) {
|
||||
throw new Error(`Unknown ${label}: ${id}`);
|
||||
}
|
||||
|
||||
return item;
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
|
|
@ -7,6 +7,8 @@ import { dirname, extname, join, resolve } from "node:path";
|
|||
import { fileURLToPath } from "node:url";
|
||||
import { createServer as createViteServer } from "vite";
|
||||
import { createRemoteJWKSet, jwtVerify } from "jose";
|
||||
import { createAuthentikSyncClient, resolveRequiredGroups } from "./authentik-sync.mjs";
|
||||
import { createControlPlaneStore } from "./control-plane-store.mjs";
|
||||
|
||||
const serverRoot = dirname(fileURLToPath(import.meta.url));
|
||||
const projectRoot = resolve(serverRoot, "..");
|
||||
|
|
@ -25,8 +27,11 @@ loadEnvFiles([
|
|||
const config = readConfig();
|
||||
const app = express();
|
||||
const httpServer = createHttpServer(app);
|
||||
const controlPlaneStore = createControlPlaneStore({ projectRoot });
|
||||
const authentikSyncClient = createAuthentikSyncClient({ baseUrl: config.authentikBaseUrl, token: config.authentikApiToken });
|
||||
const pendingLogins = new Map();
|
||||
const sessions = new Map();
|
||||
const runtimeEventClients = new Set();
|
||||
let discoveryCache = null;
|
||||
let jwksCache = null;
|
||||
|
||||
|
|
@ -34,7 +39,12 @@ app.disable("x-powered-by");
|
|||
app.use(express.json({ limit: maxStorageJsonBodyBytes }));
|
||||
|
||||
app.get("/healthz", (_req, res) => {
|
||||
res.json({ ok: true, service: "nodedc-launcher-bff", oidcConfigured: config.oidcConfigured });
|
||||
res.json({
|
||||
ok: true,
|
||||
service: "nodedc-launcher-bff",
|
||||
oidcConfigured: config.oidcConfigured,
|
||||
authentikApiConfigured: authentikSyncClient.isConfigured(),
|
||||
});
|
||||
});
|
||||
|
||||
app.get("/auth/login", asyncRoute(async (req, res) => {
|
||||
|
|
@ -165,11 +175,13 @@ app.get("/api/me", (req, res) => {
|
|||
return;
|
||||
}
|
||||
|
||||
const runtimeContext = getRuntimeSessionContext(session);
|
||||
|
||||
res.json({
|
||||
authenticated: true,
|
||||
user: session.user,
|
||||
groups: session.user.groups,
|
||||
isSuperAdmin: session.user.groups.includes("nodedc:superadmin"),
|
||||
user: runtimeContext.user,
|
||||
groups: runtimeContext.groups,
|
||||
isSuperAdmin: runtimeContext.groups.includes("nodedc:superadmin"),
|
||||
logoutUrl: "/auth/logout",
|
||||
});
|
||||
});
|
||||
|
|
@ -182,7 +194,257 @@ app.get("/api/apps", (req, res) => {
|
|||
return;
|
||||
}
|
||||
|
||||
res.json({ apps: getAppsForUser(session.user.groups) });
|
||||
res.json({ apps: getAppsForSession(session) });
|
||||
});
|
||||
|
||||
app.get("/api/profile", requireSession, (req, res) => {
|
||||
const { actor, data } = getLauncherProfileContext(req.nodedcSession);
|
||||
const user = findLauncherUser(data, actor.id);
|
||||
|
||||
res.json({
|
||||
user,
|
||||
memberships: data.memberships.filter((membership) => membership.userId === user.id),
|
||||
});
|
||||
});
|
||||
|
||||
app.get("/api/events", requireSession, (req, res) => {
|
||||
const client = {
|
||||
id: randomUUID(),
|
||||
res,
|
||||
};
|
||||
|
||||
res.setHeader("Content-Type", "text/event-stream");
|
||||
res.setHeader("Cache-Control", "no-cache, no-transform");
|
||||
res.setHeader("Connection", "keep-alive");
|
||||
res.setHeader("X-Accel-Buffering", "no");
|
||||
res.flushHeaders?.();
|
||||
res.write(`event: nodedc-ready\ndata: ${JSON.stringify({ ok: true })}\n\n`);
|
||||
|
||||
const keepAlive = setInterval(() => {
|
||||
res.write(": keep-alive\n\n");
|
||||
}, 30000);
|
||||
|
||||
runtimeEventClients.add(client);
|
||||
|
||||
req.on("close", () => {
|
||||
clearInterval(keepAlive);
|
||||
runtimeEventClients.delete(client);
|
||||
});
|
||||
});
|
||||
|
||||
app.patch("/api/profile", requireSession, asyncRoute(async (req, res) => {
|
||||
const { actor } = getLauncherProfileContext(req.nodedcSession);
|
||||
const result = await controlPlaneStore.updateUserProfile(actor.id, sanitizeSelfProfilePatch(req.body), req.nodedcSession.user);
|
||||
const provisionedUser = await authentikSyncClient.provisionUser({
|
||||
data: result.data,
|
||||
userId: actor.id,
|
||||
});
|
||||
const storeResult = await controlPlaneStore.markUserAuthentikProvisioned(actor.id, provisionedUser, req.nodedcSession.user);
|
||||
|
||||
publishControlPlaneEvent("profile.updated", [actor.id]);
|
||||
res.json({ ...storeResult, provisioning: toProvisioningResponse(provisionedUser) });
|
||||
}));
|
||||
|
||||
app.post("/api/profile/password", requireSession, asyncRoute(async (req, res) => {
|
||||
const newPassword = sanitizeNewPassword(req.body?.newPassword);
|
||||
const { actor, data } = getLauncherProfileContext(req.nodedcSession);
|
||||
const provisionedUser = await authentikSyncClient.provisionUser({
|
||||
data,
|
||||
userId: actor.id,
|
||||
password: newPassword,
|
||||
});
|
||||
const result = await controlPlaneStore.markUserAuthentikProvisioned(actor.id, provisionedUser, req.nodedcSession.user);
|
||||
|
||||
publishControlPlaneEvent("profile.password.updated", [actor.id]);
|
||||
res.json({ data: result.data, ok: true });
|
||||
}));
|
||||
|
||||
app.get("/api/admin/control-plane", requireLauncherAdmin, (req, res) => {
|
||||
res.json(controlPlaneStore.getSnapshot(req.nodedcSession.user));
|
||||
});
|
||||
|
||||
app.get("/api/admin/clients", requireLauncherAdmin, (req, res) => {
|
||||
const snapshot = controlPlaneStore.getSnapshot(req.nodedcSession.user);
|
||||
res.json({ clients: snapshot.data.clients });
|
||||
});
|
||||
|
||||
app.post("/api/admin/clients", requireLauncherAdmin, asyncRoute(async (req, res) => {
|
||||
const result = await controlPlaneStore.createClient(req.body, req.nodedcSession.user);
|
||||
res.status(201).json(result);
|
||||
}));
|
||||
|
||||
app.patch("/api/admin/clients/:clientId", requireLauncherAdmin, asyncRoute(async (req, res) => {
|
||||
const result = await controlPlaneStore.updateClient(req.params.clientId, req.body, req.nodedcSession.user);
|
||||
res.json(result);
|
||||
}));
|
||||
|
||||
app.delete("/api/admin/clients/:clientId", requireLauncherAdmin, asyncRoute(async (req, res) => {
|
||||
const result = await controlPlaneStore.deleteClient(req.params.clientId, req.nodedcSession.user);
|
||||
res.json(result);
|
||||
}));
|
||||
|
||||
app.get("/api/admin/users", requireLauncherAdmin, (req, res) => {
|
||||
const snapshot = controlPlaneStore.getSnapshot(req.nodedcSession.user);
|
||||
res.json({ users: snapshot.data.users, memberships: snapshot.data.memberships });
|
||||
});
|
||||
|
||||
app.post("/api/admin/users", requireLauncherAdmin, asyncRoute(async (req, res) => {
|
||||
const result = await controlPlaneStore.createUser(req.body, req.nodedcSession.user);
|
||||
let provisioning = null;
|
||||
|
||||
if (req.body?.provisionAuth !== false) {
|
||||
const provisionedUser = await authentikSyncClient.provisionUser({
|
||||
data: result.data,
|
||||
userId: result.user.id,
|
||||
password: sanitizePassword(req.body?.password),
|
||||
generatePassword: req.body?.generatePassword !== false,
|
||||
});
|
||||
const storeResult = await controlPlaneStore.markUserAuthentikProvisioned(result.user.id, provisionedUser, req.nodedcSession.user);
|
||||
result.data = storeResult.data;
|
||||
provisioning = toProvisioningResponse(provisionedUser);
|
||||
}
|
||||
|
||||
publishControlPlaneEvent("admin.user.created", [result.user.id]);
|
||||
res.status(201).json({ ...result, provisioning });
|
||||
}));
|
||||
|
||||
app.patch("/api/admin/users/:userId/profile", requireLauncherAdmin, asyncRoute(async (req, res) => {
|
||||
const result = await controlPlaneStore.updateUserProfile(req.params.userId, req.body, req.nodedcSession.user);
|
||||
const syncResult = await syncUsersToAuthentik(result.data, [req.params.userId], req.nodedcSession.user);
|
||||
publishControlPlaneEvent("admin.user.updated", syncResult.userIds);
|
||||
res.json({ ...result, data: syncResult.data });
|
||||
}));
|
||||
|
||||
app.post("/api/admin/users/:userId/provision-authentik", requireLauncherAdmin, asyncRoute(async (req, res) => {
|
||||
const snapshot = controlPlaneStore.getSnapshot(req.nodedcSession.user);
|
||||
const provisionedUser = await authentikSyncClient.provisionUser({
|
||||
data: snapshot.data,
|
||||
userId: req.params.userId,
|
||||
password: sanitizePassword(req.body?.password),
|
||||
generatePassword: req.body?.generatePassword === true,
|
||||
});
|
||||
const result = await controlPlaneStore.markUserAuthentikProvisioned(req.params.userId, provisionedUser, req.nodedcSession.user);
|
||||
|
||||
publishControlPlaneEvent("admin.user.provisioned", [req.params.userId]);
|
||||
res.json({ ...result, provisioning: toProvisioningResponse(provisionedUser) });
|
||||
}));
|
||||
|
||||
app.patch("/api/admin/memberships/:membershipId", requireLauncherAdmin, asyncRoute(async (req, res) => {
|
||||
const result = await controlPlaneStore.updateMembership(req.params.membershipId, req.body, req.nodedcSession.user);
|
||||
const syncResult = await syncUsersToAuthentik(result.data, [result.membership.userId], req.nodedcSession.user);
|
||||
publishControlPlaneEvent("admin.membership.updated", syncResult.userIds);
|
||||
res.json({ ...result, data: syncResult.data });
|
||||
}));
|
||||
|
||||
app.delete("/api/admin/memberships/:membershipId", requireLauncherAdmin, asyncRoute(async (req, res) => {
|
||||
const result = await controlPlaneStore.deleteMembership(req.params.membershipId, req.nodedcSession.user);
|
||||
const syncResult = await syncUsersToAuthentik(result.data, [result.membership.userId], req.nodedcSession.user);
|
||||
publishControlPlaneEvent("admin.membership.deleted", syncResult.userIds);
|
||||
res.json({ ...result, data: syncResult.data });
|
||||
}));
|
||||
|
||||
app.post("/api/admin/invites", requireLauncherAdmin, asyncRoute(async (req, res) => {
|
||||
const result = await controlPlaneStore.createInvite(req.body, req.nodedcSession.user);
|
||||
publishControlPlaneEvent("admin.invite.created");
|
||||
res.status(201).json(result);
|
||||
}));
|
||||
|
||||
app.patch("/api/admin/invites/:inviteId", requireLauncherAdmin, asyncRoute(async (req, res) => {
|
||||
const result = await controlPlaneStore.updateInvite(req.params.inviteId, req.body, req.nodedcSession.user);
|
||||
publishControlPlaneEvent("admin.invite.updated");
|
||||
res.json(result);
|
||||
}));
|
||||
|
||||
app.delete("/api/admin/invites/:inviteId", requireLauncherAdmin, asyncRoute(async (req, res) => {
|
||||
const result = await controlPlaneStore.deleteInvite(req.params.inviteId, req.nodedcSession.user);
|
||||
publishControlPlaneEvent("admin.invite.deleted");
|
||||
res.json(result);
|
||||
}));
|
||||
|
||||
app.post("/api/admin/groups", requireLauncherAdmin, asyncRoute(async (req, res) => {
|
||||
const result = await controlPlaneStore.createGroup(req.body, req.nodedcSession.user);
|
||||
const syncResult = await syncUsersToAuthentik(result.data, result.group.memberIds, req.nodedcSession.user);
|
||||
publishControlPlaneEvent("admin.group.created", syncResult.userIds);
|
||||
res.status(201).json({ ...result, data: syncResult.data });
|
||||
}));
|
||||
|
||||
app.patch("/api/admin/groups/:groupId", requireLauncherAdmin, asyncRoute(async (req, res) => {
|
||||
const beforeSnapshot = controlPlaneStore.getSnapshot(req.nodedcSession.user);
|
||||
const previousMemberIds = beforeSnapshot.data.groups.find((group) => group.id === req.params.groupId)?.memberIds ?? [];
|
||||
const result = await controlPlaneStore.updateGroup(req.params.groupId, req.body, req.nodedcSession.user);
|
||||
const syncResult = await syncUsersToAuthentik(
|
||||
result.data,
|
||||
[...previousMemberIds, ...result.group.memberIds],
|
||||
req.nodedcSession.user
|
||||
);
|
||||
publishControlPlaneEvent("admin.group.updated", syncResult.userIds);
|
||||
res.json({ ...result, data: syncResult.data });
|
||||
}));
|
||||
|
||||
app.delete("/api/admin/groups/:groupId", requireLauncherAdmin, asyncRoute(async (req, res) => {
|
||||
const result = await controlPlaneStore.deleteGroup(req.params.groupId, req.nodedcSession.user);
|
||||
const syncResult = await syncUsersToAuthentik(result.data, result.group.memberIds, req.nodedcSession.user);
|
||||
publishControlPlaneEvent("admin.group.deleted", syncResult.userIds);
|
||||
res.json({ ...result, data: syncResult.data });
|
||||
}));
|
||||
|
||||
app.post("/api/admin/services", requireLauncherAdmin, asyncRoute(async (req, res) => {
|
||||
const result = await controlPlaneStore.createService(req.body, req.nodedcSession.user);
|
||||
publishControlPlaneEvent("admin.service.created");
|
||||
res.status(201).json(result);
|
||||
}));
|
||||
|
||||
app.patch("/api/admin/services/reorder", requireLauncherAdmin, asyncRoute(async (req, res) => {
|
||||
const result = await controlPlaneStore.reorderServices(req.body, req.nodedcSession.user);
|
||||
publishControlPlaneEvent("admin.service.reordered");
|
||||
res.json(result);
|
||||
}));
|
||||
|
||||
app.patch("/api/admin/services/:serviceId", requireLauncherAdmin, asyncRoute(async (req, res) => {
|
||||
const result = await controlPlaneStore.updateService(req.params.serviceId, req.body, req.nodedcSession.user);
|
||||
publishControlPlaneEvent("admin.service.updated");
|
||||
res.json(result);
|
||||
}));
|
||||
|
||||
app.delete("/api/admin/services/:serviceId", requireLauncherAdmin, asyncRoute(async (req, res) => {
|
||||
const result = await controlPlaneStore.deleteService(req.params.serviceId, req.nodedcSession.user);
|
||||
publishControlPlaneEvent("admin.service.deleted");
|
||||
res.json(result);
|
||||
}));
|
||||
|
||||
app.post("/api/admin/access/grants", requireLauncherAdmin, asyncRoute(async (req, res) => {
|
||||
const result = await controlPlaneStore.upsertGrant(req.body, req.nodedcSession.user);
|
||||
const syncResult = await syncUsersToAuthentik(
|
||||
result.data,
|
||||
resolveGrantTargetUserIds(result.data, result.grant.targetType, result.grant.targetId),
|
||||
req.nodedcSession.user
|
||||
);
|
||||
publishControlPlaneEvent("admin.access.grant.updated", syncResult.userIds);
|
||||
res.json({ ...result, data: syncResult.data });
|
||||
}));
|
||||
|
||||
app.post("/api/admin/access/exceptions", requireLauncherAdmin, asyncRoute(async (req, res) => {
|
||||
const result = await controlPlaneStore.upsertException(req.body, req.nodedcSession.user);
|
||||
const syncResult = await syncUsersToAuthentik(result.data, [result.exception.userId], req.nodedcSession.user);
|
||||
publishControlPlaneEvent("admin.access.exception.updated", syncResult.userIds);
|
||||
res.json({ ...result, data: syncResult.data });
|
||||
}));
|
||||
|
||||
app.post("/api/admin/access/user-service", requireLauncherAdmin, asyncRoute(async (req, res) => {
|
||||
const result = await controlPlaneStore.setUserServiceAccess(req.body, req.nodedcSession.user);
|
||||
const syncResult = await syncUsersToAuthentik(result.data, [req.body?.userId], req.nodedcSession.user);
|
||||
publishControlPlaneEvent("admin.access.user-service.updated", syncResult.userIds);
|
||||
res.json({ ...result, data: syncResult.data });
|
||||
}));
|
||||
|
||||
app.post("/api/admin/sync/:syncId/retry", requireLauncherAdmin, asyncRoute(async (req, res) => {
|
||||
const result = await controlPlaneStore.retrySync(req.params.syncId, req.nodedcSession.user);
|
||||
publishControlPlaneEvent("admin.sync.retry");
|
||||
res.json(result);
|
||||
}));
|
||||
|
||||
app.get("/api/admin/sync/authentik/plan", requireLauncherAdmin, (_req, res) => {
|
||||
res.json(controlPlaneStore.buildAuthentikSyncPlan());
|
||||
});
|
||||
|
||||
app.post("/api/storage/upload", asyncRoute(async (req, res) => {
|
||||
|
|
@ -190,8 +452,9 @@ app.post("/api/storage/upload", asyncRoute(async (req, res) => {
|
|||
res.json(result);
|
||||
}));
|
||||
|
||||
app.post("/api/storage/data", asyncRoute(async (req, res) => {
|
||||
app.post("/api/storage/data", requireLauncherAdmin, asyncRoute(async (req, res) => {
|
||||
await saveLauncherData(req.body);
|
||||
publishControlPlaneEvent("storage.data.updated");
|
||||
res.json({ ok: true, url: "/storage/launcher-data.json" });
|
||||
}));
|
||||
|
||||
|
|
@ -234,6 +497,15 @@ function readConfig() {
|
|||
cookieDomain: process.env.LAUNCHER_COOKIE_DOMAIN || undefined,
|
||||
cookieSecure: process.env.COOKIE_SECURE === "true",
|
||||
oidcConfigured: Boolean(issuer && clientId && clientSecret),
|
||||
authentikBaseUrl:
|
||||
process.env.NODEDC_AUTHENTIK_BASE_URL ??
|
||||
process.env.AUTHENTIK_BASE_URL ??
|
||||
(process.env.AUTH_DOMAIN ? `http://${process.env.AUTH_DOMAIN}` : ""),
|
||||
authentikApiToken:
|
||||
process.env.NODEDC_AUTHENTIK_SERVICE_TOKEN ??
|
||||
process.env.AUTHENTIK_SERVICE_TOKEN ??
|
||||
process.env.AUTHENTIK_BOOTSTRAP_TOKEN ??
|
||||
"",
|
||||
};
|
||||
}
|
||||
|
||||
|
|
@ -314,6 +586,7 @@ async function verifyIdToken(discovery, idToken, nonce) {
|
|||
function normalizeUser(claims) {
|
||||
const groups = normalizeGroups(claims.groups);
|
||||
const email = typeof claims.email === "string" ? claims.email : "";
|
||||
const avatarUrl = firstStringClaim(claims.picture, claims.avatar_url, claims.avatar);
|
||||
const name =
|
||||
typeof claims.name === "string" && claims.name
|
||||
? claims.name
|
||||
|
|
@ -326,10 +599,106 @@ function normalizeUser(claims) {
|
|||
email,
|
||||
name,
|
||||
preferredUsername: typeof claims.preferred_username === "string" ? claims.preferred_username : null,
|
||||
avatarUrl,
|
||||
groups,
|
||||
};
|
||||
}
|
||||
|
||||
function firstStringClaim(...values) {
|
||||
for (const value of values) {
|
||||
if (typeof value === "string" && value) return value;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
function sanitizePassword(value) {
|
||||
return typeof value === "string" && value.length >= 8 ? value : null;
|
||||
}
|
||||
|
||||
function sanitizeNewPassword(value) {
|
||||
if (typeof value !== "string" || value.length < 8) {
|
||||
throw new Error("Новый пароль должен быть не короче 8 символов");
|
||||
}
|
||||
|
||||
return value;
|
||||
}
|
||||
|
||||
function sanitizeSelfProfilePatch(payload) {
|
||||
return {
|
||||
name: payload?.name,
|
||||
email: payload?.email,
|
||||
phone: payload?.phone,
|
||||
position: payload?.position,
|
||||
avatarUrl: payload?.avatarUrl,
|
||||
};
|
||||
}
|
||||
|
||||
function toProvisioningResponse(provisionedUser) {
|
||||
return {
|
||||
authentikUserId: provisionedUser.authentikUserId,
|
||||
email: provisionedUser.email,
|
||||
name: provisionedUser.name,
|
||||
groups: provisionedUser.groups,
|
||||
created: provisionedUser.created,
|
||||
temporaryPassword: provisionedUser.temporaryPassword,
|
||||
};
|
||||
}
|
||||
|
||||
async function syncUsersToAuthentik(data, userIds, identity) {
|
||||
let latestData = data;
|
||||
const uniqueUserIds = [...new Set(userIds.filter((userId) => typeof userId === "string" && userId))];
|
||||
|
||||
for (const userId of uniqueUserIds) {
|
||||
if (!latestData.users.some((user) => user.id === userId)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
const provisionedUser = await authentikSyncClient.provisionUser({ data: latestData, userId });
|
||||
const result = await controlPlaneStore.markUserAuthentikProvisioned(userId, provisionedUser, identity);
|
||||
latestData = result.data;
|
||||
}
|
||||
|
||||
return { data: latestData, userIds: uniqueUserIds };
|
||||
}
|
||||
|
||||
function resolveGrantTargetUserIds(data, targetType, targetId) {
|
||||
if (targetType === "user") {
|
||||
return [targetId];
|
||||
}
|
||||
|
||||
if (targetType === "group") {
|
||||
return data.groups.find((group) => group.id === targetId)?.memberIds ?? [];
|
||||
}
|
||||
|
||||
if (targetType === "client") {
|
||||
return data.memberships.filter((membership) => membership.clientId === targetId).map((membership) => membership.userId);
|
||||
}
|
||||
|
||||
return [];
|
||||
}
|
||||
|
||||
function publishControlPlaneEvent(action, affectedUserIds = []) {
|
||||
publishRuntimeEvent({
|
||||
type: "control-plane.updated",
|
||||
action,
|
||||
affectedUserIds: [...new Set(affectedUserIds.filter((userId) => typeof userId === "string" && userId))],
|
||||
emittedAt: new Date().toISOString(),
|
||||
});
|
||||
}
|
||||
|
||||
function publishRuntimeEvent(payload) {
|
||||
const message = `event: nodedc-runtime\ndata: ${JSON.stringify(payload)}\n\n`;
|
||||
|
||||
for (const client of runtimeEventClients) {
|
||||
try {
|
||||
client.res.write(message);
|
||||
} catch {
|
||||
runtimeEventClients.delete(client);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function normalizeGroups(groupsClaim) {
|
||||
if (Array.isArray(groupsClaim)) {
|
||||
return [...new Set(groupsClaim.filter((group) => typeof group === "string"))];
|
||||
|
|
@ -342,6 +711,47 @@ function normalizeGroups(groupsClaim) {
|
|||
return [];
|
||||
}
|
||||
|
||||
function getRuntimeSessionContext(session) {
|
||||
const fallback = {
|
||||
user: session.user,
|
||||
groups: session.user.groups,
|
||||
};
|
||||
|
||||
try {
|
||||
const snapshot = controlPlaneStore.getSnapshot(session.user);
|
||||
|
||||
if (snapshot.actor.source !== "launcher") {
|
||||
return fallback;
|
||||
}
|
||||
|
||||
const user = snapshot.data.users.find((candidate) => candidate.id === snapshot.actor.id);
|
||||
|
||||
if (!user) {
|
||||
return fallback;
|
||||
}
|
||||
|
||||
const groups = resolveRequiredGroups(snapshot.data, user);
|
||||
|
||||
return {
|
||||
groups,
|
||||
user: {
|
||||
...session.user,
|
||||
email: user.email,
|
||||
name: user.name,
|
||||
avatarUrl: user.avatarUrl ?? session.user.avatarUrl,
|
||||
groups,
|
||||
},
|
||||
};
|
||||
} catch (error) {
|
||||
console.warn(error instanceof Error ? error.message : "Не удалось рассчитать runtime контекст Launcher");
|
||||
return fallback;
|
||||
}
|
||||
}
|
||||
|
||||
function getAppsForSession(session) {
|
||||
return getAppsForUser(getRuntimeSessionContext(session).groups);
|
||||
}
|
||||
|
||||
function getAppsForUser(userGroups) {
|
||||
const groupSet = new Set(userGroups);
|
||||
const catalog = getAppCatalog();
|
||||
|
|
@ -407,7 +817,7 @@ function getAppCatalog() {
|
|||
}
|
||||
|
||||
function specialRequiredGroups(slug) {
|
||||
if (slug === "launcher" || slug === "nodedc") return ["nodedc:launcher:admin", "nodedc:launcher:user"];
|
||||
if (slug === "launcher") return ["nodedc:launcher:admin", "nodedc:launcher:user"];
|
||||
if (slug === "task-manager") return ["nodedc:taskmanager:admin", "nodedc:taskmanager:user"];
|
||||
return [];
|
||||
}
|
||||
|
|
@ -465,12 +875,7 @@ async function saveUploadedFile(payload) {
|
|||
}
|
||||
|
||||
async function saveLauncherData(payload) {
|
||||
await Promise.all(
|
||||
getWritableStorageRoots().map(async (storageRoot) => {
|
||||
await mkdir(storageRoot, { recursive: true });
|
||||
await writeFile(join(storageRoot, "launcher-data.json"), `${JSON.stringify(payload, null, 2)}\n`, "utf8");
|
||||
})
|
||||
);
|
||||
await controlPlaneStore.writeData(payload);
|
||||
}
|
||||
|
||||
function getWritableStorageRoots() {
|
||||
|
|
@ -563,6 +968,65 @@ function parseCookies(cookieHeader) {
|
|||
);
|
||||
}
|
||||
|
||||
function requireLauncherAdmin(req, res, next) {
|
||||
const session = getCurrentSession(req);
|
||||
|
||||
if (!session) {
|
||||
res.status(401).json({ authenticated: false, loginUrl: "/auth/login" });
|
||||
return;
|
||||
}
|
||||
|
||||
const runtimeContext = getRuntimeSessionContext(session);
|
||||
|
||||
if (!isLauncherAdmin(runtimeContext.groups)) {
|
||||
res.status(403).json({ error: "Недостаточно прав Launcher admin" });
|
||||
return;
|
||||
}
|
||||
|
||||
req.nodedcSession = { ...session, user: runtimeContext.user };
|
||||
next();
|
||||
}
|
||||
|
||||
function requireSession(req, res, next) {
|
||||
const session = getCurrentSession(req);
|
||||
|
||||
if (!session) {
|
||||
res.status(401).json({ authenticated: false, loginUrl: "/auth/login" });
|
||||
return;
|
||||
}
|
||||
|
||||
const runtimeContext = getRuntimeSessionContext(session);
|
||||
req.nodedcSession = { ...session, user: runtimeContext.user };
|
||||
next();
|
||||
}
|
||||
|
||||
function getLauncherProfileContext(session) {
|
||||
const snapshot = controlPlaneStore.getSnapshot(session.user);
|
||||
|
||||
if (snapshot.actor.source !== "launcher") {
|
||||
throw new Error("Профиль пользователя не найден в Launcher control-plane");
|
||||
}
|
||||
|
||||
return {
|
||||
actor: snapshot.actor,
|
||||
data: snapshot.data,
|
||||
};
|
||||
}
|
||||
|
||||
function findLauncherUser(data, userId) {
|
||||
const user = data.users.find((candidate) => candidate.id === userId);
|
||||
|
||||
if (!user) {
|
||||
throw new Error(`Unknown Launcher user: ${userId}`);
|
||||
}
|
||||
|
||||
return user;
|
||||
}
|
||||
|
||||
function isLauncherAdmin(groups) {
|
||||
return groups.includes("nodedc:superadmin") || groups.includes("nodedc:launcher:admin");
|
||||
}
|
||||
|
||||
function cookieOptions(maxAgeMs) {
|
||||
const options = {
|
||||
httpOnly: true,
|
||||
|
|
|
|||
|
|
@ -3,8 +3,30 @@ import type { Client } from "../entities/client/types";
|
|||
import type { Invite } from "../entities/invite/types";
|
||||
import { syncServiceLaunchLink } from "../entities/service/links";
|
||||
import type { LauncherServiceView, Service } from "../entities/service/types";
|
||||
import type { SyncStatus } from "../entities/sync/types";
|
||||
import type { ClientGroup, ClientMembership, LauncherUser } from "../entities/user/types";
|
||||
import {
|
||||
createAdminClient,
|
||||
createAdminGroup,
|
||||
createAdminInvite,
|
||||
createAdminService,
|
||||
createAdminUser,
|
||||
deleteAdminClient,
|
||||
deleteAdminGroup,
|
||||
deleteAdminInvite,
|
||||
deleteAdminMembership,
|
||||
deleteAdminService,
|
||||
fetchControlPlaneSnapshot,
|
||||
reorderAdminServices,
|
||||
retryAdminSync,
|
||||
setAdminUserServiceAccess,
|
||||
updateAdminClient,
|
||||
updateAdminGroup,
|
||||
updateAdminInvite,
|
||||
updateAdminMembership,
|
||||
updateAdminService,
|
||||
updateAdminUserProfile,
|
||||
type ControlPlaneMutationResult,
|
||||
} from "../shared/api/adminApi";
|
||||
import {
|
||||
buildLauncherServices,
|
||||
buildMe,
|
||||
|
|
@ -12,9 +34,22 @@ import {
|
|||
profileOptions,
|
||||
type LauncherData,
|
||||
} from "../shared/api/mockApi";
|
||||
import { fetchAuthSession, fetchAvailableApps, type AuthSession, type LauncherAuthApp } from "../shared/api/authApi";
|
||||
import { loadPersistedLauncherData, persistLauncherData } from "../shared/api/storageApi";
|
||||
import { AdminOverlay, type SetUserServiceAccessCommand } from "../widgets/admin-overlay/AdminOverlay";
|
||||
import {
|
||||
fetchAuthSession,
|
||||
fetchAvailableApps,
|
||||
type AuthenticatedSession,
|
||||
type AuthSession,
|
||||
type LauncherAuthApp,
|
||||
} from "../shared/api/authApi";
|
||||
import { updateOwnPassword, updateOwnProfile } from "../shared/api/profileApi";
|
||||
import { loadPersistedLauncherData } from "../shared/api/storageApi";
|
||||
import {
|
||||
AdminOverlay,
|
||||
type AccessAssignmentValue,
|
||||
type CreateUserCommand,
|
||||
type SetUserServiceAccessCommand,
|
||||
} from "../widgets/admin-overlay/AdminOverlay";
|
||||
import { ProfileSettingsPanel } from "../widgets/profile-settings-panel/ProfileSettingsPanel";
|
||||
import { ServiceRail } from "../widgets/service-rail/ServiceRail";
|
||||
import { ServiceStage } from "../widgets/service-stage/ServiceStage";
|
||||
import { TopBar } from "../widgets/top-bar/TopBar";
|
||||
|
|
@ -25,12 +60,14 @@ export function LauncherApp() {
|
|||
const [activeClientId, setActiveClientId] = useState(profileOptions[0].defaultClientId);
|
||||
const [selectedServiceId, setSelectedServiceId] = useState<string | undefined>();
|
||||
const [adminOpen, setAdminOpen] = useState(false);
|
||||
const [storageHydrated, setStorageHydrated] = useState(false);
|
||||
const [authSession, setAuthSession] = useState<AuthSession | null>(null);
|
||||
const [authApps, setAuthApps] = useState<LauncherAuthApp[] | null>(null);
|
||||
const [authError, setAuthError] = useState<string | null>(null);
|
||||
const [profileSettingsOpen, setProfileSettingsOpen] = useState(false);
|
||||
const [pendingAccessAssignments, setPendingAccessAssignments] = useState<Record<string, AccessAssignmentValue>>({});
|
||||
|
||||
const me = useMemo(() => buildMe(data, activeProfileId, activeClientId), [data, activeProfileId, activeClientId]);
|
||||
const activeProfileUser = data.users.find((user) => user.id === activeProfileId) ?? data.users[0];
|
||||
const runtimeMe = useMemo(() => {
|
||||
if (!authSession?.authenticated) return me;
|
||||
|
||||
|
|
@ -39,14 +76,16 @@ export function LauncherApp() {
|
|||
user: {
|
||||
...me.user,
|
||||
authentikUserId: authSession.user.sub,
|
||||
email: authSession.user.email || me.user.email,
|
||||
name: authSession.user.name || me.user.name,
|
||||
email: me.user.email || authSession.user.email,
|
||||
name: me.user.name || authSession.user.name,
|
||||
avatarUrl: me.user.avatarUrl ?? authSession.user.avatarUrl,
|
||||
},
|
||||
mockAuthentikClaims: {
|
||||
...me.mockAuthentikClaims,
|
||||
sub: authSession.user.sub,
|
||||
email: authSession.user.email || me.mockAuthentikClaims.email,
|
||||
name: authSession.user.name || me.mockAuthentikClaims.name,
|
||||
avatarUrl: authSession.user.avatarUrl ?? null,
|
||||
groups: authSession.groups,
|
||||
},
|
||||
};
|
||||
|
|
@ -150,17 +189,16 @@ export function LauncherApp() {
|
|||
useEffect(() => {
|
||||
if (!authSession?.authenticated) return;
|
||||
|
||||
const nextProfileId = authSession.isSuperAdmin ? "user_root" : "user_vasya";
|
||||
const nextProfile = profileOptions.find((profile) => profile.userId === nextProfileId);
|
||||
const nextContext = resolveAuthenticatedContext(data, authSession, activeProfileId, activeClientId);
|
||||
|
||||
if (activeProfileId !== nextProfileId) {
|
||||
setActiveProfileId(nextProfileId);
|
||||
if (activeProfileId !== nextContext.profileId) {
|
||||
setActiveProfileId(nextContext.profileId);
|
||||
}
|
||||
|
||||
if (nextProfile && activeClientId !== nextProfile.defaultClientId) {
|
||||
setActiveClientId(nextProfile.defaultClientId);
|
||||
if (activeClientId !== nextContext.clientId) {
|
||||
setActiveClientId(nextContext.clientId);
|
||||
}
|
||||
}, [activeClientId, activeProfileId, authSession]);
|
||||
}, [activeClientId, activeProfileId, authSession, data]);
|
||||
|
||||
useEffect(() => {
|
||||
let isMounted = true;
|
||||
|
|
@ -170,11 +208,6 @@ export function LauncherApp() {
|
|||
if (isMounted && persistedData) {
|
||||
setData(syncLauncherServiceLinks(persistedData));
|
||||
}
|
||||
})
|
||||
.finally(() => {
|
||||
if (isMounted) {
|
||||
setStorageHydrated(true);
|
||||
}
|
||||
});
|
||||
|
||||
return () => {
|
||||
|
|
@ -183,16 +216,78 @@ export function LauncherApp() {
|
|||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
if (!storageHydrated) return;
|
||||
if (!authSession?.authenticated || !canUseAdminApi(authSession)) return;
|
||||
|
||||
const saveTimer = window.setTimeout(() => {
|
||||
persistLauncherData(data).catch((error: unknown) => {
|
||||
console.warn(error instanceof Error ? error.message : "Не удалось сохранить состояние витрины");
|
||||
let isMounted = true;
|
||||
|
||||
fetchControlPlaneSnapshot()
|
||||
.then((snapshot) => {
|
||||
if (isMounted) {
|
||||
setData(syncLauncherServiceLinks(snapshot.data));
|
||||
}
|
||||
})
|
||||
.catch((error: unknown) => {
|
||||
console.warn(error instanceof Error ? error.message : "Не удалось загрузить control-plane snapshot");
|
||||
});
|
||||
}, 350);
|
||||
|
||||
return () => window.clearTimeout(saveTimer);
|
||||
}, [data, storageHydrated]);
|
||||
return () => {
|
||||
isMounted = false;
|
||||
};
|
||||
}, [authSession]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!authSession?.authenticated) return;
|
||||
|
||||
let isMounted = true;
|
||||
|
||||
const refreshRuntimeState = async () => {
|
||||
try {
|
||||
const nextSession = await fetchAuthSession();
|
||||
|
||||
if (!isMounted) return;
|
||||
|
||||
setAuthSession(nextSession);
|
||||
setAuthError(null);
|
||||
|
||||
if (!nextSession.authenticated) {
|
||||
setAuthApps([]);
|
||||
return;
|
||||
}
|
||||
|
||||
const [persistedData, apps] = await Promise.all([
|
||||
canUseAdminApi(nextSession)
|
||||
? fetchControlPlaneSnapshot().then((snapshot) => snapshot.data)
|
||||
: loadPersistedLauncherData(),
|
||||
fetchAvailableApps(),
|
||||
]);
|
||||
|
||||
if (!isMounted) return;
|
||||
|
||||
if (persistedData) {
|
||||
setData(syncLauncherServiceLinks(persistedData));
|
||||
}
|
||||
|
||||
setAuthApps(apps);
|
||||
} catch (error: unknown) {
|
||||
console.warn(error instanceof Error ? error.message : "Не удалось обновить runtime состояние Launcher");
|
||||
}
|
||||
};
|
||||
|
||||
const eventSource = new EventSource("/api/events");
|
||||
|
||||
eventSource.addEventListener("nodedc-runtime", () => {
|
||||
void refreshRuntimeState();
|
||||
});
|
||||
|
||||
eventSource.onerror = () => {
|
||||
console.warn("Launcher event stream disconnected; browser will retry automatically");
|
||||
};
|
||||
|
||||
return () => {
|
||||
isMounted = false;
|
||||
eventSource.close();
|
||||
};
|
||||
}, [authSession?.authenticated]);
|
||||
|
||||
function handleProfileChange(userId: string) {
|
||||
const profile = profileOptions.find((option) => option.userId === userId);
|
||||
|
|
@ -227,200 +322,84 @@ export function LauncherApp() {
|
|||
});
|
||||
}
|
||||
|
||||
function applyControlPlaneMutation(request: Promise<ControlPlaneMutationResult>) {
|
||||
request
|
||||
.then((result) => {
|
||||
setData(syncLauncherServiceLinks(result.data));
|
||||
})
|
||||
.catch((error: unknown) => {
|
||||
console.warn(error instanceof Error ? error.message : "Не удалось выполнить admin API операцию");
|
||||
});
|
||||
}
|
||||
|
||||
function handleSetUserServiceAccess({ userId, serviceId, value }: SetUserServiceAccessCommand) {
|
||||
setData((current) => {
|
||||
const now = new Date().toISOString();
|
||||
const directGrant = current.grants.find(
|
||||
(grant) => grant.serviceId === serviceId && grant.targetType === "user" && grant.targetId === userId
|
||||
);
|
||||
const grantsWithoutDirect = current.grants.filter(
|
||||
(grant) => !(grant.serviceId === serviceId && grant.targetType === "user" && grant.targetId === userId)
|
||||
);
|
||||
const exceptionsWithoutDirect = current.exceptions.filter(
|
||||
(exception) => !(exception.serviceId === serviceId && exception.userId === userId)
|
||||
);
|
||||
const assignmentKey = accessAssignmentKey(userId, serviceId);
|
||||
|
||||
if (value === "unset") {
|
||||
return {
|
||||
...current,
|
||||
grants: grantsWithoutDirect,
|
||||
exceptions: exceptionsWithoutDirect,
|
||||
};
|
||||
}
|
||||
if (pendingAccessAssignments[assignmentKey]) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (value === "deny") {
|
||||
return {
|
||||
...current,
|
||||
grants: grantsWithoutDirect,
|
||||
exceptions: [
|
||||
...exceptionsWithoutDirect,
|
||||
{
|
||||
id: `exception_mock_${Date.now()}`,
|
||||
serviceId,
|
||||
userId,
|
||||
type: "deny",
|
||||
reason: "Создано из матрицы доступа.",
|
||||
createdAt: now,
|
||||
updatedAt: now,
|
||||
},
|
||||
],
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
...current,
|
||||
grants: [
|
||||
...grantsWithoutDirect,
|
||||
{
|
||||
id: directGrant?.id ?? `grant_mock_${Date.now()}`,
|
||||
serviceId,
|
||||
targetType: "user",
|
||||
targetId: userId,
|
||||
appRole: value,
|
||||
status: "active",
|
||||
createdAt: directGrant?.createdAt ?? now,
|
||||
updatedAt: now,
|
||||
},
|
||||
],
|
||||
exceptions: exceptionsWithoutDirect,
|
||||
};
|
||||
});
|
||||
setPendingAccessAssignments((current) => ({ ...current, [assignmentKey]: value }));
|
||||
setAdminUserServiceAccess({ userId, serviceId, value })
|
||||
.then((result) => {
|
||||
setData(syncLauncherServiceLinks(result.data));
|
||||
})
|
||||
.catch((error: unknown) => {
|
||||
console.warn(error instanceof Error ? error.message : "Не удалось выполнить admin API операцию");
|
||||
})
|
||||
.finally(() => {
|
||||
setPendingAccessAssignments((current) => {
|
||||
const { [assignmentKey]: _completed, ...rest } = current;
|
||||
return rest;
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
function handleCreateInvite(invite: Pick<Invite, "clientId" | "email" | "role">) {
|
||||
setData((current) => ({
|
||||
...current,
|
||||
invites: [
|
||||
{
|
||||
...invite,
|
||||
id: `invite_mock_${Date.now()}`,
|
||||
invitedByUserId: runtimeMe.user.id,
|
||||
token: `mock-${Date.now()}`,
|
||||
expiresAt: new Date(Date.now() + 14 * 24 * 60 * 60 * 1000).toISOString(),
|
||||
status: "created",
|
||||
createdAt: new Date().toISOString(),
|
||||
updatedAt: new Date().toISOString(),
|
||||
},
|
||||
...current.invites,
|
||||
],
|
||||
}));
|
||||
applyControlPlaneMutation(createAdminInvite(invite));
|
||||
}
|
||||
|
||||
function handleUpdateInvite(inviteId: string, patch: Partial<Invite>) {
|
||||
setData((current) => ({
|
||||
...current,
|
||||
invites: current.invites.map((invite) =>
|
||||
invite.id === inviteId
|
||||
? {
|
||||
...invite,
|
||||
...patch,
|
||||
updatedAt: new Date().toISOString(),
|
||||
}
|
||||
: invite
|
||||
),
|
||||
}));
|
||||
applyControlPlaneMutation(updateAdminInvite(inviteId, patch));
|
||||
}
|
||||
|
||||
function handleDeleteInvite(inviteId: string) {
|
||||
setData((current) => ({
|
||||
...current,
|
||||
invites: current.invites.filter((invite) => invite.id !== inviteId),
|
||||
}));
|
||||
applyControlPlaneMutation(deleteAdminInvite(inviteId));
|
||||
}
|
||||
|
||||
function handleRetrySync(syncId: string) {
|
||||
setData((current) => ({
|
||||
...current,
|
||||
syncStatuses: current.syncStatuses.map((sync): SyncStatus =>
|
||||
sync.id === syncId
|
||||
? {
|
||||
...sync,
|
||||
state: "pending",
|
||||
error: null,
|
||||
updatedAt: new Date().toISOString(),
|
||||
}
|
||||
: sync
|
||||
),
|
||||
}));
|
||||
applyControlPlaneMutation(retryAdminSync(syncId));
|
||||
}
|
||||
|
||||
function handleUpdateService(serviceId: string, patch: Partial<Service>) {
|
||||
setData((current) => ({
|
||||
...current,
|
||||
services: current.services.map((service) =>
|
||||
service.id === serviceId
|
||||
? syncServiceLaunchLink({
|
||||
...service,
|
||||
...patch,
|
||||
updatedAt: new Date().toISOString(),
|
||||
})
|
||||
: service
|
||||
),
|
||||
}));
|
||||
applyControlPlaneMutation(updateAdminService(serviceId, patch));
|
||||
}
|
||||
|
||||
function handleCreateClient() {
|
||||
const createdAt = new Date().toISOString();
|
||||
const index = data.clients.length + 1;
|
||||
|
||||
setData((current) => ({
|
||||
...current,
|
||||
clients: [
|
||||
...current.clients,
|
||||
{
|
||||
id: `client_mock_${Date.now()}`,
|
||||
type: "company",
|
||||
name: `Новый клиент ${index}`,
|
||||
legalName: `Новый клиент ${index}`,
|
||||
status: "demo",
|
||||
demoEndsAt: new Date(Date.now() + 14 * 24 * 60 * 60 * 1000).toISOString(),
|
||||
contactName: "",
|
||||
contactEmail: "",
|
||||
notes: "",
|
||||
createdAt,
|
||||
updatedAt: createdAt,
|
||||
},
|
||||
],
|
||||
}));
|
||||
applyControlPlaneMutation(
|
||||
createAdminClient({
|
||||
type: "company",
|
||||
name: `Новый клиент ${index}`,
|
||||
legalName: `Новый клиент ${index}`,
|
||||
status: "demo",
|
||||
demoEndsAt: new Date(Date.now() + 14 * 24 * 60 * 60 * 1000).toISOString(),
|
||||
contactName: "",
|
||||
contactEmail: "",
|
||||
notes: "",
|
||||
})
|
||||
);
|
||||
}
|
||||
|
||||
function handleUpdateClient(clientId: string, patch: Partial<Client>) {
|
||||
setData((current) => ({
|
||||
...current,
|
||||
clients: current.clients.map((client) =>
|
||||
client.id === clientId
|
||||
? {
|
||||
...client,
|
||||
...patch,
|
||||
updatedAt: new Date().toISOString(),
|
||||
}
|
||||
: client
|
||||
),
|
||||
}));
|
||||
applyControlPlaneMutation(updateAdminClient(clientId, patch));
|
||||
}
|
||||
|
||||
function handleDeleteClient(clientId: string) {
|
||||
const nextClientId = data.clients.find((client) => client.id !== clientId)?.id ?? activeClientId;
|
||||
|
||||
setData((current) => {
|
||||
if (current.clients.length <= 1) return current;
|
||||
|
||||
const deletedGroupIds = new Set(current.groups.filter((group) => group.clientId === clientId).map((group) => group.id));
|
||||
|
||||
return {
|
||||
...current,
|
||||
clients: current.clients.filter((client) => client.id !== clientId),
|
||||
memberships: current.memberships.filter((membership) => membership.clientId !== clientId),
|
||||
groups: current.groups.filter((group) => group.clientId !== clientId),
|
||||
grants: current.grants.filter(
|
||||
(grant) =>
|
||||
!(grant.targetType === "client" && grant.targetId === clientId) &&
|
||||
!(grant.targetType === "group" && deletedGroupIds.has(grant.targetId))
|
||||
),
|
||||
invites: current.invites.filter((invite) => invite.clientId !== clientId),
|
||||
syncStatuses: current.syncStatuses.filter((sync) => sync.objectId !== clientId),
|
||||
};
|
||||
});
|
||||
applyControlPlaneMutation(deleteAdminClient(clientId));
|
||||
|
||||
if (activeClientId === clientId) {
|
||||
setActiveClientId(nextClientId);
|
||||
|
|
@ -428,166 +407,63 @@ export function LauncherApp() {
|
|||
}
|
||||
|
||||
function handleUpdateUser(userId: string, patch: Partial<LauncherUser>) {
|
||||
setData((current) => ({
|
||||
...current,
|
||||
users: current.users.map((user) =>
|
||||
user.id === userId
|
||||
? {
|
||||
...user,
|
||||
...patch,
|
||||
updatedAt: new Date().toISOString(),
|
||||
}
|
||||
: user
|
||||
),
|
||||
}));
|
||||
applyControlPlaneMutation(updateAdminUserProfile(userId, patch));
|
||||
}
|
||||
|
||||
async function handleUpdateOwnProfile(patch: Partial<LauncherUser>) {
|
||||
const result = await updateOwnProfile(patch);
|
||||
setData(syncLauncherServiceLinks(result.data));
|
||||
}
|
||||
|
||||
async function handleUpdateOwnPassword(newPassword: string) {
|
||||
const result = await updateOwnPassword(newPassword);
|
||||
setData(syncLauncherServiceLinks(result.data));
|
||||
}
|
||||
|
||||
function handleCreateUser(command: CreateUserCommand) {
|
||||
createAdminUser(command)
|
||||
.then((result) => {
|
||||
setData(syncLauncherServiceLinks(result.data));
|
||||
|
||||
if (result.provisioning?.temporaryPassword) {
|
||||
window.alert(`Пользователь создан. Временный пароль: ${result.provisioning.temporaryPassword}`);
|
||||
}
|
||||
})
|
||||
.catch((error: unknown) => {
|
||||
console.warn(error instanceof Error ? error.message : "Не удалось создать пользователя");
|
||||
});
|
||||
}
|
||||
|
||||
function handleUpdateMembership(membershipId: string, patch: Partial<ClientMembership>) {
|
||||
setData((current) => ({
|
||||
...current,
|
||||
memberships: current.memberships.map((membership) =>
|
||||
membership.id === membershipId
|
||||
? {
|
||||
...membership,
|
||||
...patch,
|
||||
updatedAt: new Date().toISOString(),
|
||||
}
|
||||
: membership
|
||||
),
|
||||
}));
|
||||
applyControlPlaneMutation(updateAdminMembership(membershipId, patch));
|
||||
}
|
||||
|
||||
function handleDeleteMembership(membershipId: string) {
|
||||
setData((current) => {
|
||||
const membership = current.memberships.find((item) => item.id === membershipId);
|
||||
if (!membership) return current;
|
||||
|
||||
return {
|
||||
...current,
|
||||
memberships: current.memberships.filter((item) => item.id !== membershipId),
|
||||
groups: current.groups.map((group) =>
|
||||
group.clientId === membership.clientId
|
||||
? {
|
||||
...group,
|
||||
memberIds: group.memberIds.filter((userId) => userId !== membership.userId),
|
||||
updatedAt: new Date().toISOString(),
|
||||
}
|
||||
: group
|
||||
),
|
||||
};
|
||||
});
|
||||
applyControlPlaneMutation(deleteAdminMembership(membershipId));
|
||||
}
|
||||
|
||||
function handleCreateGroup(clientId: string) {
|
||||
const createdAt = new Date().toISOString();
|
||||
|
||||
setData((current) => ({
|
||||
...current,
|
||||
groups: [
|
||||
...current.groups,
|
||||
{
|
||||
id: `group_mock_${Date.now()}`,
|
||||
clientId,
|
||||
name: "Новая группа",
|
||||
description: "Описание группы",
|
||||
memberIds: [],
|
||||
createdAt,
|
||||
updatedAt: createdAt,
|
||||
},
|
||||
],
|
||||
}));
|
||||
applyControlPlaneMutation(createAdminGroup({ clientId, name: "Новая группа", description: "Описание группы", memberIds: [] }));
|
||||
}
|
||||
|
||||
function handleUpdateGroup(groupId: string, patch: Partial<ClientGroup>) {
|
||||
setData((current) => ({
|
||||
...current,
|
||||
groups: current.groups.map((group) =>
|
||||
group.id === groupId
|
||||
? {
|
||||
...group,
|
||||
...patch,
|
||||
updatedAt: new Date().toISOString(),
|
||||
}
|
||||
: group
|
||||
),
|
||||
}));
|
||||
applyControlPlaneMutation(updateAdminGroup(groupId, patch));
|
||||
}
|
||||
|
||||
function handleDeleteGroup(groupId: string) {
|
||||
setData((current) => ({
|
||||
...current,
|
||||
groups: current.groups.filter((group) => group.id !== groupId),
|
||||
grants: current.grants.filter((grant) => !(grant.targetType === "group" && grant.targetId === groupId)),
|
||||
}));
|
||||
applyControlPlaneMutation(deleteAdminGroup(groupId));
|
||||
}
|
||||
|
||||
function handleReorderServices(orderedServiceIds: string[]) {
|
||||
setData((current) => {
|
||||
const orderById = new Map(orderedServiceIds.map((serviceId, index) => [serviceId, (index + 1) * 10]));
|
||||
const now = new Date().toISOString();
|
||||
|
||||
return {
|
||||
...current,
|
||||
services: current.services.map((service) => {
|
||||
const nextOrder = orderById.get(service.id);
|
||||
|
||||
return nextOrder
|
||||
? {
|
||||
...service,
|
||||
order: nextOrder,
|
||||
updatedAt: now,
|
||||
}
|
||||
: service;
|
||||
}),
|
||||
};
|
||||
});
|
||||
applyControlPlaneMutation(reorderAdminServices(orderedServiceIds));
|
||||
}
|
||||
|
||||
function handleCreateService() {
|
||||
const createdAt = new Date().toISOString();
|
||||
|
||||
setData((current) => {
|
||||
const nextOrder = Math.max(0, ...current.services.map((service) => service.order)) + 10;
|
||||
const id = `service_mock_${Date.now()}`;
|
||||
|
||||
return {
|
||||
...current,
|
||||
services: [
|
||||
...current.services,
|
||||
{
|
||||
id,
|
||||
slug: `new-service-${current.services.length + 1}`,
|
||||
title: "New Service",
|
||||
subtitle: "Новый сервис",
|
||||
description: "Описание сервиса для витрины.",
|
||||
fullDescription: "Заполните описание, медиа и ссылку запуска в редакторе контента.",
|
||||
url: "https://service.handhdc.ru/sso/launch",
|
||||
launchUrl: "https://service.handhdc.ru/sso/launch",
|
||||
accentColor: "#F7F8F4",
|
||||
fallbackGradient: "linear-gradient(135deg, rgba(247, 248, 244, 0.72), rgba(36, 37, 42, 0.9) 52%, #090B0F 88%)",
|
||||
coverMediaSource: "url",
|
||||
coverMediaKind: "image",
|
||||
ambientMediaSource: "url",
|
||||
ambientMediaKind: "gif",
|
||||
status: "hidden",
|
||||
order: nextOrder,
|
||||
authentikApplicationSlug: `new-service-${current.services.length + 1}`,
|
||||
authentikGroupName: `service-new-${current.services.length + 1}`,
|
||||
createdAt,
|
||||
updatedAt: createdAt,
|
||||
},
|
||||
],
|
||||
};
|
||||
});
|
||||
applyControlPlaneMutation(createAdminService());
|
||||
}
|
||||
|
||||
function handleDeleteService(serviceId: string) {
|
||||
setData((current) => ({
|
||||
...current,
|
||||
services: current.services.filter((service) => service.id !== serviceId),
|
||||
grants: current.grants.filter((grant) => grant.serviceId !== serviceId),
|
||||
exceptions: current.exceptions.filter((exception) => exception.serviceId !== serviceId),
|
||||
}));
|
||||
applyControlPlaneMutation(deleteAdminService(serviceId));
|
||||
|
||||
setSelectedServiceId((current) => (current === serviceId ? undefined : current));
|
||||
}
|
||||
|
|
@ -613,6 +489,7 @@ export function LauncherApp() {
|
|||
onClientChange={setActiveClientId}
|
||||
onToggleAdmin={() => setAdminOpen((current) => !current)}
|
||||
onOpenShowcase={() => setAdminOpen(false)}
|
||||
onOpenProfileSettings={() => setProfileSettingsOpen(true)}
|
||||
onLogout={() => window.location.assign(authSession.logoutUrl)}
|
||||
/>
|
||||
|
||||
|
|
@ -638,9 +515,11 @@ export function LauncherApp() {
|
|||
onCreateClient={handleCreateClient}
|
||||
onUpdateClient={handleUpdateClient}
|
||||
onDeleteClient={handleDeleteClient}
|
||||
onCreateUser={handleCreateUser}
|
||||
onUpdateUser={handleUpdateUser}
|
||||
onUpdateMembership={handleUpdateMembership}
|
||||
onDeleteMembership={handleDeleteMembership}
|
||||
pendingAccessAssignments={pendingAccessAssignments}
|
||||
onCreateGroup={handleCreateGroup}
|
||||
onUpdateGroup={handleUpdateGroup}
|
||||
onDeleteGroup={handleDeleteGroup}
|
||||
|
|
@ -650,6 +529,14 @@ export function LauncherApp() {
|
|||
onDeleteService={handleDeleteService}
|
||||
/>
|
||||
) : null}
|
||||
{profileSettingsOpen && activeProfileUser ? (
|
||||
<ProfileSettingsPanel
|
||||
user={activeProfileUser}
|
||||
onClose={() => setProfileSettingsOpen(false)}
|
||||
onSaveProfile={handleUpdateOwnProfile}
|
||||
onChangePassword={handleUpdateOwnPassword}
|
||||
/>
|
||||
) : null}
|
||||
<ServiceRail services={launcherServices} selectedServiceId={selectedServiceId} onSelect={handleServiceSelect} />
|
||||
</main>
|
||||
</div>
|
||||
|
|
@ -663,6 +550,65 @@ function syncLauncherServiceLinks(data: LauncherData): LauncherData {
|
|||
};
|
||||
}
|
||||
|
||||
function accessAssignmentKey(userId: string, serviceId: string) {
|
||||
return `${userId}:${serviceId}`;
|
||||
}
|
||||
|
||||
function canUseAdminApi(session: AuthSession): boolean {
|
||||
return (
|
||||
session.authenticated &&
|
||||
(session.isSuperAdmin || session.groups.includes("nodedc:launcher:admin") || session.groups.includes("nodedc:superadmin"))
|
||||
);
|
||||
}
|
||||
|
||||
function resolveAuthenticatedContext(
|
||||
data: LauncherData,
|
||||
session: AuthenticatedSession,
|
||||
currentProfileId: string,
|
||||
currentClientId: string
|
||||
): { profileId: string; clientId: string } {
|
||||
const sessionEmail = session.user.email?.toLowerCase();
|
||||
const sessionSub = session.user.sub;
|
||||
const profile =
|
||||
data.users.find(
|
||||
(user) =>
|
||||
(sessionSub && user.authentikUserId === sessionSub) ||
|
||||
(sessionEmail && user.email.toLowerCase() === sessionEmail)
|
||||
) ??
|
||||
(session.isSuperAdmin ? data.users.find((user) => user.id === "user_root") : undefined) ??
|
||||
data.users.find((user) => user.id === currentProfileId) ??
|
||||
data.users[0];
|
||||
|
||||
if (!profile) {
|
||||
return { profileId: currentProfileId, clientId: currentClientId };
|
||||
}
|
||||
|
||||
return {
|
||||
profileId: profile.id,
|
||||
clientId: resolveDefaultClientId(data, profile.id, currentClientId),
|
||||
};
|
||||
}
|
||||
|
||||
function resolveDefaultClientId(data: LauncherData, userId: string, requestedClientId: string): string {
|
||||
const user = data.users.find((item) => item.id === userId);
|
||||
const isRoot = user?.id === "user_root";
|
||||
const availableClientIds = isRoot
|
||||
? data.clients.map((client) => client.id)
|
||||
: data.memberships.filter((membership) => membership.userId === userId && membership.status === "active").map((membership) => membership.clientId);
|
||||
|
||||
if (requestedClientId && availableClientIds.includes(requestedClientId)) {
|
||||
return requestedClientId;
|
||||
}
|
||||
|
||||
const defaultClientId = profileOptions.find((profile) => profile.userId === userId)?.defaultClientId;
|
||||
|
||||
if (defaultClientId && availableClientIds.includes(defaultClientId)) {
|
||||
return defaultClientId;
|
||||
}
|
||||
|
||||
return availableClientIds[0] ?? data.clients[0]?.id ?? requestedClientId;
|
||||
}
|
||||
|
||||
function AuthStateScreen({
|
||||
title,
|
||||
description,
|
||||
|
|
|
|||
|
|
@ -0,0 +1,220 @@
|
|||
import type { ServiceAccessException, ServiceAppRole, ServiceGrant } from "../../entities/access/types";
|
||||
import type { Client } from "../../entities/client/types";
|
||||
import type { Invite } from "../../entities/invite/types";
|
||||
import type { Service } from "../../entities/service/types";
|
||||
import type { SyncStatus } from "../../entities/sync/types";
|
||||
import type { ClientGroup, ClientMembership, LauncherUser } from "../../entities/user/types";
|
||||
import type { LauncherData } from "./mockApi";
|
||||
|
||||
export type AdminAccessAssignmentValue = Exclude<ServiceAppRole, "owner"> | "deny" | "unset";
|
||||
|
||||
export interface ControlPlaneSnapshot {
|
||||
actor: {
|
||||
id: string;
|
||||
name: string;
|
||||
email: string | null;
|
||||
source: string;
|
||||
};
|
||||
counts: Record<keyof LauncherData, number>;
|
||||
data: LauncherData;
|
||||
}
|
||||
|
||||
export interface ControlPlaneMutationResult {
|
||||
data: LauncherData;
|
||||
provisioning?: {
|
||||
authentikUserId: string;
|
||||
email: string;
|
||||
name: string;
|
||||
groups: string[];
|
||||
created: boolean;
|
||||
temporaryPassword: string | null;
|
||||
} | null;
|
||||
}
|
||||
|
||||
export async function fetchControlPlaneSnapshot(): Promise<ControlPlaneSnapshot> {
|
||||
return requestJson<ControlPlaneSnapshot>("/api/admin/control-plane");
|
||||
}
|
||||
|
||||
export async function createAdminClient(payload: Partial<Client>): Promise<ControlPlaneMutationResult> {
|
||||
return requestJson<ControlPlaneMutationResult>("/api/admin/clients", {
|
||||
method: "POST",
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
}
|
||||
|
||||
export async function updateAdminClient(clientId: string, patch: Partial<Client>): Promise<ControlPlaneMutationResult> {
|
||||
return requestJson<ControlPlaneMutationResult>(`/api/admin/clients/${encodeURIComponent(clientId)}`, {
|
||||
method: "PATCH",
|
||||
body: JSON.stringify(patch),
|
||||
});
|
||||
}
|
||||
|
||||
export async function deleteAdminClient(clientId: string): Promise<ControlPlaneMutationResult> {
|
||||
return requestJson<ControlPlaneMutationResult>(`/api/admin/clients/${encodeURIComponent(clientId)}`, { method: "DELETE" });
|
||||
}
|
||||
|
||||
export async function updateAdminUserProfile(userId: string, patch: Partial<LauncherUser>): Promise<ControlPlaneMutationResult> {
|
||||
return requestJson<ControlPlaneMutationResult>(`/api/admin/users/${encodeURIComponent(userId)}/profile`, {
|
||||
method: "PATCH",
|
||||
body: JSON.stringify(patch),
|
||||
});
|
||||
}
|
||||
|
||||
export async function createAdminUser(payload: {
|
||||
clientId: string;
|
||||
email: string;
|
||||
name?: string;
|
||||
role?: ClientMembership["role"];
|
||||
groupIds?: string[];
|
||||
provisionAuth?: boolean;
|
||||
generatePassword?: boolean;
|
||||
password?: string;
|
||||
}): Promise<ControlPlaneMutationResult> {
|
||||
return requestJson<ControlPlaneMutationResult>("/api/admin/users", {
|
||||
method: "POST",
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
}
|
||||
|
||||
export async function provisionAdminUserAuthentik(
|
||||
userId: string,
|
||||
payload: { generatePassword?: boolean; password?: string } = {}
|
||||
): Promise<ControlPlaneMutationResult> {
|
||||
return requestJson<ControlPlaneMutationResult>(`/api/admin/users/${encodeURIComponent(userId)}/provision-authentik`, {
|
||||
method: "POST",
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
}
|
||||
|
||||
export async function updateAdminMembership(
|
||||
membershipId: string,
|
||||
patch: Partial<ClientMembership>
|
||||
): Promise<ControlPlaneMutationResult> {
|
||||
return requestJson<ControlPlaneMutationResult>(`/api/admin/memberships/${encodeURIComponent(membershipId)}`, {
|
||||
method: "PATCH",
|
||||
body: JSON.stringify(patch),
|
||||
});
|
||||
}
|
||||
|
||||
export async function deleteAdminMembership(membershipId: string): Promise<ControlPlaneMutationResult> {
|
||||
return requestJson<ControlPlaneMutationResult>(`/api/admin/memberships/${encodeURIComponent(membershipId)}`, { method: "DELETE" });
|
||||
}
|
||||
|
||||
export async function createAdminGroup(payload: Pick<ClientGroup, "clientId"> & Partial<ClientGroup>): Promise<ControlPlaneMutationResult> {
|
||||
return requestJson<ControlPlaneMutationResult>("/api/admin/groups", {
|
||||
method: "POST",
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
}
|
||||
|
||||
export async function updateAdminGroup(groupId: string, patch: Partial<ClientGroup>): Promise<ControlPlaneMutationResult> {
|
||||
return requestJson<ControlPlaneMutationResult>(`/api/admin/groups/${encodeURIComponent(groupId)}`, {
|
||||
method: "PATCH",
|
||||
body: JSON.stringify(patch),
|
||||
});
|
||||
}
|
||||
|
||||
export async function deleteAdminGroup(groupId: string): Promise<ControlPlaneMutationResult> {
|
||||
return requestJson<ControlPlaneMutationResult>(`/api/admin/groups/${encodeURIComponent(groupId)}`, { method: "DELETE" });
|
||||
}
|
||||
|
||||
export async function createAdminService(payload: Partial<Service> = {}): Promise<ControlPlaneMutationResult> {
|
||||
return requestJson<ControlPlaneMutationResult>("/api/admin/services", {
|
||||
method: "POST",
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
}
|
||||
|
||||
export async function updateAdminService(serviceId: string, patch: Partial<Service>): Promise<ControlPlaneMutationResult> {
|
||||
return requestJson<ControlPlaneMutationResult>(`/api/admin/services/${encodeURIComponent(serviceId)}`, {
|
||||
method: "PATCH",
|
||||
body: JSON.stringify(patch),
|
||||
});
|
||||
}
|
||||
|
||||
export async function reorderAdminServices(orderedServiceIds: string[]): Promise<ControlPlaneMutationResult> {
|
||||
return requestJson<ControlPlaneMutationResult>("/api/admin/services/reorder", {
|
||||
method: "PATCH",
|
||||
body: JSON.stringify({ orderedServiceIds }),
|
||||
});
|
||||
}
|
||||
|
||||
export async function deleteAdminService(serviceId: string): Promise<ControlPlaneMutationResult> {
|
||||
return requestJson<ControlPlaneMutationResult>(`/api/admin/services/${encodeURIComponent(serviceId)}`, { method: "DELETE" });
|
||||
}
|
||||
|
||||
export async function createAdminInvite(
|
||||
payload: Pick<Invite, "clientId" | "email" | "role">
|
||||
): Promise<ControlPlaneMutationResult> {
|
||||
return requestJson<ControlPlaneMutationResult>("/api/admin/invites", {
|
||||
method: "POST",
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
}
|
||||
|
||||
export async function updateAdminInvite(inviteId: string, patch: Partial<Invite>): Promise<ControlPlaneMutationResult> {
|
||||
return requestJson<ControlPlaneMutationResult>(`/api/admin/invites/${encodeURIComponent(inviteId)}`, {
|
||||
method: "PATCH",
|
||||
body: JSON.stringify(patch),
|
||||
});
|
||||
}
|
||||
|
||||
export async function deleteAdminInvite(inviteId: string): Promise<ControlPlaneMutationResult> {
|
||||
return requestJson<ControlPlaneMutationResult>(`/api/admin/invites/${encodeURIComponent(inviteId)}`, { method: "DELETE" });
|
||||
}
|
||||
|
||||
export async function setAdminUserServiceAccess(payload: {
|
||||
userId: string;
|
||||
serviceId: string;
|
||||
value: AdminAccessAssignmentValue;
|
||||
}): Promise<ControlPlaneMutationResult> {
|
||||
return requestJson<ControlPlaneMutationResult>("/api/admin/access/user-service", {
|
||||
method: "POST",
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
}
|
||||
|
||||
export async function upsertAdminGrant(payload: Partial<ServiceGrant>): Promise<ControlPlaneMutationResult> {
|
||||
return requestJson<ControlPlaneMutationResult>("/api/admin/access/grants", {
|
||||
method: "POST",
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
}
|
||||
|
||||
export async function upsertAdminException(payload: Partial<ServiceAccessException>): Promise<ControlPlaneMutationResult> {
|
||||
return requestJson<ControlPlaneMutationResult>("/api/admin/access/exceptions", {
|
||||
method: "POST",
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
}
|
||||
|
||||
export async function retryAdminSync(syncId: string): Promise<ControlPlaneMutationResult> {
|
||||
return requestJson<ControlPlaneMutationResult>(`/api/admin/sync/${encodeURIComponent(syncId)}/retry`, { method: "POST" });
|
||||
}
|
||||
|
||||
async function requestJson<T>(url: string, init: RequestInit = {}): Promise<T> {
|
||||
const headers = new Headers(init.headers);
|
||||
if (!headers.has("Content-Type")) {
|
||||
headers.set("Content-Type", "application/json");
|
||||
}
|
||||
|
||||
const response = await fetch(url, {
|
||||
...init,
|
||||
headers,
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(await readErrorMessage(response));
|
||||
}
|
||||
|
||||
return (await response.json()) as T;
|
||||
}
|
||||
|
||||
async function readErrorMessage(response: Response) {
|
||||
try {
|
||||
const payload = (await response.json()) as { error?: string };
|
||||
return payload.error ?? response.statusText;
|
||||
} catch {
|
||||
return response.statusText;
|
||||
}
|
||||
}
|
||||
|
|
@ -3,6 +3,7 @@ export interface AuthUser {
|
|||
email: string;
|
||||
name: string;
|
||||
preferredUsername: string | null;
|
||||
avatarUrl: string | null;
|
||||
groups: string[];
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -30,6 +30,7 @@ export interface AuthentikClaimsMock {
|
|||
sub: string;
|
||||
email: string;
|
||||
name: string;
|
||||
avatarUrl?: string | null;
|
||||
groups: string[];
|
||||
activeClientId: string;
|
||||
}
|
||||
|
|
@ -98,40 +99,16 @@ export const initialLauncherData: LauncherData = {
|
|||
export const profileOptions: ProfileOption[] = [
|
||||
{
|
||||
userId: "user_root",
|
||||
label: "Root Admin",
|
||||
description: "Полный каталог и все клиенты",
|
||||
label: "DC Touch",
|
||||
description: "NODE.DC superadmin",
|
||||
defaultClientId: "client_romashka",
|
||||
},
|
||||
{
|
||||
userId: "user_ivan",
|
||||
label: "Client Owner",
|
||||
description: "Иван, владелец Ромашки и админ демо-клиента",
|
||||
userId: "user_silver_psih",
|
||||
label: "Silver Psy",
|
||||
description: "DCTOUCH manager",
|
||||
defaultClientId: "client_romashka",
|
||||
},
|
||||
{
|
||||
userId: "user_vera",
|
||||
label: "Client Admin",
|
||||
description: "Вера, админ ООО Ромашка",
|
||||
defaultClientId: "client_romashka",
|
||||
},
|
||||
{
|
||||
userId: "user_vasya",
|
||||
label: "Member",
|
||||
description: "Василий, обычный участник",
|
||||
defaultClientId: "client_romashka",
|
||||
},
|
||||
{
|
||||
userId: "user_lena",
|
||||
label: "Member + deny",
|
||||
description: "Лена, участник с deny-исключением",
|
||||
defaultClientId: "client_romashka",
|
||||
},
|
||||
{
|
||||
userId: "user_maria",
|
||||
label: "Client Owner demo",
|
||||
description: "Мария, владелец демо-клиента",
|
||||
defaultClientId: "client_roga_kopyta",
|
||||
},
|
||||
];
|
||||
|
||||
export function buildMe(data: LauncherData, userId: string, requestedClientId?: string): MeResponse {
|
||||
|
|
@ -237,7 +214,7 @@ export function buildLauncherServices(data: LauncherData, userId: string, active
|
|||
effectiveAccess,
|
||||
};
|
||||
})
|
||||
.filter((service) => isRoot || service.effectiveAccess.visible);
|
||||
.filter((service) => isRoot || service.status !== "hidden");
|
||||
}
|
||||
|
||||
export function buildAccessMatrix(data: LauncherData, clientId: string, includeAllServices: boolean): AccessMatrix {
|
||||
|
|
|
|||
|
|
@ -12,40 +12,17 @@ export const mockClients: Client[] = [
|
|||
{
|
||||
id: "client_romashka",
|
||||
type: "company",
|
||||
name: "ООО Ромашка",
|
||||
legalName: "ООО Ромашка",
|
||||
name: "DCTOUCH",
|
||||
legalName: "ООО ДИСИТАЧ",
|
||||
status: "active",
|
||||
contractStartsAt: "2026-05-04T00:00:00.000Z",
|
||||
contractEndsAt: null,
|
||||
paidUntil: null,
|
||||
demoEndsAt: null,
|
||||
contactName: "Иван Петров",
|
||||
contactEmail: "ivan@romashka.ru",
|
||||
notes: "Основной demo-клиент для проверки Task Manager, NodeDC и deny-исключений.",
|
||||
createdAt: "2026-04-01T10:00:00Z",
|
||||
updatedAt: now,
|
||||
},
|
||||
{
|
||||
id: "client_roga_kopyta",
|
||||
type: "company",
|
||||
name: "ООО Рога и Копыта",
|
||||
legalName: "ООО Рога и Копыта",
|
||||
status: "demo",
|
||||
demoEndsAt: "2026-06-01T00:00:00Z",
|
||||
contactName: "Мария Иванова",
|
||||
contactEmail: "maria@example.ru",
|
||||
notes: "Клиент на демо-доступе, подключены только базовые сервисы.",
|
||||
createdAt: "2026-04-10T10:00:00Z",
|
||||
updatedAt: now,
|
||||
},
|
||||
{
|
||||
id: "client_private_architect",
|
||||
type: "person",
|
||||
name: "Илья Архитектор",
|
||||
legalName: null,
|
||||
status: "suspended",
|
||||
demoEndsAt: "2026-04-20T00:00:00Z",
|
||||
contactName: "Илья Архитектор",
|
||||
contactEmail: "ilya@example.ru",
|
||||
notes: "Пример приостановленного частного клиента.",
|
||||
createdAt: "2026-03-14T10:00:00Z",
|
||||
contactName: "DC Touch",
|
||||
contactEmail: "dcctouch@gmail.com",
|
||||
notes: "Live-клиент NODE.DC для первичной проверки control-plane, SSO и доступа к сервисам.",
|
||||
createdAt: "2026-05-04T00:00:00.000Z",
|
||||
updatedAt: now,
|
||||
},
|
||||
];
|
||||
|
|
@ -53,92 +30,44 @@ export const mockClients: Client[] = [
|
|||
export const mockUsers: LauncherUser[] = [
|
||||
{
|
||||
id: "user_root",
|
||||
authentikUserId: "ak-root",
|
||||
name: "Root Admin",
|
||||
email: "root@nodedc.local",
|
||||
authentikUserId: null,
|
||||
name: "DC Touch",
|
||||
email: "dcctouch@gmail.com",
|
||||
phone: null,
|
||||
position: "NODE.DC Super Admin",
|
||||
notes: "Главный супер-администратор NODE.DC.",
|
||||
avatarUrl: null,
|
||||
globalStatus: "active",
|
||||
createdAt: "2026-04-01T10:00:00Z",
|
||||
createdAt: "2026-05-04T00:00:00.000Z",
|
||||
updatedAt: now,
|
||||
},
|
||||
{
|
||||
id: "user_ivan",
|
||||
authentikUserId: "ak-ivan",
|
||||
name: "Иван Петров",
|
||||
email: "ivan@romashka.ru",
|
||||
id: "user_silver_psih",
|
||||
authentikUserId: null,
|
||||
name: "Silver Psy",
|
||||
email: "silver_psih@yahoo.com",
|
||||
phone: null,
|
||||
position: "Manager",
|
||||
notes: "Живой пользователь из Plane. Требует Authentik invite/sync flow.",
|
||||
avatarUrl: null,
|
||||
globalStatus: "active",
|
||||
createdAt: "2026-04-01T10:00:00Z",
|
||||
updatedAt: now,
|
||||
},
|
||||
{
|
||||
id: "user_vera",
|
||||
authentikUserId: "ak-vera",
|
||||
name: "Вера Соколова",
|
||||
email: "vera@romashka.ru",
|
||||
globalStatus: "active",
|
||||
createdAt: "2026-04-02T10:00:00Z",
|
||||
updatedAt: now,
|
||||
},
|
||||
{
|
||||
id: "user_vasya",
|
||||
authentikUserId: "ak-vasya",
|
||||
name: "Василий Орлов",
|
||||
email: "vasya@romashka.ru",
|
||||
globalStatus: "active",
|
||||
createdAt: "2026-04-05T10:00:00Z",
|
||||
updatedAt: now,
|
||||
},
|
||||
{
|
||||
id: "user_lena",
|
||||
authentikUserId: "ak-lena",
|
||||
name: "Лена Волкова",
|
||||
email: "lena@romashka.ru",
|
||||
globalStatus: "active",
|
||||
createdAt: "2026-04-08T10:00:00Z",
|
||||
updatedAt: now,
|
||||
},
|
||||
{
|
||||
id: "user_maria",
|
||||
authentikUserId: "ak-maria",
|
||||
name: "Мария Иванова",
|
||||
email: "maria@example.ru",
|
||||
globalStatus: "active",
|
||||
createdAt: "2026-04-10T10:00:00Z",
|
||||
updatedAt: now,
|
||||
},
|
||||
{
|
||||
id: "user_blocked",
|
||||
authentikUserId: "ak-blocked",
|
||||
name: "Олег Заблокирован",
|
||||
email: "oleg@romashka.ru",
|
||||
globalStatus: "blocked",
|
||||
createdAt: "2026-04-12T10:00:00Z",
|
||||
createdAt: "2026-05-04T00:00:00.000Z",
|
||||
updatedAt: now,
|
||||
},
|
||||
];
|
||||
|
||||
export const mockMemberships: ClientMembership[] = [
|
||||
membership("mem_ivan_romashka", "client_romashka", "user_ivan", "client_owner"),
|
||||
membership("mem_vera_romashka", "client_romashka", "user_vera", "client_admin"),
|
||||
membership("mem_vasya_romashka", "client_romashka", "user_vasya", "member"),
|
||||
membership("mem_lena_romashka", "client_romashka", "user_lena", "member"),
|
||||
membership("mem_blocked_romashka", "client_romashka", "user_blocked", "member", "disabled"),
|
||||
membership("mem_maria_roga", "client_roga_kopyta", "user_maria", "client_owner"),
|
||||
membership("mem_ivan_roga", "client_roga_kopyta", "user_ivan", "client_admin"),
|
||||
membership("mem_dc_touch_dctouch", "client_romashka", "user_root", "client_owner"),
|
||||
membership("mem_silver_psih_dctouch", "client_romashka", "user_silver_psih", "member"),
|
||||
];
|
||||
|
||||
export const mockGroups: ClientGroup[] = [
|
||||
group("group_romashka_leads", "client_romashka", "Руководство", "Собственники и руководители клиента.", [
|
||||
"user_ivan",
|
||||
"user_vera",
|
||||
group("group_dctouch_admins", "client_romashka", "Администраторы", "Администраторы клиента и владельцы платформенного доступа.", [
|
||||
"user_root",
|
||||
]),
|
||||
group("group_romashka_accounting", "client_romashka", "Бухгалтерия", "1C и финансовые сценарии.", [
|
||||
"user_lena",
|
||||
group("group_dctouch_managers", "client_romashka", "Менеджеры", "Рабочая группа менеджеров с доступом к операционному контуру.", [
|
||||
"user_silver_psih",
|
||||
]),
|
||||
group("group_romashka_ops", "client_romashka", "Операторы", "Ежедневная работа в задачах и тендерах.", [
|
||||
"user_vasya",
|
||||
"user_lena",
|
||||
]),
|
||||
group("group_roga_demo", "client_roga_kopyta", "Демо-команда", "Пилотный контур клиента.", ["user_maria", "user_ivan"]),
|
||||
];
|
||||
|
||||
export const mockServices: Service[] = [
|
||||
|
|
@ -272,82 +201,43 @@ export const mockServices: Service[] = [
|
|||
];
|
||||
|
||||
export const mockGrants: ServiceGrant[] = [
|
||||
grant("grant_romashka_task", "service_task_manager", "client", "client_romashka", "member"),
|
||||
grant("grant_romashka_nodedc_leads", "service_nodedc", "group", "group_romashka_leads", "admin"),
|
||||
grant("grant_romashka_1c_accounting", "service_1c", "group", "group_romashka_accounting", "member"),
|
||||
grant("grant_romashka_tender_ops", "service_tender", "group", "group_romashka_ops", "viewer"),
|
||||
grant("grant_romashka_twin_vasya", "service_digital_twin", "user", "user_vasya", "viewer"),
|
||||
grant("grant_roga_task", "service_task_manager", "client", "client_roga_kopyta", "member"),
|
||||
grant("grant_roga_nodedc", "service_nodedc", "client", "client_roga_kopyta", "viewer"),
|
||||
grant("grant_dctouch_task_admins", "service_task_manager", "group", "group_dctouch_admins", "admin"),
|
||||
grant("grant_dctouch_task_managers", "service_task_manager", "group", "group_dctouch_managers", "member"),
|
||||
grant("grant_dctouch_nodedc_admins", "service_nodedc", "group", "group_dctouch_admins", "admin"),
|
||||
];
|
||||
|
||||
export const mockExceptions: ServiceAccessException[] = [
|
||||
{
|
||||
id: "exception_lena_task_deny",
|
||||
serviceId: "service_task_manager",
|
||||
userId: "user_lena",
|
||||
type: "deny",
|
||||
reason: "Индивидуально отключён Task Manager на период ревизии доступа.",
|
||||
createdAt: "2026-04-28T10:00:00Z",
|
||||
updatedAt: now,
|
||||
},
|
||||
];
|
||||
export const mockExceptions: ServiceAccessException[] = [];
|
||||
|
||||
export const mockInvites: Invite[] = [
|
||||
{
|
||||
id: "invite_romashka_analyst",
|
||||
clientId: "client_romashka",
|
||||
email: "analyst@romashka.ru",
|
||||
role: "member",
|
||||
invitedByUserId: "user_ivan",
|
||||
token: "romashka-analyst-demo",
|
||||
expiresAt: "2026-05-15T12:00:00Z",
|
||||
status: "sent",
|
||||
createdAt: "2026-04-30T12:00:00Z",
|
||||
updatedAt: now,
|
||||
},
|
||||
{
|
||||
id: "invite_roga_admin",
|
||||
clientId: "client_roga_kopyta",
|
||||
email: "ops@example.ru",
|
||||
role: "client_admin",
|
||||
invitedByUserId: "user_maria",
|
||||
token: "roga-admin-demo",
|
||||
expiresAt: "2026-05-18T12:00:00Z",
|
||||
status: "created",
|
||||
createdAt: "2026-04-30T14:00:00Z",
|
||||
updatedAt: now,
|
||||
},
|
||||
];
|
||||
export const mockInvites: Invite[] = [];
|
||||
|
||||
export const mockSyncStatuses: SyncStatus[] = [
|
||||
sync("sync_romashka_auth", "client_romashka", "ООО Ромашка", "client", "authentik", "synced"),
|
||||
sync("sync_task_auth", "service_task_manager", "Task Manager", "service", "authentik", "synced"),
|
||||
sync("sync_dctouch_client_authentik", "client_romashka", "DCTOUCH", "client", "authentik", "synced"),
|
||||
sync("sync_dc_touch_authentik", "user_root", "dcctouch@gmail.com", "user", "authentik", "synced"),
|
||||
sync(
|
||||
"sync_lena_task",
|
||||
"exception_lena_task_deny",
|
||||
"Deny: Лена / Task Manager",
|
||||
"grant",
|
||||
"task_manager",
|
||||
"sync_silver_psih_authentik",
|
||||
"user_silver_psih",
|
||||
"silver_psih@yahoo.com",
|
||||
"user",
|
||||
"authentik",
|
||||
"pending",
|
||||
null
|
||||
),
|
||||
sync(
|
||||
"sync_roga_nodedc",
|
||||
"client_roga_kopyta",
|
||||
"ООО Рога и Копыта",
|
||||
"client",
|
||||
"nodedc",
|
||||
"error",
|
||||
"OIDC binding ещё не создан для demo-клиента."
|
||||
"Пользователь найден в Plane, но ещё не создан в Authentik через Launcher invite/sync flow."
|
||||
),
|
||||
sync("sync_dctouch_groups_authentik", "client_romashka:groups", "DCTOUCH groups", "group", "authentik", "pending"),
|
||||
sync("sync_task_manager_authentik", "service_task_manager", "OPERATIONAL CORE", "service", "authentik", "synced"),
|
||||
];
|
||||
|
||||
export const mockAuditEvents: AuditEvent[] = [
|
||||
audit("audit_1", "2026-05-01T08:40:00Z", "user_root", "Root Admin", "Создан сервис", "service", "Digital Modules", "success", null),
|
||||
audit("audit_2", "2026-05-01T08:20:00Z", "user_ivan", "Иван Петров", "Создан invite", "invite", "analyst@romashka.ru", "success", "Срок действия до 15.05.2026"),
|
||||
audit("audit_3", "2026-04-30T17:10:00Z", "user_root", "Root Admin", "Создано deny-исключение", "access", "Лена / Task Manager", "warning", "Индивидуальное правило перекрыло client grant."),
|
||||
audit("audit_4", "2026-04-30T16:00:00Z", "user_root", "Root Admin", "Ошибка синхронизации", "sync", "ООО Рога и Копыта / NodeDC", "error", "Нет application binding."),
|
||||
audit(
|
||||
"audit_live_seed_control_plane",
|
||||
"2026-05-04T00:00:00.000Z",
|
||||
"system",
|
||||
"NODE.DC seed",
|
||||
"Применён live seed control-plane",
|
||||
"control_plane",
|
||||
"Launcher users and access",
|
||||
"success",
|
||||
"Demo-участники удалены из runtime storage. Оставлены dcctouch@gmail.com и silver_psih@yahoo.com."
|
||||
),
|
||||
];
|
||||
|
||||
function membership(
|
||||
|
|
|
|||
|
|
@ -0,0 +1,57 @@
|
|||
import type { ClientMembership, LauncherUser } from "../../entities/user/types";
|
||||
import type { LauncherData } from "./mockApi";
|
||||
|
||||
export interface ProfileResponse {
|
||||
user: LauncherUser;
|
||||
memberships: ClientMembership[];
|
||||
}
|
||||
|
||||
export interface ProfileMutationResult {
|
||||
data: LauncherData;
|
||||
}
|
||||
|
||||
export async function fetchOwnProfile(): Promise<ProfileResponse> {
|
||||
return requestJson<ProfileResponse>("/api/profile");
|
||||
}
|
||||
|
||||
export async function updateOwnProfile(patch: Partial<LauncherUser>): Promise<ProfileMutationResult> {
|
||||
return requestJson<ProfileMutationResult>("/api/profile", {
|
||||
method: "PATCH",
|
||||
body: JSON.stringify(patch),
|
||||
});
|
||||
}
|
||||
|
||||
export async function updateOwnPassword(newPassword: string): Promise<ProfileMutationResult> {
|
||||
return requestJson<ProfileMutationResult>("/api/profile/password", {
|
||||
method: "POST",
|
||||
body: JSON.stringify({ newPassword }),
|
||||
});
|
||||
}
|
||||
|
||||
async function requestJson<T>(url: string, init: RequestInit = {}): Promise<T> {
|
||||
const headers = new Headers(init.headers);
|
||||
|
||||
if (!headers.has("Content-Type")) {
|
||||
headers.set("Content-Type", "application/json");
|
||||
}
|
||||
|
||||
const response = await fetch(url, {
|
||||
...init,
|
||||
headers,
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(await readErrorMessage(response));
|
||||
}
|
||||
|
||||
return (await response.json()) as T;
|
||||
}
|
||||
|
||||
async function readErrorMessage(response: Response) {
|
||||
try {
|
||||
const payload = (await response.json()) as { error?: string };
|
||||
return payload.error ?? response.statusText;
|
||||
} catch {
|
||||
return response.statusText;
|
||||
}
|
||||
}
|
||||
|
|
@ -28,21 +28,37 @@ export function NodeDcProfileMenu({ user, coverUrl = "/storage/default.gif", tri
|
|||
surfaceClassName="nodedc-ui-profile-menu"
|
||||
trigger={({ open, toggle, setTriggerRef }) => trigger({ open, toggle, setTriggerRef })}
|
||||
>
|
||||
<div className="nodedc-ui-profile-card">
|
||||
<div className="nodedc-ui-profile-card__cover" style={{ backgroundImage: `url(${coverUrl})` }}>
|
||||
<Avatar user={user} className="nodedc-ui-profile-card__avatar" />
|
||||
<strong>{user.name}</strong>
|
||||
<span>{user.email}</span>
|
||||
{({ close }) => (
|
||||
<div className="nodedc-ui-profile-card">
|
||||
<div className="nodedc-ui-profile-card__cover" style={{ backgroundImage: `url(${coverUrl})` }}>
|
||||
<Avatar user={user} className="nodedc-ui-profile-card__avatar" />
|
||||
<strong>{user.name}</strong>
|
||||
<span>{user.email}</span>
|
||||
</div>
|
||||
<button
|
||||
className="nodedc-ui-profile-card__row"
|
||||
type="button"
|
||||
onClick={() => {
|
||||
close();
|
||||
onSettings?.();
|
||||
}}
|
||||
>
|
||||
<Settings size={15} strokeWidth={1.7} />
|
||||
<span>Настройки</span>
|
||||
</button>
|
||||
<button
|
||||
className="nodedc-ui-profile-card__row"
|
||||
type="button"
|
||||
onClick={() => {
|
||||
close();
|
||||
onLogout?.();
|
||||
}}
|
||||
>
|
||||
<LogOut size={15} strokeWidth={1.7} />
|
||||
<span>Выйти</span>
|
||||
</button>
|
||||
</div>
|
||||
<button className="nodedc-ui-profile-card__row" type="button" onClick={onSettings}>
|
||||
<Settings size={15} strokeWidth={1.7} />
|
||||
<span>Настройки</span>
|
||||
</button>
|
||||
<button className="nodedc-ui-profile-card__row" type="button" onClick={onLogout}>
|
||||
<LogOut size={15} strokeWidth={1.7} />
|
||||
<span>Выйти</span>
|
||||
</button>
|
||||
</div>
|
||||
)}
|
||||
</NodeDcDropdown>
|
||||
);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -449,8 +449,10 @@ code {
|
|||
padding-left: calc(var(--launcher-page-pad) + var(--admin-nav-width) + var(--admin-content-width) + (var(--admin-panel-gap) * 2));
|
||||
}
|
||||
|
||||
.launcher-main:has(.admin-panel-layer--content-open) .stage-video-topline,
|
||||
.launcher-main:has(.admin-panel-layer--content-open) .stage-side-controls,
|
||||
.launcher-main:has(.profile-settings-layer) .service-stage {
|
||||
padding-right: calc(var(--launcher-page-pad) + var(--admin-nav-width) + var(--admin-panel-gap));
|
||||
}
|
||||
|
||||
.launcher-main:has(.admin-panel-layer--content-open) .stage-service-overlay,
|
||||
.launcher-main:has(.admin-panel-layer--content-open) .stage-video-controls,
|
||||
.launcher-main:has(.admin-panel-layer--content-open) .stage-timeline-strip {
|
||||
|
|
@ -470,6 +472,7 @@ code {
|
|||
background: #050506;
|
||||
transition:
|
||||
padding-left 440ms cubic-bezier(0.22, 1, 0.36, 1),
|
||||
padding-right 440ms cubic-bezier(0.22, 1, 0.36, 1),
|
||||
background 220ms ease;
|
||||
}
|
||||
|
||||
|
|
@ -536,21 +539,6 @@ code {
|
|||
content: "";
|
||||
}
|
||||
|
||||
.stage-video-topline {
|
||||
position: absolute;
|
||||
z-index: 3;
|
||||
top: 1.05rem;
|
||||
left: 1.05rem;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 0.6rem;
|
||||
color: rgba(255, 255, 255, 0.86);
|
||||
font-size: 0.95rem;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.stage-round-button,
|
||||
.stage-side-controls span,
|
||||
.stage-video-controls button {
|
||||
display: grid;
|
||||
place-items: center;
|
||||
|
|
@ -562,23 +550,30 @@ code {
|
|||
-webkit-backdrop-filter: blur(18px);
|
||||
}
|
||||
|
||||
.stage-round-button {
|
||||
width: 2rem;
|
||||
height: 2rem;
|
||||
}
|
||||
|
||||
.stage-side-controls {
|
||||
.stage-empty-title {
|
||||
position: absolute;
|
||||
z-index: 3;
|
||||
left: 1.05rem;
|
||||
top: 31%;
|
||||
z-index: 4;
|
||||
top: 5.76rem;
|
||||
left: 5.76rem;
|
||||
display: grid;
|
||||
gap: 0.62rem;
|
||||
gap: 0.22rem;
|
||||
color: rgba(255, 255, 255, 0.94);
|
||||
text-transform: uppercase;
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.stage-side-controls span {
|
||||
width: 2rem;
|
||||
height: 2rem;
|
||||
.stage-empty-title span {
|
||||
color: rgba(64, 64, 64, 0.92);
|
||||
font-size: clamp(1.82rem, 2.3vw, 2.52rem);
|
||||
font-weight: 350;
|
||||
line-height: 1;
|
||||
}
|
||||
|
||||
.stage-empty-title strong {
|
||||
color: rgba(255, 255, 255, 0.94);
|
||||
font-size: clamp(1.82rem, 2.3vw, 2.52rem);
|
||||
font-weight: 350;
|
||||
line-height: 1;
|
||||
}
|
||||
|
||||
.stage-service-overlay {
|
||||
|
|
@ -702,13 +697,6 @@ code {
|
|||
line-height: 0.98;
|
||||
}
|
||||
|
||||
.stage-description-card__copy p {
|
||||
margin: 0;
|
||||
color: rgba(255, 255, 255, 0.72);
|
||||
font-size: 0.86rem;
|
||||
line-height: 1.48;
|
||||
}
|
||||
|
||||
.stage-rich-description {
|
||||
display: grid;
|
||||
gap: 0.75rem;
|
||||
|
|
@ -748,14 +736,14 @@ code {
|
|||
}
|
||||
|
||||
.stage-description-card__chips,
|
||||
.stage-description-card__actions {
|
||||
.stage-description-card__footer {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.stage-description-card__chips .status-badge,
|
||||
.stage-description-card__actions .button {
|
||||
.stage-description-card__footer .button {
|
||||
min-height: 2.78rem;
|
||||
border-radius: var(--launcher-radius-circle);
|
||||
padding: 0 1.22rem;
|
||||
|
|
@ -763,31 +751,29 @@ code {
|
|||
font-weight: 800;
|
||||
}
|
||||
|
||||
.stage-description-card__actions {
|
||||
align-self: flex-end;
|
||||
justify-content: flex-end;
|
||||
margin-top: auto;
|
||||
}
|
||||
|
||||
.stage-description-card__reason {
|
||||
.stage-description-card__description {
|
||||
display: grid;
|
||||
gap: 0.3rem;
|
||||
min-height: 3.85rem;
|
||||
max-height: 13rem;
|
||||
overflow-y: auto;
|
||||
padding: 0.78rem;
|
||||
border-radius: 1rem;
|
||||
background: rgba(255, 255, 255, 0.1);
|
||||
scrollbar-width: none;
|
||||
}
|
||||
|
||||
.stage-description-card__reason span {
|
||||
color: rgba(255, 255, 255, 0.48);
|
||||
font-size: 0.72rem;
|
||||
font-weight: 800;
|
||||
text-transform: uppercase;
|
||||
.stage-description-card__description::-webkit-scrollbar {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.stage-description-card__reason strong {
|
||||
color: rgba(255, 255, 255, 0.76);
|
||||
font-size: 0.86rem;
|
||||
line-height: 1.38;
|
||||
.stage-description-card__footer {
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
margin-top: auto;
|
||||
}
|
||||
|
||||
.stage-description-card__chips {
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.stage-video-controls {
|
||||
|
|
@ -971,8 +957,8 @@ code {
|
|||
}
|
||||
|
||||
.service-tile--active .service-tile__arrow {
|
||||
background: rgb(var(--nodedc-card-active-rgb));
|
||||
color: rgb(var(--nodedc-on-accent-rgb));
|
||||
background: rgba(247, 248, 244, 0.94);
|
||||
color: rgba(8, 8, 10, 0.96);
|
||||
}
|
||||
|
||||
.service-tile__media {
|
||||
|
|
@ -1045,8 +1031,8 @@ code {
|
|||
height: 2.3rem;
|
||||
place-items: center;
|
||||
border-radius: var(--launcher-radius-circle);
|
||||
background: rgba(247, 248, 244, 0.94);
|
||||
color: rgba(8, 8, 10, 0.96);
|
||||
background: rgba(64, 64, 64, 0.62);
|
||||
color: rgba(255, 255, 255, 0.88);
|
||||
transform: translateY(-50%);
|
||||
}
|
||||
|
||||
|
|
@ -1246,6 +1232,164 @@ code {
|
|||
animation: adminPanelSlide 460ms cubic-bezier(0.22, 1, 0.36, 1) both;
|
||||
}
|
||||
|
||||
.profile-settings-layer {
|
||||
position: absolute;
|
||||
z-index: 9;
|
||||
top: 0;
|
||||
right: var(--launcher-page-pad);
|
||||
bottom: calc(var(--launcher-rail-height) + var(--launcher-rail-bottom) + var(--launcher-stage-rail-gap));
|
||||
width: var(--admin-nav-width);
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
.profile-settings-panel {
|
||||
display: grid;
|
||||
height: 100%;
|
||||
grid-template-rows: auto minmax(0, 1fr) auto auto;
|
||||
gap: 1rem;
|
||||
pointer-events: auto;
|
||||
border: 0;
|
||||
border-radius: var(--launcher-radius-card);
|
||||
background:
|
||||
linear-gradient(180deg, rgba(255, 255, 255, 0.04), rgba(255, 255, 255, 0.014)),
|
||||
rgba(10, 10, 13, 0.9);
|
||||
box-shadow: 0 34px 110px rgba(0, 0, 0, 0.52);
|
||||
backdrop-filter: blur(28px);
|
||||
-webkit-backdrop-filter: blur(28px);
|
||||
padding: var(--admin-nav-pad);
|
||||
animation: profilePanelSlide 420ms cubic-bezier(0.22, 1, 0.36, 1) both;
|
||||
}
|
||||
|
||||
.profile-settings-panel__head {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
justify-content: space-between;
|
||||
gap: 1rem;
|
||||
}
|
||||
|
||||
.profile-settings-panel__head h2 {
|
||||
margin: 0.15rem 0 0;
|
||||
font-size: 1.35rem;
|
||||
}
|
||||
|
||||
.profile-settings-panel__body {
|
||||
display: grid;
|
||||
align-content: start;
|
||||
gap: 0.85rem;
|
||||
min-height: 0;
|
||||
overflow: auto;
|
||||
padding-right: 0.15rem;
|
||||
}
|
||||
|
||||
.profile-settings-avatar-card {
|
||||
display: grid;
|
||||
justify-items: center;
|
||||
gap: 0.85rem;
|
||||
border-radius: 1.25rem;
|
||||
background:
|
||||
radial-gradient(circle at 50% 0%, rgba(181, 255, 90, 0.16), transparent 42%),
|
||||
rgba(255, 255, 255, 0.045);
|
||||
padding: 1.25rem 1rem;
|
||||
}
|
||||
|
||||
.profile-settings-avatar-card__image {
|
||||
display: grid;
|
||||
width: 5.25rem;
|
||||
height: 5.25rem;
|
||||
place-items: center;
|
||||
overflow: hidden;
|
||||
border-radius: var(--launcher-radius-circle);
|
||||
background:
|
||||
radial-gradient(circle at 72% 20%, rgba(255, 255, 255, 0.72), transparent 23%),
|
||||
linear-gradient(135deg, rgb(166, 194, 109), rgb(142, 123, 139));
|
||||
color: rgba(8, 8, 10, 0.96);
|
||||
object-fit: cover;
|
||||
font-size: 1rem;
|
||||
font-weight: 850;
|
||||
}
|
||||
|
||||
.profile-settings-upload {
|
||||
display: inline-flex;
|
||||
min-height: 2.35rem;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 0.45rem;
|
||||
border-radius: 999px;
|
||||
background: rgba(255, 255, 255, 0.08);
|
||||
color: var(--text-primary);
|
||||
cursor: pointer;
|
||||
padding: 0 0.85rem;
|
||||
font-size: 0.78rem;
|
||||
font-weight: 800;
|
||||
}
|
||||
|
||||
.profile-settings-upload:hover {
|
||||
background: rgba(255, 255, 255, 0.13);
|
||||
}
|
||||
|
||||
.profile-settings-upload input {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.profile-settings-field {
|
||||
display: grid;
|
||||
gap: 0.4rem;
|
||||
}
|
||||
|
||||
.profile-settings-field span {
|
||||
color: var(--text-secondary);
|
||||
font-size: 0.74rem;
|
||||
font-weight: 800;
|
||||
letter-spacing: 0.04em;
|
||||
text-transform: uppercase;
|
||||
}
|
||||
|
||||
.profile-settings-field input {
|
||||
min-height: 2.75rem;
|
||||
border: 0;
|
||||
border-radius: 0.95rem;
|
||||
outline: 0;
|
||||
background: rgba(255, 255, 255, 0.07);
|
||||
color: var(--text-primary);
|
||||
padding: 0 0.85rem;
|
||||
font: inherit;
|
||||
}
|
||||
|
||||
.profile-settings-field input:focus {
|
||||
background: rgba(255, 255, 255, 0.1);
|
||||
box-shadow: 0 0 0 1px rgba(181, 255, 90, 0.34);
|
||||
}
|
||||
|
||||
.profile-settings-divider {
|
||||
height: 1px;
|
||||
background: rgba(255, 255, 255, 0.08);
|
||||
margin: 0.25rem 0;
|
||||
}
|
||||
|
||||
.profile-settings-message {
|
||||
margin: 0;
|
||||
color: var(--text-secondary);
|
||||
font-size: 0.78rem;
|
||||
line-height: 1.4;
|
||||
}
|
||||
|
||||
.profile-settings-panel__foot {
|
||||
display: grid;
|
||||
gap: 0.65rem;
|
||||
}
|
||||
|
||||
@keyframes profilePanelSlide {
|
||||
from {
|
||||
opacity: 0;
|
||||
transform: translateX(1.25rem);
|
||||
}
|
||||
|
||||
to {
|
||||
opacity: 1;
|
||||
transform: translateX(0);
|
||||
}
|
||||
}
|
||||
|
||||
.admin-panel-nav__head {
|
||||
display: flex;
|
||||
align-items: start;
|
||||
|
|
@ -1266,7 +1410,7 @@ code {
|
|||
width: var(--admin-control-ring);
|
||||
height: var(--admin-control-ring);
|
||||
flex: 0 0 auto;
|
||||
border: 0;
|
||||
border: 1px solid rgba(255, 255, 255, 0.22);
|
||||
outline: none;
|
||||
background: transparent !important;
|
||||
background-image: none !important;
|
||||
|
|
@ -1275,6 +1419,7 @@ code {
|
|||
}
|
||||
|
||||
.admin-panel-close:hover {
|
||||
border-color: rgba(255, 255, 255, 0.3);
|
||||
background: rgba(255, 255, 255, 0.07) !important;
|
||||
color: var(--text-primary);
|
||||
}
|
||||
|
|
@ -1665,6 +1810,11 @@ code {
|
|||
filter: grayscale(1);
|
||||
}
|
||||
|
||||
.admin-content-close {
|
||||
background: transparent !important;
|
||||
color: rgba(255, 255, 255, 0.8);
|
||||
}
|
||||
|
||||
.admin-section-grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(4, minmax(0, 1fr));
|
||||
|
|
@ -2609,8 +2759,13 @@ code {
|
|||
box-shadow: none;
|
||||
}
|
||||
|
||||
.access-cell:hover,
|
||||
.access-cell[aria-expanded="true"] {
|
||||
.access-cell--pending {
|
||||
cursor: wait;
|
||||
opacity: 0.72;
|
||||
}
|
||||
|
||||
.access-cell:not(.access-cell--pending):hover,
|
||||
.access-cell:not(.access-cell--pending)[aria-expanded="true"] {
|
||||
filter: brightness(1.12);
|
||||
}
|
||||
|
||||
|
|
@ -3114,6 +3269,11 @@ code {
|
|||
width: min(62rem, calc(100% - 5rem));
|
||||
gap: 0.8rem;
|
||||
}
|
||||
|
||||
.stage-empty-title {
|
||||
top: 3.84rem;
|
||||
left: 3.84rem;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 760px) {
|
||||
|
|
@ -3179,7 +3339,11 @@ code {
|
|||
transform: translate(-50%, -50%);
|
||||
}
|
||||
|
||||
.stage-side-controls,
|
||||
.stage-empty-title {
|
||||
top: 2.05rem;
|
||||
left: 2.05rem;
|
||||
}
|
||||
|
||||
.stage-timeline-strip {
|
||||
display: none;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -89,6 +89,16 @@ export interface SetUserServiceAccessCommand {
|
|||
value: AccessAssignmentValue;
|
||||
}
|
||||
|
||||
export interface CreateUserCommand {
|
||||
clientId: string;
|
||||
email: string;
|
||||
name?: string;
|
||||
role: ClientMembershipRole;
|
||||
groupIds: string[];
|
||||
provisionAuth: boolean;
|
||||
generatePassword: boolean;
|
||||
}
|
||||
|
||||
const rootSections: Array<{ id: AdminSection; label: string; icon: React.ReactNode }> = [
|
||||
{ id: "overview", label: "Обзор", icon: <LayoutDashboard size={16} /> },
|
||||
{ id: "clients", label: "Клиенты", icon: <Building2 size={16} /> },
|
||||
|
|
@ -124,9 +134,11 @@ export function AdminOverlay({
|
|||
onCreateClient,
|
||||
onUpdateClient,
|
||||
onDeleteClient,
|
||||
onCreateUser,
|
||||
onUpdateUser,
|
||||
onUpdateMembership,
|
||||
onDeleteMembership,
|
||||
pendingAccessAssignments,
|
||||
onCreateGroup,
|
||||
onUpdateGroup,
|
||||
onDeleteGroup,
|
||||
|
|
@ -147,9 +159,11 @@ export function AdminOverlay({
|
|||
onCreateClient: () => void;
|
||||
onUpdateClient: (clientId: string, patch: Partial<Client>) => void;
|
||||
onDeleteClient: (clientId: string) => void;
|
||||
onCreateUser: (command: CreateUserCommand) => void;
|
||||
onUpdateUser: (userId: string, patch: Partial<LauncherUser>) => void;
|
||||
onUpdateMembership: (membershipId: string, patch: Partial<ClientMembership>) => void;
|
||||
onDeleteMembership: (membershipId: string) => void;
|
||||
pendingAccessAssignments: Record<string, AccessAssignmentValue>;
|
||||
onCreateGroup: (clientId: string) => void;
|
||||
onUpdateGroup: (groupId: string, patch: Partial<ClientGroup>) => void;
|
||||
onDeleteGroup: (groupId: string) => void;
|
||||
|
|
@ -264,7 +278,7 @@ export function AdminOverlay({
|
|||
|
||||
{activeSection ? (
|
||||
<section className="admin-panel-content">
|
||||
<AdminHeader />
|
||||
<AdminHeader onCloseContent={() => setActiveSection(null)} />
|
||||
<div className="admin-panel-content__body">
|
||||
{activeSection === "overview" ? <OverviewSection data={data} clientId={scopedClientId} isRoot={isRoot} /> : null}
|
||||
{activeSection === "clients" && isRoot ? (
|
||||
|
|
@ -275,6 +289,7 @@ export function AdminOverlay({
|
|||
data={data}
|
||||
clientId={scopedClientId}
|
||||
isRoot={isRoot}
|
||||
onCreateUser={onCreateUser}
|
||||
onUpdateUser={onUpdateUser}
|
||||
onUpdateMembership={onUpdateMembership}
|
||||
onDeleteMembership={onDeleteMembership}
|
||||
|
|
@ -305,6 +320,7 @@ export function AdminOverlay({
|
|||
selectedCell={selectedAccessCell}
|
||||
onSelectCell={(cell) => setSelectedCell({ userId: cell.userId, serviceId: cell.serviceId })}
|
||||
onSetUserServiceAccess={onSetUserServiceAccess}
|
||||
pendingAccessAssignments={pendingAccessAssignments}
|
||||
/>
|
||||
) : null}
|
||||
{activeSection === "invites" ? (
|
||||
|
|
@ -327,7 +343,7 @@ export function AdminOverlay({
|
|||
);
|
||||
}
|
||||
|
||||
function AdminHeader() {
|
||||
function AdminHeader({ onCloseContent }: { onCloseContent: () => void }) {
|
||||
return (
|
||||
<div className="admin-header">
|
||||
<div className="admin-header__actions">
|
||||
|
|
@ -337,6 +353,9 @@ function AdminHeader() {
|
|||
<IconButton label="Синхронизация" className="admin-circle-action admin-circle-action--solid" type="button">
|
||||
<RefreshCw size={16} />
|
||||
</IconButton>
|
||||
<IconButton label="Закрыть панель раздела" className="admin-circle-action admin-content-close" type="button" onClick={onCloseContent}>
|
||||
<X size={15} strokeWidth={1.45} />
|
||||
</IconButton>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
|
@ -496,6 +515,7 @@ function UsersSection({
|
|||
data,
|
||||
clientId,
|
||||
isRoot,
|
||||
onCreateUser,
|
||||
onUpdateUser,
|
||||
onUpdateMembership,
|
||||
onDeleteMembership,
|
||||
|
|
@ -503,26 +523,93 @@ function UsersSection({
|
|||
data: LauncherData;
|
||||
clientId: string;
|
||||
isRoot: boolean;
|
||||
onCreateUser: (command: CreateUserCommand) => void;
|
||||
onUpdateUser: (userId: string, patch: Partial<LauncherUser>) => void;
|
||||
onUpdateMembership: (membershipId: string, patch: Partial<ClientMembership>) => void;
|
||||
onDeleteMembership: (membershipId: string) => void;
|
||||
}) {
|
||||
const [editingMembershipId, setEditingMembershipId] = useState<string | null>(null);
|
||||
const [newUserEmail, setNewUserEmail] = useState("");
|
||||
const [newUserName, setNewUserName] = useState("");
|
||||
const [newUserRole, setNewUserRole] = useState<ClientMembershipRole>("member");
|
||||
const [newUserGroupId, setNewUserGroupId] = useState<string>("none");
|
||||
const rows = isRoot
|
||||
? data.memberships.map((membership) => ({ membership, user: getUser(data, membership.userId), client: getClient(data, membership.clientId) }))
|
||||
: data.memberships
|
||||
.filter((membership) => membership.clientId === clientId)
|
||||
.map((membership) => ({ membership, user: getUser(data, membership.userId), client: getClient(data, membership.clientId) }));
|
||||
const editingRow = rows.find((row) => row.membership.id === editingMembershipId) ?? null;
|
||||
const clientGroups = data.groups.filter((group) => group.clientId === clientId);
|
||||
const groupOptions: Array<NodeDcSelectOption<string>> = [
|
||||
{ value: "none", label: "Без группы" },
|
||||
...clientGroups.map((group) => ({ value: group.id, label: group.name })),
|
||||
];
|
||||
|
||||
function handleCreateUser() {
|
||||
const email = newUserEmail.trim();
|
||||
|
||||
if (!email) {
|
||||
return;
|
||||
}
|
||||
|
||||
onCreateUser({
|
||||
clientId,
|
||||
email,
|
||||
name: newUserName.trim() || undefined,
|
||||
role: newUserRole,
|
||||
groupIds: newUserGroupId === "none" ? [] : [newUserGroupId],
|
||||
provisionAuth: true,
|
||||
generatePassword: true,
|
||||
});
|
||||
setNewUserEmail("");
|
||||
setNewUserName("");
|
||||
setNewUserRole("member");
|
||||
setNewUserGroupId("none");
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<GlassSurface className="invite-form invite-form--compact">
|
||||
<div className="table-toolbar">
|
||||
<div>
|
||||
<p className="eyebrow">Launcher → Authentik</p>
|
||||
<h3>Создать участника</h3>
|
||||
</div>
|
||||
<IconButton
|
||||
label="Создать участника"
|
||||
className="admin-circle-action admin-circle-action--solid"
|
||||
type="button"
|
||||
disabled={!newUserEmail.trim()}
|
||||
onClick={handleCreateUser}
|
||||
>
|
||||
<Plus size={17} />
|
||||
</IconButton>
|
||||
</div>
|
||||
<div className="invite-form__fields">
|
||||
<input value={newUserEmail} onChange={(event) => setNewUserEmail(event.target.value)} placeholder="email@company.ru" />
|
||||
<input value={newUserName} onChange={(event) => setNewUserName(event.target.value)} placeholder="Имя пользователя" />
|
||||
<NodeDcSelect
|
||||
className="admin-table-select-wrap"
|
||||
triggerClassName="admin-modal-select-trigger"
|
||||
value={newUserRole}
|
||||
options={membershipRoleOptions}
|
||||
label="Роль"
|
||||
onChange={(role) => setNewUserRole(role)}
|
||||
/>
|
||||
<NodeDcSelect
|
||||
className="admin-table-select-wrap"
|
||||
triggerClassName="admin-modal-select-trigger"
|
||||
value={newUserGroupId}
|
||||
options={groupOptions}
|
||||
label="Группа"
|
||||
onChange={(groupId) => setNewUserGroupId(groupId)}
|
||||
/>
|
||||
</div>
|
||||
</GlassSurface>
|
||||
|
||||
<GlassSurface className="table-shell">
|
||||
<div className="table-toolbar">
|
||||
<h3>Участники</h3>
|
||||
<IconButton label="Создать инвайт" className="admin-circle-action admin-circle-action--solid" type="button">
|
||||
<MailPlus size={16} />
|
||||
</IconButton>
|
||||
</div>
|
||||
<table className="admin-data-table">
|
||||
<thead>
|
||||
|
|
@ -1823,12 +1910,14 @@ function AccessSection({
|
|||
selectedCell,
|
||||
onSelectCell,
|
||||
onSetUserServiceAccess,
|
||||
pendingAccessAssignments,
|
||||
}: {
|
||||
data: LauncherData;
|
||||
matrix: ReturnType<typeof buildAccessMatrix>;
|
||||
selectedCell: AccessMatrixCell | null;
|
||||
onSelectCell: (cell: AccessMatrixCell) => void;
|
||||
onSetUserServiceAccess: (command: SetUserServiceAccessCommand) => void;
|
||||
pendingAccessAssignments: Record<string, AccessAssignmentValue>;
|
||||
}) {
|
||||
const hasMatrixData = matrix.users.length > 0 && matrix.services.length > 0 && selectedCell !== null;
|
||||
|
||||
|
|
@ -1893,6 +1982,7 @@ function AccessSection({
|
|||
<AccessCellControl
|
||||
cell={cell}
|
||||
active={active}
|
||||
pendingValue={pendingAccessAssignments[accessCellKey(user.id, service.id)]}
|
||||
onSelectCell={onSelectCell}
|
||||
onSetAccess={(value) => onSetUserServiceAccess({ userId: user.id, serviceId: service.id, value })}
|
||||
/>
|
||||
|
|
@ -1926,15 +2016,18 @@ function AccessSection({
|
|||
function AccessCellControl({
|
||||
cell,
|
||||
active,
|
||||
pendingValue,
|
||||
onSelectCell,
|
||||
onSetAccess,
|
||||
}: {
|
||||
cell: AccessMatrixCell;
|
||||
active: boolean;
|
||||
pendingValue?: AccessAssignmentValue;
|
||||
onSelectCell: (cell: AccessMatrixCell) => void;
|
||||
onSetAccess: (value: AccessAssignmentValue) => void;
|
||||
}) {
|
||||
const assignmentValue = accessAssignmentValue(cell);
|
||||
const isPending = pendingValue !== undefined;
|
||||
const assignmentValue = pendingValue ?? accessAssignmentValue(cell);
|
||||
|
||||
return (
|
||||
<NodeDcSelect
|
||||
|
|
@ -1943,6 +2036,7 @@ function AccessCellControl({
|
|||
label={`Назначить доступ ${cell.userId} / ${cell.serviceId}`}
|
||||
minMenuWidth={172}
|
||||
menuClassName="access-cell-menu"
|
||||
disabled={isPending}
|
||||
onChange={(value) => onSetAccess(value)}
|
||||
trigger={({ open, toggle, setTriggerRef }) => (
|
||||
<button
|
||||
|
|
@ -1952,17 +2046,19 @@ function AccessCellControl({
|
|||
cell.effectiveAccess.allowed && "access-cell--allowed",
|
||||
!cell.effectiveAccess.allowed && "access-cell--denied",
|
||||
cell.effectiveAccess.source === "exception" && "access-cell--exception",
|
||||
isPending && "access-cell--pending",
|
||||
active && "access-cell--active"
|
||||
)}
|
||||
type="button"
|
||||
aria-expanded={open}
|
||||
aria-busy={isPending}
|
||||
onClick={() => {
|
||||
onSelectCell(cell);
|
||||
toggle();
|
||||
}}
|
||||
>
|
||||
<strong>{accessCellTitle(cell)}</strong>
|
||||
<span>{sourceLabel(cell.effectiveAccess.source)}</span>
|
||||
<strong>{isPending ? accessAssignmentLabel(assignmentValue) : accessCellTitle(cell)}</strong>
|
||||
<span>{isPending ? "Сохраняем..." : sourceLabel(cell.effectiveAccess.source)}</span>
|
||||
</button>
|
||||
)}
|
||||
/>
|
||||
|
|
@ -2308,6 +2404,14 @@ function accessAssignmentValue(cell: AccessMatrixCell): AccessAssignmentValue {
|
|||
return "unset";
|
||||
}
|
||||
|
||||
function accessAssignmentLabel(value: AccessAssignmentValue): string {
|
||||
return accessAssignmentOptions.find((option) => option.value === value)?.label ?? value;
|
||||
}
|
||||
|
||||
function accessCellKey(userId: string, serviceId: string): string {
|
||||
return `${userId}:${serviceId}`;
|
||||
}
|
||||
|
||||
function sourceLabel(source?: AccessMatrixCell["effectiveAccess"]["source"]): string {
|
||||
if (!source) return "—";
|
||||
const labels = {
|
||||
|
|
|
|||
|
|
@ -0,0 +1,186 @@
|
|||
import { useEffect, useState } from "react";
|
||||
import { KeyRound, Save, Upload, X } from "lucide-react";
|
||||
import type { LauncherUser } from "../../entities/user/types";
|
||||
import { uploadStorageFile } from "../../shared/api/storageApi";
|
||||
import { initials } from "../../shared/lib/format";
|
||||
import { Button, IconButton } from "../../shared/ui/Button";
|
||||
|
||||
export function ProfileSettingsPanel({
|
||||
user,
|
||||
onClose,
|
||||
onSaveProfile,
|
||||
onChangePassword,
|
||||
}: {
|
||||
user: LauncherUser;
|
||||
onClose: () => void;
|
||||
onSaveProfile: (patch: Partial<LauncherUser>) => Promise<void>;
|
||||
onChangePassword: (newPassword: string) => Promise<void>;
|
||||
}) {
|
||||
const [draft, setDraft] = useState<LauncherUser>(user);
|
||||
const [newPassword, setNewPassword] = useState("");
|
||||
const [uploading, setUploading] = useState(false);
|
||||
const [savingProfile, setSavingProfile] = useState(false);
|
||||
const [savingPassword, setSavingPassword] = useState(false);
|
||||
const [message, setMessage] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => setDraft(user), [user]);
|
||||
|
||||
useEffect(() => {
|
||||
const handleKeyDown = (event: KeyboardEvent) => {
|
||||
if (event.key === "Escape") onClose();
|
||||
};
|
||||
|
||||
window.addEventListener("keydown", handleKeyDown);
|
||||
return () => window.removeEventListener("keydown", handleKeyDown);
|
||||
}, [onClose]);
|
||||
|
||||
function update<K extends keyof LauncherUser>(key: K, value: LauncherUser[K]) {
|
||||
setDraft((current) => ({ ...current, [key]: value }));
|
||||
}
|
||||
|
||||
async function handleAvatarUpload(file: File | undefined) {
|
||||
if (!file) return;
|
||||
|
||||
setUploading(true);
|
||||
setMessage(null);
|
||||
|
||||
try {
|
||||
const result = await uploadStorageFile(file);
|
||||
update("avatarUrl", result.url);
|
||||
} catch (error) {
|
||||
setMessage(error instanceof Error ? error.message : "Не удалось загрузить аватар");
|
||||
} finally {
|
||||
setUploading(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function handleSaveProfile() {
|
||||
setSavingProfile(true);
|
||||
setMessage(null);
|
||||
|
||||
try {
|
||||
await onSaveProfile({
|
||||
name: draft.name,
|
||||
email: draft.email,
|
||||
phone: draft.phone ?? null,
|
||||
position: draft.position ?? null,
|
||||
avatarUrl: draft.avatarUrl ?? null,
|
||||
});
|
||||
setMessage("Профиль сохранён");
|
||||
} catch (error) {
|
||||
setMessage(error instanceof Error ? error.message : "Не удалось сохранить профиль");
|
||||
} finally {
|
||||
setSavingProfile(false);
|
||||
}
|
||||
}
|
||||
|
||||
async function handleSavePassword() {
|
||||
if (newPassword.length < 8) {
|
||||
setMessage("Пароль должен быть не короче 8 символов");
|
||||
return;
|
||||
}
|
||||
|
||||
setSavingPassword(true);
|
||||
setMessage(null);
|
||||
|
||||
try {
|
||||
await onChangePassword(newPassword);
|
||||
setNewPassword("");
|
||||
setMessage("Пароль обновлён");
|
||||
} catch (error) {
|
||||
setMessage(error instanceof Error ? error.message : "Не удалось обновить пароль");
|
||||
} finally {
|
||||
setSavingPassword(false);
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<aside className="profile-settings-layer" aria-label="Настройки профиля">
|
||||
<section className="profile-settings-panel">
|
||||
<div className="profile-settings-panel__head">
|
||||
<div>
|
||||
<p className="eyebrow">Профиль</p>
|
||||
<h2>Настройки</h2>
|
||||
</div>
|
||||
<IconButton label="Закрыть настройки" className="admin-panel-close" type="button" onClick={onClose}>
|
||||
<X size={15} strokeWidth={1.45} />
|
||||
</IconButton>
|
||||
</div>
|
||||
|
||||
<div className="profile-settings-panel__body">
|
||||
<div className="profile-settings-avatar-card">
|
||||
{draft.avatarUrl ? (
|
||||
<img className="profile-settings-avatar-card__image" src={draft.avatarUrl} alt="" />
|
||||
) : (
|
||||
<span className="profile-settings-avatar-card__image">{initials(draft.name)}</span>
|
||||
)}
|
||||
<label className="profile-settings-upload">
|
||||
<Upload size={15} />
|
||||
<span>{uploading ? "Загружаем" : "Загрузить аватар"}</span>
|
||||
<input
|
||||
type="file"
|
||||
accept="image/png,image/jpeg,image/webp,image/gif"
|
||||
disabled={uploading}
|
||||
onChange={(event) => void handleAvatarUpload(event.target.files?.[0])}
|
||||
/>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<label className="profile-settings-field">
|
||||
<span>Имя</span>
|
||||
<input value={draft.name} onChange={(event) => update("name", event.target.value)} />
|
||||
</label>
|
||||
<label className="profile-settings-field">
|
||||
<span>Email</span>
|
||||
<input value={draft.email} onChange={(event) => update("email", event.target.value)} />
|
||||
</label>
|
||||
<label className="profile-settings-field">
|
||||
<span>Телефон</span>
|
||||
<input value={draft.phone ?? ""} onChange={(event) => update("phone", event.target.value || null)} />
|
||||
</label>
|
||||
<label className="profile-settings-field">
|
||||
<span>Должность</span>
|
||||
<input value={draft.position ?? ""} onChange={(event) => update("position", event.target.value || null)} />
|
||||
</label>
|
||||
|
||||
<div className="profile-settings-divider" />
|
||||
|
||||
<label className="profile-settings-field">
|
||||
<span>Новый пароль</span>
|
||||
<input
|
||||
value={newPassword}
|
||||
type="password"
|
||||
placeholder="Минимум 8 символов"
|
||||
onChange={(event) => setNewPassword(event.target.value)}
|
||||
/>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
{message ? <p className="profile-settings-message">{message}</p> : null}
|
||||
|
||||
<div className="profile-settings-panel__foot">
|
||||
<Button
|
||||
variant="secondary"
|
||||
surface="modal"
|
||||
type="button"
|
||||
icon={<KeyRound size={16} />}
|
||||
disabled={savingPassword || !newPassword}
|
||||
onClick={() => void handleSavePassword()}
|
||||
>
|
||||
{savingPassword ? "Обновляем" : "Сменить пароль"}
|
||||
</Button>
|
||||
<Button
|
||||
variant="accent"
|
||||
surface="modal"
|
||||
type="button"
|
||||
icon={<Save size={16} />}
|
||||
disabled={savingProfile || uploading}
|
||||
onClick={() => void handleSaveProfile()}
|
||||
>
|
||||
{savingProfile ? "Сохраняем" : "Сохранить"}
|
||||
</Button>
|
||||
</div>
|
||||
</section>
|
||||
</aside>
|
||||
);
|
||||
}
|
||||
|
|
@ -17,6 +17,8 @@ import type { LauncherServiceView } from "../../entities/service/types";
|
|||
import { Button } from "../../shared/ui/Button";
|
||||
import { ServiceStatusBadge, StatusBadge } from "../../shared/ui/StatusBadge";
|
||||
|
||||
const stageActionAccentRgb = [247, 248, 244] as const;
|
||||
|
||||
export function ServiceStage({
|
||||
service,
|
||||
hasServices,
|
||||
|
|
@ -50,7 +52,7 @@ export function ServiceStage({
|
|||
? service.status === "maintenance"
|
||||
? "Сервис временно недоступен"
|
||||
: service.userAccess === "denied"
|
||||
? "Доступ не выдан"
|
||||
? "Нет доступа"
|
||||
: service.effectiveAccess.openEnabled
|
||||
? null
|
||||
: "Открытие заблокировано"
|
||||
|
|
@ -63,20 +65,6 @@ export function ServiceStage({
|
|||
<StageMedia className="stage-video-gif" src={ambientMedia.src} kind={ambientMedia.kind} />
|
||||
</div>
|
||||
|
||||
<div className="stage-video-topline">
|
||||
<button className="stage-round-button" type="button" aria-label="Назад">
|
||||
<ChevronLeft size={17} />
|
||||
</button>
|
||||
<span>{service?.title ?? "Витрина NODE.DC"}</span>
|
||||
</div>
|
||||
|
||||
<div className="stage-side-controls" aria-hidden="true">
|
||||
<span />
|
||||
<span />
|
||||
<span />
|
||||
<span />
|
||||
</div>
|
||||
|
||||
{service ? (
|
||||
<div className="stage-service-overlay">
|
||||
<article className="stage-image-card">
|
||||
|
|
@ -104,26 +92,24 @@ export function ServiceStage({
|
|||
|
||||
<div className="stage-description-card__copy">
|
||||
<h1>{service.title}</h1>
|
||||
</div>
|
||||
|
||||
<div className="stage-description-card__description">
|
||||
<RichDescription text={service.fullDescription ?? service.description} />
|
||||
</div>
|
||||
|
||||
<div className="stage-description-card__chips">
|
||||
<ServiceStatusBadge status={service.status} />
|
||||
<StatusBadge
|
||||
label={service.userAccess === "allowed" ? `Доступ: ${service.appRole ?? "member"}` : "Нет доступа"}
|
||||
tone={service.userAccess === "allowed" ? "green" : "red"}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className="stage-description-card__reason">
|
||||
<span>Почему видно</span>
|
||||
<strong>{service.effectiveAccess.reason}</strong>
|
||||
</div>
|
||||
|
||||
<div className="stage-description-card__actions">
|
||||
<div className="stage-description-card__footer">
|
||||
<div className="stage-description-card__chips">
|
||||
<ServiceStatusBadge status={service.status} />
|
||||
<StatusBadge
|
||||
label={service.userAccess === "allowed" ? `Доступ: ${service.appRole ?? "member"}` : "Нет доступа"}
|
||||
tone={service.userAccess === "allowed" ? "green" : "muted"}
|
||||
/>
|
||||
</div>
|
||||
<Button
|
||||
type="button"
|
||||
variant="primary"
|
||||
variant="accent"
|
||||
accentRgb={stageActionAccentRgb}
|
||||
icon={
|
||||
service.status === "maintenance" ? (
|
||||
<Wrench size={16} />
|
||||
|
|
@ -138,19 +124,15 @@ export function ServiceStage({
|
|||
>
|
||||
{disabledReason ?? "Открыть"}
|
||||
</Button>
|
||||
<Button
|
||||
type="button"
|
||||
variant="secondary"
|
||||
icon={<ChevronRight size={16} />}
|
||||
onClick={() => onLaunch(service)}
|
||||
disabled={!service.effectiveAccess.openEnabled || !service.openUrl}
|
||||
>
|
||||
Перейти
|
||||
</Button>
|
||||
</div>
|
||||
</aside>
|
||||
</div>
|
||||
) : null}
|
||||
) : (
|
||||
<div className="stage-empty-title" aria-label="NodeDC витрина модулей">
|
||||
<span>NODE.DC</span>
|
||||
<strong>Витрина модулей</strong>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="stage-video-controls">
|
||||
<button type="button" aria-label="Предыдущий сервис" onClick={onSelectPrevious}>
|
||||
|
|
|
|||
|
|
@ -15,6 +15,7 @@ export function TopBar({
|
|||
onClientChange,
|
||||
onToggleAdmin,
|
||||
onOpenShowcase,
|
||||
onOpenProfileSettings,
|
||||
onLogout,
|
||||
}: {
|
||||
me: MeResponse;
|
||||
|
|
@ -27,6 +28,7 @@ export function TopBar({
|
|||
onClientChange: (clientId: string) => void;
|
||||
onToggleAdmin: () => void;
|
||||
onOpenShowcase: () => void;
|
||||
onOpenProfileSettings: () => void;
|
||||
onLogout?: () => void;
|
||||
}) {
|
||||
const availableClientIds = new Set(me.memberships.map((membership) => membership.clientId));
|
||||
|
|
@ -114,6 +116,7 @@ export function TopBar({
|
|||
<div className="nodedc-expanded-toolbar-right">
|
||||
<NodeDcProfileMenu
|
||||
user={me.user}
|
||||
onSettings={onOpenProfileSettings}
|
||||
onLogout={onLogout}
|
||||
trigger={({ open, toggle, setTriggerRef }) => (
|
||||
<div
|
||||
|
|
@ -141,7 +144,11 @@ export function TopBar({
|
|||
</span>
|
||||
</span>
|
||||
<span className="nodedc-expanded-user-avatar-button" aria-hidden="true">
|
||||
<span className="nodedc-expanded-user-avatar">{initials(me.user.name)}</span>
|
||||
{me.user.avatarUrl ? (
|
||||
<img className="nodedc-expanded-user-avatar" src={me.user.avatarUrl} alt="" style={{ objectFit: "cover" }} />
|
||||
) : (
|
||||
<span className="nodedc-expanded-user-avatar">{initials(me.user.name)}</span>
|
||||
)}
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
|
|
|
|||
Loading…
Reference in New Issue