627 lines
39 KiB
JavaScript
627 lines
39 KiB
JavaScript
import {
|
|
identityStates,
|
|
applicationCatalog,
|
|
systemRoles,
|
|
} from "../patterns/demo-identity.js";
|
|
export const accountPageIds = [
|
|
"profile",
|
|
"security",
|
|
"sessions",
|
|
"applications",
|
|
"appearance",
|
|
"identity",
|
|
];
|
|
export function createAccountUI({
|
|
adapter,
|
|
t,
|
|
escape: e,
|
|
heading,
|
|
icon,
|
|
openDialog,
|
|
toast,
|
|
render,
|
|
navigate,
|
|
setTheme,
|
|
}) {
|
|
const $ = (s) => document.querySelector(s),
|
|
snap = () => adapter.snapshot();
|
|
let pendingEnrollment = false;
|
|
let avatarDraft = null,
|
|
avatarPreview = null,
|
|
selectedGrants = new Set(),
|
|
editingUser = null;
|
|
const title = {
|
|
profile: t("Аккаунт", "Account"),
|
|
security: t("Безопасность", "Security"),
|
|
sessions: t("Устройства и сеансы", "Devices and sessions"),
|
|
applications: t("Приложения", "Applications"),
|
|
appearance: t("Оформление", "Appearance"),
|
|
identity: t("Состояния входа", "Sign-in states"),
|
|
};
|
|
const demo = `<p class="identity-demo">${t("Демонстрация Anidev Identity · действия не обращаются к SSO", "Anidev Identity demo · actions do not contact SSO")}</p>`;
|
|
const names = (a) => `${a.firstName} ${a.lastName}`;
|
|
const avatar = (a, cls = "") =>
|
|
a.avatar
|
|
? `<img class="identity-avatar ${cls}" src="${e(a.avatar)}" alt="${e(names(a))}">`
|
|
: `<span class="identity-avatar ${cls}" aria-hidden="true">${e(a.firstName[0] || "")}${e(a.lastName[0] || "")}</span>`;
|
|
const action = (id, ru, en, cls = "") =>
|
|
`<button class="${cls}" data-identity="${id}">${t(ru, en)}</button>`;
|
|
const stateLabels = {
|
|
authenticated: t("Вход выполнен", "Signed in"),
|
|
loading: t("Проверяем сеанс", "Checking session"),
|
|
signed_out: t("Вы вышли из аккаунта", "You are signed out"),
|
|
access_denied: t("Нет доступа к приложению", "Application access denied"),
|
|
factor_required: t("Подтвердите вход", "Verify your sign-in"),
|
|
factor_enrollment_required: t(
|
|
"Подключите способ подтверждения",
|
|
"Set up a verification method",
|
|
),
|
|
rebind_required: t("Восстановите подключение", "Reconnect your session"),
|
|
unavailable: t("Сервис входа недоступен", "Identity service unavailable"),
|
|
account_changed: t("Аккаунт изменился", "Account changed"),
|
|
signing_out: t("Завершаем сеанс", "Signing out"),
|
|
};
|
|
const stateDescriptions = {
|
|
loading: t(
|
|
"Пока личность не проверена, данные аккаунта скрыты.",
|
|
"Account data stays hidden until identity is verified.",
|
|
),
|
|
signed_out: t(
|
|
"Войдите, чтобы продолжить работу. Другие устройства сохраняют свои сеансы.",
|
|
"Sign in to continue. Other devices retain their sessions.",
|
|
),
|
|
access_denied: t(
|
|
"Текущему аккаунту не выдан доступ. Обратитесь к администратору или смените аккаунт.",
|
|
"This account has not been granted access. Contact an administrator or switch account.",
|
|
),
|
|
factor_required: t(
|
|
"Приложению требуется свежий код TOTP. Пароль повторно не запрашивается.",
|
|
"This application requires a fresh TOTP code. Your password is not requested again.",
|
|
),
|
|
factor_enrollment_required: t(
|
|
"Для продолжения нужно зарегистрировать способ подтверждения в SSO.",
|
|
"Register a verification method in SSO to continue.",
|
|
),
|
|
rebind_required: t(
|
|
"Повторно подключите приложение через SSO, используя действующий вход.",
|
|
"Reconnect the application through SSO using your existing sign-in.",
|
|
),
|
|
unavailable: t(
|
|
"Защищённые данные скрыты. Проверьте соединение и повторите попытку.",
|
|
"Protected data is hidden. Check your connection and try again.",
|
|
),
|
|
account_changed: t(
|
|
"Прежнее содержимое очищено. Подтвердите загрузку текущего аккаунта.",
|
|
"Previous content has been cleared. Continue to load the current account.",
|
|
),
|
|
signing_out: t(
|
|
"Данные скрыты, повторное действие недоступно.",
|
|
"Data is hidden and repeat actions are disabled.",
|
|
),
|
|
};
|
|
function gate(status = snap().status) {
|
|
return `<section class="identity-gate" aria-live="polite"><span class="identity-gate-symbol" aria-hidden="true">${icon(["factor_required", "factor_enrollment_required"].includes(status) ? "security" : "profile")}</span><h1>${stateLabels[status] || stateLabels.signed_out}</h1><p>${stateDescriptions[status] || ""}</p>${["loading", "signing_out"].includes(status) ? `<div class="skeleton" aria-busy="true" aria-label="${t("Ожидание", "Waiting")}"></div>` : `<div class="component-row">${status === "factor_required" ? action("verify-factor", "Подтвердить TOTP", "Verify TOTP", "primary") : status === "factor_enrollment_required" ? action("enroll-factor", "Подключить в SSO", "Set up in SSO", "primary") : status === "signed_out" ? action("begin-signin", "Войти", "Sign in", "primary") : status === "access_denied" ? action("switch", "Сменить аккаунт", "Switch account", "primary") : action("resolve", "Повторить проверку", "Check again", "primary")}${status !== "signed_out" ? action("logout", "Выйти из SSO", "Sign out of SSO") : ""}</div>`}${demo}</section>`;
|
|
}
|
|
function renderPage(page) {
|
|
if (page === "identity") return stateLab();
|
|
if (snap().status !== "authenticated") return gate();
|
|
const a = snap().account;
|
|
return {
|
|
profile: profile,
|
|
security: security,
|
|
sessions: sessions,
|
|
applications: applications,
|
|
appearance: appearance,
|
|
}[page](a);
|
|
}
|
|
function profile(a) {
|
|
return `${heading(title.profile, t("Личные данные и ваш профиль в экосистеме Anidev.", "Your profile across the Anidev ecosystem."))}<div class="page-body identity-body"><div class="identity-profile-summary">${avatar(a, "large")}<div><h2>${e(names(a))}</h2><p>@${e(a.username)}</p><div class="identity-roles">${a.roles.map((r) => `<span>${e(r)}</span>`).join("")}</div></div></div><div class="identity-split"><section><h2>${t("Личные данные", "Personal information")}</h2><p class="muted">${t("Имя и username можно изменить. Идентификатор аккаунта остаётся прежним.", "Your name and username may change. Your account ID stays the same.")}</p></section><form id="identity-profile"><div class="identity-fields"><label class="field">${t("Имя", "First name")}<input name="firstName" required maxlength="50" autocomplete="given-name" value="${e(a.firstName)}"></label><label class="field">${t("Фамилия", "Last name")}<input name="lastName" required maxlength="50" autocomplete="family-name" value="${e(a.lastName)}"></label></div><label class="field">Username<input name="username" required pattern="[a-zA-Z0-9._-]+" maxlength="40" autocomplete="username" value="${e(a.username)}"></label><div class="identity-readonly"><span>Email</span><strong>${a.email ? e(a.email) : t("Не добавлен", "Not added")}</strong>${a.emailVerified ? `<span class="status">${t("Подтверждён", "Verified")}</span>` : action("add-email", "Добавить и подтвердить", "Add and verify")}</div><small>${t("Для изменения подтверждённой почты обратитесь к администратору.", "Contact your administrator to change a verified email address.")}</small><div class="identity-avatar-editor"><div id="avatar-preview">${avatar(a)}</div><div><label class="file-button">${t("Выбрать фотографию", "Choose photo")}<input id="identity-avatar-file" type="file" accept="image/png,image/jpeg,image/webp"></label><small>PNG, JPEG, WebP · ${t("до 2 МБ", "up to 2 MB")}</small>${action("clear-avatar", "Убрать фото", "Remove photo")}</div></div><p id="profile-error" class="error-text" role="alert"></p><div class="form-footer"><button type="reset">${t("Отмена", "Cancel")}</button><button class="primary" type="submit">${t("Сохранить профиль", "Save profile")}</button></div></form></div><div class="identity-footnote"><span>Account ID</span><code>${e(a.sub)}</code></div>${demo}</div>`;
|
|
}
|
|
function security(a) {
|
|
return `${heading(title.security, t("Способы входа и подтверждение важных действий.", "Sign-in methods and verification for important changes."))}<div class="page-body identity-body"><section class="identity-section"><h2>${t("Способы входа", "Sign-in methods")}</h2><div class="identity-setting-row"><div><h3>${t("Пароль", "Password")}</h3><p>${t("Последнее изменение: ", "Last changed: ")}${a.passwordChanged ? new Intl.DateTimeFormat(t("ru-RU", "en-US"), { dateStyle: "long" }).format(new Date(a.passwordChanged + "T12:00:00Z")) : t("нет данных", "no data")}</p></div>${action("password-link", "Сменить", "Change")}</div><div class="identity-setting-row"><div><h3>TOTP</h3><p class="status ${a.totp ? "" : "warn"}">${a.totp ? t("Подключён", "Enabled") : t("Не подключён", "Not enabled")}</p><small>${t("Сброс подтверждается ссылкой из письма.", "Reset is verified using an email link.")}</small></div>${action(a.totp ? "totp-link" : "enroll-factor", a.totp ? "Сменить" : "Подключить", a.totp ? "Change" : "Set up")}</div></section><section class="identity-section"><div class="section-title"><div><h2>Passkey</h2><p class="muted">${t("Встроенный способ входа: Windows Hello или Touch ID.", "Platform sign-in with Windows Hello or Touch ID.")}</p></div>${action("add-passkey", "Добавить", "Add")}</div>${a.passkeys.length ? a.passkeys.map((k) => `<div class="identity-setting-row"><div><h3>${e(k.name)}</h3><p>${t("Добавлен", "Added")} ${k.created}</p></div><button class="danger" data-identity="remove-passkey" data-key="${e(k.id)}">${t("Удалить", "Remove")}</button></div>`).join("") : `<div class="empty-state"><h3>${t("Passkey ещё не добавлен", "No passkey added yet")}</h3><p>${t("Добавьте ключ, чтобы входить с помощью устройства.", "Add a key to sign in with your device.")}</p></div>`}</section><section class="identity-section identity-security-note"><h2>${t("Как работают проверки", "How verification works")}</h2><p>${t("Приложение запрашивает только недостающий фактор. Возможность заменить TOTP свежим Passkey задаёт администратор приложения. Для администрирования SSO требуется отдельный TOTP.", "Applications request only the missing factor. An application administrator decides whether a fresh passkey can replace TOTP. SSO administration requires a separate TOTP verification.")}</p></section>${demo}</div>`;
|
|
}
|
|
function sessions() {
|
|
const rows = snap().sessions;
|
|
return `${heading(title.sessions, t("Устройства, на которых выполнен вход в ваш аккаунт.", "Devices currently signed in to your account."), action("revoke-others", "Завершить другие сеансы", "End other sessions"))}<div class="page-body identity-body"><section class="identity-section"><div class="identity-list-heading"><span>${t("Устройство", "Device")}</span><span>${t("Последняя активность", "Last activity")}</span></div>${rows.map((s) => `<div class="identity-session"><span class="identity-device-icon">${icon("sessions")}</span><div><h3>${s.device}</h3><p>${s.place}${s.current ? " · " + t("Текущий сеанс", "Current session") : ""}</p></div><time>${s.seen}</time><button class="${s.current ? "" : "danger"}" data-identity="revoke-session" data-session="${s.id}">${s.current ? t("Выйти", "Sign out") : t("Завершить", "End session")}</button></div>`).join("")}</section><p class="identity-explanation">${t("Выход из SSO завершает текущий браузерный сеанс. Остальные устройства сохраняют вход, пока вы не завершите их отдельно.", "Signing out of SSO ends this browser session. Other devices stay signed in until you end those sessions separately.")}</p>${demo}</div>`;
|
|
}
|
|
function applications(a) {
|
|
const grants = adapter.getGrants(a.sub === "demo-anna" ? 1 : 2);
|
|
return `${heading(title.applications, t("Сервисы, доступные вашему аккаунту.", "Services available to your account."))}<div class="page-body identity-body"><div class="identity-apps">${grants
|
|
.map((g) => {
|
|
const app = applicationCatalog.find((v) => v.id === g.application);
|
|
return `<article class="identity-app"><span class="app-monogram" aria-hidden="true">${app.code}</span><div><h2>${app.name}</h2><p>${app.description[t("ru", "en") === "ru" ? 0 : 1]}</p><small>${g.status === "active" ? t("Доступ выдан", "Access granted") + " · " + g.added : t("Доступ приостановлен", "Access suspended") + (g.showReason ? " · " + e(g.reason) : "")}</small></div><button data-identity="open-app" data-app="${app.id}" ${g.status !== "active" ? "disabled" : ""}>${t("Открыть", "Open")}</button></article>`;
|
|
})
|
|
.join(
|
|
"",
|
|
)}</div><p class="identity-explanation">${t("Нужен другой сервис? Запросите доступ у администратора организации.", "Need another service? Request access from your organization administrator.")}</p>${demo}</div>`;
|
|
}
|
|
function appearance() {
|
|
return `${heading(title.appearance, t("Выберите режим для повседневной работы.", "Choose a mode for everyday work."))}<div class="page-body identity-body"><div class="theme-choice-grid">${["light", "dark"].map((mode) => `<button class="theme-choice" data-identity="theme" data-theme="${mode}" aria-pressed="${document.body.dataset.theme === mode}"><span class="theme-thumbnail ${mode}" aria-hidden="true"><i></i><i></i><i></i></span><strong>${mode === "light" ? t("Светлая", "Light") : t("Тёмная", "Dark")}</strong><small>${mode === "light" ? t("Светлые поверхности и петрольный текст", "Light surfaces and petrol text") : t("Глубокий петроль и мягкий контраст", "Deep petrol and soft contrast")}</small></button>`).join("")}</div><p class="identity-explanation">${t("Палитру организации настраивает администратор. Пользователь выбирает только светлый или тёмный режим.", "An administrator configures your organization palette. Users choose only light or dark mode.")}</p>${demo}</div>`;
|
|
}
|
|
function stateLab() {
|
|
const status = snap().status;
|
|
return `${heading(title.identity, t("Просмотрите реакцию интерфейса на состояние SSO.", "Inspect how the interface responds to SSO state."), action("reset", "Сбросить демо", "Reset demo"))}<div class="page-body"><div class="identity-state-controls"><label class="field">${t("Состояние", "State")}<select id="identity-state">${identityStates.map((s) => `<option value="${s}" ${s === status ? "selected" : ""}>${stateLabels[s]}</option>`).join("")}</select></label><code>${status}</code></div><div class="identity-state-preview">${status === "authenticated" ? `<div class="identity-gate"><h2>${stateLabels.authenticated}</h2><p>${t("Личность проверена. Доступны профиль, сеансы и разрешённые приложения.", "Identity verified. Profile, sessions and permitted applications are available.")}</p><div class="component-row"><button data-page="profile">${title.profile}</button><button data-page="applications">${title.applications}</button></div></div>` : gate(status)}</div><p class="identity-explanation">${t("Все состояния здесь управляются вручную для сравнения дизайна. При реальной интеграции они приходят от backend приложения. События браузера сами по себе не подтверждают вход.", "All states here are controlled manually for design comparison. A real integration obtains them from the application backend. Browser events alone never establish authentication.")}</p></div>`;
|
|
}
|
|
function emailLink(kind) {
|
|
if (!snap().account.emailVerified) {
|
|
addEmail();
|
|
return;
|
|
}
|
|
openDialog(
|
|
t("Подтверждение по почте", "Email verification"),
|
|
`<p>${kind === "password" ? t("Смена пароля подтверждается одноразовой ссылкой из письма.", "Password changes are verified with a single-use email link.") : t("Сброс TOTP подтверждается одноразовой ссылкой из письма.", "TOTP reset is verified with a single-use email link.")}</p><p>${e(snap().account.email)}</p><small>${t("Ссылка действует 1 час. В этом демо письмо не отправляется.", "The link is valid for 1 hour. This demo does not send an email.")}</small><div class="form-footer">${action("email-sent", "Показать результат", "Show result", "primary")}</div>`,
|
|
);
|
|
}
|
|
function addEmail() {
|
|
openDialog(
|
|
t("Добавить почту", "Add email"),
|
|
`<p>${t("Сначала подтвердите почту. В реальном SSO привязка требует недавнего подтверждения личности.", "Verify your email first. A real SSO link requires recent identity verification.")}</p><form id="identity-email"><label class="field">Email<input type="email" name="email" autocomplete="email" required></label><small>${t("Демо: письма не отправляются. Нажатие имитирует завершённое подтверждение.", "Demo: no email is sent. This button simulates completed verification.")}</small><div class="form-footer"><button class="primary" type="submit">${t("Подтвердить в демо", "Verify in demo")}</button></div></form>`,
|
|
);
|
|
$("#identity-email").onsubmit = (ev) => {
|
|
ev.preventDefault();
|
|
adapter.verifyEmail(new FormData(ev.target).get("email"));
|
|
$("#dialog").close();
|
|
render();
|
|
toast(t("Почта подтверждена в демо", "Email verified in demo"));
|
|
};
|
|
}
|
|
function confirm(titleText, description, confirmId, data = "") {
|
|
openDialog(
|
|
titleText,
|
|
`<p>${description}</p><div class="form-footer"><button data-action="close">${t("Отмена", "Cancel")}</button><button class="danger" data-identity="${confirmId}" ${data}>${t("Подтвердить", "Confirm")}</button></div>`,
|
|
);
|
|
}
|
|
function switchAccount() {
|
|
openDialog(
|
|
t("Сменить аккаунт", "Switch account"),
|
|
`<p>${t("Текущий браузерный вход будет завершён. Затем откроется новая форма входа SSO. Другие устройства сохранят свои сеансы.", "This browser session will end, followed by a new SSO sign-in form. Other devices will retain their sessions.")}</p><small>${t("Демо: письма, токены и запросы к провайдеру не используются.", "Demo: no email, tokens or provider requests are used.")}</small><div class="form-footer"><button data-action="close">${t("Отмена", "Cancel")}</button><button class="primary" data-identity="confirm-switch">${t("Продолжить", "Continue")}</button></div>`,
|
|
);
|
|
}
|
|
async function handleClick(event) {
|
|
const b = event.target.closest("[data-identity]");
|
|
if (!b) return false;
|
|
event.preventDefault();
|
|
const id = b.dataset.identity;
|
|
document
|
|
.querySelectorAll("[popover]:popover-open")
|
|
.forEach((p) => p.hidePopover());
|
|
try {
|
|
if (id === "add-email") {
|
|
addEmail();
|
|
return true;
|
|
}
|
|
if (id === "switch") {
|
|
switchAccount();
|
|
return true;
|
|
}
|
|
if (id === "confirm-switch") {
|
|
$("#dialog").close();
|
|
adapter.setScenario("signing_out");
|
|
const revision = snap().revision;
|
|
render();
|
|
await new Promise((resolve) => setTimeout(resolve, 250));
|
|
if (snap().revision !== revision) return true;
|
|
adapter.signOut();
|
|
navigate("auth");
|
|
return true;
|
|
}
|
|
if (id === "logout") {
|
|
confirm(
|
|
t("Выйти из SSO?", "Sign out of SSO?"),
|
|
t(
|
|
"Завершится текущий браузерный сеанс. Другие устройства останутся в системе.",
|
|
"This browser session will end. Other devices will remain signed in.",
|
|
),
|
|
"confirm-logout",
|
|
);
|
|
return true;
|
|
}
|
|
if (id === "confirm-logout") {
|
|
$("#dialog").close();
|
|
adapter.setScenario("signing_out");
|
|
const revision = snap().revision;
|
|
render();
|
|
await new Promise((resolve) => setTimeout(resolve, 250));
|
|
if (snap().revision !== revision) return true;
|
|
adapter.signOut();
|
|
navigate("auth");
|
|
return true;
|
|
}
|
|
if (id === "begin-signin") {
|
|
navigate("auth");
|
|
return true;
|
|
}
|
|
if (["resolve", "enroll-factor"].includes(id)) {
|
|
if (id === "enroll-factor") {
|
|
pendingEnrollment = true;
|
|
openDialog(
|
|
t("Подключение фактора", "Set up verification"),
|
|
`<p>${t("В настоящем потоке настройка выполняется в SSO после подтверждения личности.", "In a real flow this is configured in SSO after identity verification.")}</p>${demo}<button class="primary" data-identity="resolve">${t("Завершить демо-проверку", "Complete demo verification")}</button>`,
|
|
);
|
|
return true;
|
|
}
|
|
$("#dialog").close();
|
|
adapter.setScenario("authenticated");
|
|
if (pendingEnrollment) {
|
|
adapter.setTotp(true);
|
|
pendingEnrollment = false;
|
|
}
|
|
render();
|
|
return true;
|
|
}
|
|
if (id === "verify-factor") {
|
|
openDialog(
|
|
t("Подтвердите TOTP", "Verify TOTP"),
|
|
`<p>${t("Введите 6 цифр. В демо подходит 123456.", "Enter 6 digits. Use 123456 in the demo.")}</p><form id="identity-factor"><label class="field">${t("Код подтверждения", "Verification code")}<input name="code" inputmode="numeric" autocomplete="one-time-code" pattern="[0-9]{6}" maxlength="6" minlength="6" required aria-describedby="factor-error"></label><p id="factor-error" class="error-text" role="alert"></p><button class="primary" type="submit">${t("Подтвердить", "Verify")}</button></form>`,
|
|
);
|
|
const form = $("#identity-factor");
|
|
const submit = () => {
|
|
if (form.elements.code.value !== "123456") {
|
|
$("#factor-error").textContent = t(
|
|
"Неверный код. Используйте 123456 для демонстрации.",
|
|
"Incorrect code. Use 123456 for this demo.",
|
|
);
|
|
form.elements.code.setAttribute("aria-invalid", "true");
|
|
return;
|
|
}
|
|
$("#dialog").close();
|
|
adapter.setScenario("authenticated");
|
|
render();
|
|
};
|
|
form.onsubmit = (e) => {
|
|
e.preventDefault();
|
|
submit();
|
|
};
|
|
form.elements.code.oninput = (e) => {
|
|
if (e.target.value.length === 6) submit();
|
|
};
|
|
return true;
|
|
}
|
|
if (id === "password-link" || id === "totp-link") {
|
|
emailLink(id === "password-link" ? "password" : "totp");
|
|
return true;
|
|
}
|
|
if (id === "email-sent") {
|
|
$("#dialog").close();
|
|
toast(
|
|
t(
|
|
"Демо: запрос принят. Письмо не отправлено.",
|
|
"Demo request accepted. No email was sent.",
|
|
),
|
|
);
|
|
return true;
|
|
}
|
|
if (id === "add-passkey") {
|
|
openDialog(
|
|
t("Добавить Passkey", "Add passkey"),
|
|
`<p>${t("Демонстрационный ключ. Windows Hello или Touch ID здесь не запускается.", "Demo key. Windows Hello or Touch ID is not invoked here.")}</p><form id="identity-passkey"><label class="field">${t("Название устройства", "Device name")}<input name="name" required maxlength="60" value="Windows Hello"></label><button class="primary" type="submit">${t("Добавить в демо", "Add to demo")}</button></form>`,
|
|
);
|
|
$("#identity-passkey").onsubmit = (ev) => {
|
|
ev.preventDefault();
|
|
adapter.addPasskey(new FormData(ev.target).get("name"));
|
|
$("#dialog").close();
|
|
render();
|
|
toast(t("Демо-Passkey добавлен", "Demo passkey added"));
|
|
};
|
|
return true;
|
|
}
|
|
if (id === "remove-passkey") {
|
|
confirm(
|
|
t("Удалить Passkey?", "Remove passkey?"),
|
|
t(
|
|
"Другие способы входа сохранятся.",
|
|
"Other sign-in methods will remain available.",
|
|
),
|
|
"confirm-remove-key",
|
|
`data-key="${e(b.dataset.key)}"`,
|
|
);
|
|
return true;
|
|
}
|
|
if (id === "confirm-remove-key") {
|
|
adapter.removePasskey(b.dataset.key);
|
|
$("#dialog").close();
|
|
render();
|
|
toast(t("Passkey удалён в демо", "Passkey removed in demo"));
|
|
return true;
|
|
}
|
|
if (id === "revoke-session") {
|
|
const current = b.dataset.session === "current";
|
|
if (current) {
|
|
confirm(
|
|
t("Завершить текущий сеанс?", "End current session?"),
|
|
t(
|
|
"Вы выйдете из SSO в этом браузере.",
|
|
"You will be signed out of SSO in this browser.",
|
|
),
|
|
"confirm-logout",
|
|
);
|
|
return true;
|
|
}
|
|
confirm(
|
|
t("Завершить сеанс?", "End session?"),
|
|
t(
|
|
"Устройство потребуется авторизовать повторно.",
|
|
"The device will need to sign in again.",
|
|
),
|
|
"confirm-revoke",
|
|
`data-session="${e(b.dataset.session)}"`,
|
|
);
|
|
return true;
|
|
}
|
|
if (id === "confirm-revoke") {
|
|
adapter.revokeSession(b.dataset.session);
|
|
$("#dialog").close();
|
|
render();
|
|
toast(t("Сеанс завершён в демо", "Demo session ended"));
|
|
return true;
|
|
}
|
|
if (id === "revoke-others") {
|
|
confirm(
|
|
t("Завершить другие сеансы?", "End other sessions?"),
|
|
t(
|
|
"Текущий сеанс останется активным.",
|
|
"Your current session will stay active.",
|
|
),
|
|
"confirm-revoke-others",
|
|
);
|
|
return true;
|
|
}
|
|
if (id === "confirm-revoke-others") {
|
|
adapter.revokeOtherSessions();
|
|
$("#dialog").close();
|
|
render();
|
|
toast(t("Другие сеансы завершены в демо", "Other demo sessions ended"));
|
|
return true;
|
|
}
|
|
if (id === "clear-avatar") {
|
|
avatarDraft = "";
|
|
$("#avatar-preview").innerHTML = avatar({
|
|
...snap().account,
|
|
avatar: "",
|
|
});
|
|
return true;
|
|
}
|
|
if (id === "theme") {
|
|
setTheme(b.dataset.theme);
|
|
return true;
|
|
}
|
|
if (id === "open-app") {
|
|
const app = applicationCatalog.find((a) => a.id === b.dataset.app);
|
|
openDialog(
|
|
app.name,
|
|
`<p>${t("Демонстрация перехода в приложение. Реальный адрес не подключён.", "Demo application handoff. No live destination is connected.")}</p><button data-action="close">${t("Вернуться", "Go back")}</button>`,
|
|
);
|
|
return true;
|
|
}
|
|
if (id === "reset") {
|
|
adapter.reset();
|
|
render();
|
|
toast(t("SSO-демо сброшено", "SSO demo reset"));
|
|
return true;
|
|
}
|
|
if (id.startsWith("grant-") || id === "add-role") {
|
|
return handleGrant(id, b);
|
|
}
|
|
} catch (error) {
|
|
toast(
|
|
t(
|
|
"Действие недоступно. Повторите вход в демо.",
|
|
"Action unavailable. Sign in to the demo again.",
|
|
),
|
|
);
|
|
}
|
|
return true;
|
|
}
|
|
function bind(page) {
|
|
if ($("#identity-state"))
|
|
$("#identity-state").onchange = (ev) => {
|
|
adapter.setScenario(ev.target.value);
|
|
render();
|
|
$("#identity-state").focus();
|
|
};
|
|
const form = $("#identity-profile");
|
|
if (form) {
|
|
avatarDraft = null;
|
|
form.onreset = (ev) => {
|
|
ev.preventDefault();
|
|
render();
|
|
};
|
|
form.onsubmit = (ev) => {
|
|
ev.preventDefault();
|
|
const values = Object.fromEntries(new FormData(form));
|
|
if (!values.firstName.trim() || !values.lastName.trim()) {
|
|
$("#profile-error").textContent = t(
|
|
"Имя и фамилия не должны состоять из пробелов.",
|
|
"First and last name cannot be blank.",
|
|
);
|
|
return;
|
|
}
|
|
if (avatarDraft !== null) values.avatar = avatarDraft;
|
|
adapter.updateProfile(values);
|
|
render();
|
|
toast(t("Профиль сохранён в демо", "Demo profile saved"));
|
|
};
|
|
$("#identity-avatar-file").onchange = async (ev) => {
|
|
const uploadRevision = snap().revision;
|
|
const file = ev.target.files[0];
|
|
if (!file) return;
|
|
if (
|
|
!["image/png", "image/jpeg", "image/webp"].includes(file.type) ||
|
|
file.size > 2 * 1024 * 1024
|
|
) {
|
|
$("#profile-error").textContent = t(
|
|
"Выберите PNG, JPEG или WebP размером до 2 МБ.",
|
|
"Choose PNG, JPEG or WebP up to 2 MB.",
|
|
);
|
|
return;
|
|
}
|
|
try {
|
|
const data = await new Promise((resolve, reject) => {
|
|
const reader = new FileReader();
|
|
reader.onload = () => resolve(reader.result);
|
|
reader.onerror = reject;
|
|
reader.readAsDataURL(file);
|
|
});
|
|
const image = new Image();
|
|
image.src = data;
|
|
await image.decode();
|
|
if (
|
|
!$("#avatar-preview") ||
|
|
snap().revision !== uploadRevision ||
|
|
!snap().account
|
|
)
|
|
return;
|
|
avatarDraft = data;
|
|
$("#avatar-preview").innerHTML = avatar({
|
|
...snap().account,
|
|
avatar: data,
|
|
});
|
|
$("#profile-error").textContent = "";
|
|
} catch {
|
|
$("#profile-error").textContent = t(
|
|
"Изображение не удалось прочитать.",
|
|
"Could not read the image.",
|
|
);
|
|
}
|
|
};
|
|
}
|
|
}
|
|
function grantsMarkup(userId) {
|
|
const rows = adapter.getGrants(userId);
|
|
return `<section class="identity-grants"><div class="section-title"><h3>${t("Доступ к приложениям", "Application access")}</h3><button type="button" data-identity="grant-add">${t("Добавить приложение", "Add application")}</button></div><div class="grant-bulk"><span id="grant-count">${t("Выбрано", "Selected")}: ${selectedGrants.size}</span><button type="button" data-identity="grant-suspend" ${selectedGrants.size ? "" : "disabled"}>${t("Приостановить выбранные", "Suspend selected")}</button></div><div class="table-wrap"><table><thead><tr><th><input type="checkbox" id="grant-all" aria-label="${t("Выбрать все приложения", "Select all applications")}"></th><th>${t("Приложение", "Application")}</th><th>${t("Выдано", "Granted")}</th><th>${t("Кем", "By")}</th><th>${t("Действия", "Actions")}</th></tr></thead><tbody>${rows.map((g) => `<tr><td><input type="checkbox" data-grant="${g.application}" aria-label="${t("Выбрать", "Select")} ${applicationCatalog.find((a) => a.id === g.application).name}" ${selectedGrants.has(g.application) ? "checked" : ""}></td><td>${applicationCatalog.find((a) => a.id === g.application).name}<small class="${g.status === "active" ? "status" : "error-text"}">${g.status === "active" ? t("Активен", "Active") : t("Приостановлен", "Suspended")}</small></td><td>${g.added}</td><td>${e(g.by)}</td><td><details class="grant-actions"><summary aria-label="${t("Действия приложения", "Application actions")}">···</summary><div class="dropdown"><button type="button" data-identity="${g.status === "active" ? "grant-suspend" : "grant-resume"}" data-app="${g.application}">${g.status === "active" ? t("Приостановить", "Suspend") : t("Возобновить", "Resume")}</button></div></details></td></tr>`).join("")}</tbody></table></div></section>`;
|
|
}
|
|
function roleMarkup(userId) {
|
|
const roles = adapter.getUserRoles(userId);
|
|
return `<fieldset class="identity-role-fields"><legend>${t("Роли SSO", "SSO roles")}</legend>${[...systemRoles, ...snap().customRoles].map((r) => `<label><input type="checkbox" name="ssoRole" value="${e(r)}" ${roles.includes(r) ? "checked" : ""}> ${e(r)}</label>`).join("")}</fieldset><div class="component-row"><input id="custom-role" placeholder="${t("Новая роль", "New role")}" aria-label="${t("Название новой роли", "New role name")}" maxlength="40"><button type="button" data-identity="add-role">${t("Добавить роль", "Add role")}</button></div>`;
|
|
}
|
|
function bindGrants(userId, reopen) {
|
|
editingUser = { id: userId, reopen };
|
|
selectedGrants = new Set();
|
|
bindGrantChecks();
|
|
}
|
|
function bindGrantChecks() {
|
|
document.querySelectorAll("[data-grant]").forEach(
|
|
(c) =>
|
|
(c.onchange = () => {
|
|
c.checked
|
|
? selectedGrants.add(c.dataset.grant)
|
|
: selectedGrants.delete(c.dataset.grant);
|
|
updateGrantSelection();
|
|
}),
|
|
);
|
|
if ($("#grant-all"))
|
|
$("#grant-all").onchange = (ev) => {
|
|
document.querySelectorAll("[data-grant]").forEach((c) => {
|
|
c.checked = ev.target.checked;
|
|
c.checked
|
|
? selectedGrants.add(c.dataset.grant)
|
|
: selectedGrants.delete(c.dataset.grant);
|
|
});
|
|
updateGrantSelection();
|
|
};
|
|
}
|
|
function updateGrantSelection() {
|
|
if (!$("#grant-count")) return;
|
|
$("#grant-count").textContent =
|
|
t("Выбрано", "Selected") + ": " + selectedGrants.size;
|
|
$(".grant-bulk button").disabled = !selectedGrants.size;
|
|
const checks = [...document.querySelectorAll("[data-grant]")];
|
|
$("#grant-all").checked =
|
|
checks.length > 0 && checks.every((c) => c.checked);
|
|
$("#grant-all").indeterminate =
|
|
checks.some((c) => c.checked) && !checks.every((c) => c.checked);
|
|
}
|
|
function handleGrant(id, b) {
|
|
const userId = editingUser.id,
|
|
reopen = editingUser.reopen;
|
|
if (id === "grant-add") {
|
|
const available = applicationCatalog.filter(
|
|
(a) => !adapter.getGrants(userId).some((g) => g.application === a.id),
|
|
);
|
|
openDialog(
|
|
t("Добавить приложение", "Add application"),
|
|
available.length
|
|
? `<form id="grant-add-form"><label class="field">${t("Приложение", "Application")}<select name="application">${available.map((a) => `<option value="${a.id}">${a.name}</option>`).join("")}</select></label><button class="primary" type="submit">${t("Выдать доступ", "Grant access")}</button></form>`
|
|
: `<p>${t("Все приложения уже добавлены.", "All applications have already been added.")}</p>`,
|
|
);
|
|
if ($("#grant-add-form"))
|
|
$("#grant-add-form").onsubmit = (ev) => {
|
|
ev.preventDefault();
|
|
adapter.addGrant(userId, new FormData(ev.target).get("application"));
|
|
reopen();
|
|
};
|
|
return true;
|
|
}
|
|
if (id === "grant-suspend") {
|
|
const ids = b.dataset.app ? [b.dataset.app] : [...selectedGrants];
|
|
openDialog(
|
|
t("Приостановить доступ", "Suspend access"),
|
|
`<form id="grant-suspend-form"><p>${t("Приложений выбрано", "Applications selected")}: ${ids.length}</p><label class="field">${t("Причина", "Reason")}<textarea name="reason" required maxlength="300" rows="3"></textarea></label><div class="form-row"><input id="show-reason" type="checkbox" name="showReason"><label for="show-reason">${t("Показывать причину пользователю", "Show reason to user")}</label></div><button class="primary" type="submit">${t("Приостановить", "Suspend")}</button></form>`,
|
|
);
|
|
$("#grant-suspend-form").onsubmit = (ev) => {
|
|
ev.preventDefault();
|
|
const f = new FormData(ev.target),
|
|
reason = f.get("reason").trim();
|
|
if (!reason) {
|
|
ev.target.elements.reason.setCustomValidity(
|
|
t("Укажите причину", "Enter a reason"),
|
|
);
|
|
ev.target.elements.reason.reportValidity();
|
|
return;
|
|
}
|
|
adapter.updateGrants(userId, ids, {
|
|
status: "suspended",
|
|
reason,
|
|
showReason: f.has("showReason"),
|
|
});
|
|
reopen();
|
|
toast(t("Доступ приостановлен в демо", "Demo access suspended"));
|
|
};
|
|
$("#grant-suspend-form textarea").oninput = (ev) =>
|
|
ev.target.setCustomValidity("");
|
|
return true;
|
|
}
|
|
if (id === "grant-resume") {
|
|
adapter.updateGrants(userId, [b.dataset.app], {
|
|
status: "active",
|
|
reason: "",
|
|
showReason: false,
|
|
});
|
|
reopen();
|
|
return true;
|
|
}
|
|
if (id === "add-role") {
|
|
const value = $("#custom-role").value.trim();
|
|
if (value) {
|
|
adapter.addRole(value);
|
|
const field = $(".identity-role-fields");
|
|
const label = document.createElement("label");
|
|
const check = document.createElement("input");
|
|
check.type = "checkbox";
|
|
check.name = "ssoRole";
|
|
check.value = value;
|
|
check.checked = true;
|
|
label.append(check, document.createTextNode(" " + value));
|
|
if (
|
|
![...field.querySelectorAll("input")].some((c) => c.value === value)
|
|
)
|
|
field.append(label);
|
|
$("#custom-role").value = "";
|
|
}
|
|
return true;
|
|
}
|
|
return false;
|
|
}
|
|
return {
|
|
titles: title,
|
|
renderPage,
|
|
gate,
|
|
handleClick,
|
|
bind,
|
|
switchAccount,
|
|
grantsMarkup,
|
|
roleMarkup,
|
|
bindGrants,
|
|
};
|
|
}
|