feat(web): add logout button for web mode
This commit is contained in:
1 parent
7aa69a0e5e
commit
e3ea4740c0
19 files changed
+405
-3
No files matched your search
@@ -3,7 +3,7 @@ import { blockingDesktopAiRunsForUpdate } from "@/lib/ai/desktopAiRunRegistry";
|
||||
import { setupUpdatePreparation, prepareUpdateWithDraftRecovery, isUpdatePreparationActive } from "@/lib/app/updatePreparation";
|
||||
import { ref, computed, watch, onMounted, onUnmounted, nextTick, defineAsyncComponent, provide } from "vue";
|
||||
import "vue-virtual-scroller/dist/vue-virtual-scroller.css";
|
||||
import { checkStartupAuthentication, type StartupAuthentication } from "@/lib/startup/startupAuthentication";
|
||||
import { checkStartupAuthentication, logoutWeb, type StartupAuthentication } from "@/lib/startup/startupAuthentication";
|
||||
import { markStartupPhase } from "@/lib/startup/startupTiming";
|
||||
import { clearStartupPreloadRetry } from "@/lib/startup/startupPreloadRecovery";
|
||||
import { useI18n } from "vue-i18n";
|
||||
@@ -4031,6 +4031,24 @@ function onLoginSuccess() {
|
||||
void initApp();
|
||||
}
|
||||
|
||||
async function handleWebLogout() {
|
||||
if (!window.confirm(t("auth.logoutConfirm"))) return;
|
||||
try {
|
||||
await logoutWeb();
|
||||
} catch (error) {
|
||||
console.error("Failed to log out:", error);
|
||||
} finally {
|
||||
authenticated.value = false;
|
||||
needsAuth.value = true;
|
||||
const target = webPath("/login");
|
||||
if (window.location.pathname === target) {
|
||||
window.location.reload();
|
||||
} else {
|
||||
window.location.href = target;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function initApp() {
|
||||
const t0 = performance.now();
|
||||
console.log("[STARTUP] initApp begin");
|
||||
@@ -4356,6 +4374,7 @@ onUnmounted(() => {
|
||||
:has-connections="connectionStore.connections.length > 0"
|
||||
:can-new-query="canCreateNewQuery"
|
||||
:has-sql-file-connections="hasSqlFileConnections"
|
||||
:show-logout="!isDesktop && needsAuth"
|
||||
@new-connection="showConnectionDialog = true"
|
||||
@expand-sidebar="setSidebarOpen(true)"
|
||||
@new-query="newQuery"
|
||||
@@ -4375,6 +4394,7 @@ onUnmounted(() => {
|
||||
@open-data-compare="dialogs.showDataCompareDialog.value = true"
|
||||
@open-backups="openSettings('backups')"
|
||||
@open-mcp-settings="openSettings('mcp')"
|
||||
@logout="handleWebLogout"
|
||||
/>
|
||||
|
||||
<div :class="isDetachedWindowContext ? 'flex-1 flex min-h-0' : isClassicLayout ? 'app-layout-classic flex-1 flex min-h-0' : 'app-panel-gutter flex-1 flex min-h-0 gap-1 p-1'">
|
||||
@@ -4469,6 +4489,7 @@ onUnmounted(() => {
|
||||
"
|
||||
@open-mcp-settings="openSettings('mcp')"
|
||||
@ai-config-deep-link-handled="settingsAiConfigDraft = null"
|
||||
@logout="handleWebLogout"
|
||||
/>
|
||||
</AppTabBar>
|
||||
<DetachedTabHeader
|
||||
|
||||
@@ -26,6 +26,7 @@ import {
|
||||
GripVertical,
|
||||
HardDrive,
|
||||
Loader2,
|
||||
LogOut,
|
||||
Moon,
|
||||
PackageSearch,
|
||||
Palette,
|
||||
@@ -502,6 +503,7 @@ const emit = defineEmits<{
|
||||
"open-mcp-settings": [];
|
||||
"open-update-center": [];
|
||||
"ai-config-deep-link-handled": [];
|
||||
logout: [];
|
||||
}>();
|
||||
|
||||
const hasAnyUpdate = computed(() => Boolean(props.appUpdateAvailable || (props.driverUpdateCount || 0) > 0 || props.jdbcUpdateAvailable || props.mcpUpdateAvailable || (props.pluginUpdateCount || 0) > 0));
|
||||
@@ -11327,6 +11329,19 @@ LIMIT 100;</pre
|
||||
{{ passwordMessage }}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div class="border-t border-border/60 pt-5 space-y-3">
|
||||
<Label class="text-base">{{ t("auth.logout") }}</Label>
|
||||
<p class="text-sm text-muted-foreground">
|
||||
{{ t("auth.logoutDescription") }}
|
||||
</p>
|
||||
<div>
|
||||
<Button variant="outline" class="gap-2 text-destructive hover:text-destructive" @click="emit('logout')">
|
||||
<LogOut class="h-4 w-4" />
|
||||
{{ t("auth.logout") }}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section v-else-if="activeSettingsTab === 'tunnels'" data-settings-search-id="tunnels" :class="['flex flex-col gap-5 py-2', settingsSearchTargetClass('tunnels')]">
|
||||
|
||||
+137
@@ -0,0 +1,137 @@
|
||||
// @vitest-environment happy-dom
|
||||
|
||||
import { createApp, defineComponent, h, nextTick, type App } from "vue";
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { createPinia } from "pinia";
|
||||
|
||||
vi.mock("@/lib/backend/tauriRuntime", () => ({ isTauriRuntime: () => false }));
|
||||
|
||||
vi.mock("vue-i18n", async () => {
|
||||
const { ref } = await import("vue");
|
||||
const locale = ref("en");
|
||||
const t = (key: string) => key;
|
||||
return {
|
||||
createI18n: () => ({ global: { t, locale }, install: () => undefined }),
|
||||
useI18n: () => ({ t, locale }),
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock("@/components/ui/dialog", async () => {
|
||||
const { defineComponent, h } = await import("vue");
|
||||
const passthrough = defineComponent({
|
||||
setup(_props, { slots }) {
|
||||
return () => h("div", slots.default?.());
|
||||
},
|
||||
});
|
||||
return {
|
||||
Dialog: passthrough,
|
||||
DialogContent: passthrough,
|
||||
DialogFooter: passthrough,
|
||||
DialogHeader: passthrough,
|
||||
DialogTitle: passthrough,
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock("@/components/ui/button", async () => {
|
||||
const { defineComponent, h } = await import("vue");
|
||||
return {
|
||||
Button: defineComponent({
|
||||
inheritAttrs: false,
|
||||
setup(_props, { attrs, slots }) {
|
||||
return () => h("button", attrs, slots.default?.());
|
||||
},
|
||||
}),
|
||||
};
|
||||
});
|
||||
|
||||
vi.mock("@/components/settings/ChangelogPanel.vue", async () => {
|
||||
const { defineComponent } = await import("vue");
|
||||
return { default: defineComponent({ setup: () => () => null }) };
|
||||
});
|
||||
|
||||
vi.mock("@/stores/settingsStore", async (importOriginal) => {
|
||||
const actual = await importOriginal<typeof import("@/stores/settingsStore")>();
|
||||
const store = {
|
||||
settingsPageActive: false,
|
||||
editorSettings: actual.DEFAULT_EDITOR_SETTINGS,
|
||||
desktopSettings: actual.DEFAULT_DESKTOP_SETTINGS,
|
||||
mcpGlobalPolicy: { configured: false, readOnly: false },
|
||||
aiConfigs: [],
|
||||
aiDefaultTemplatesByDbType: {},
|
||||
defaultAiMode: "ask",
|
||||
restoreLastConversation: false,
|
||||
initMcpGlobalPolicy: vi.fn(async () => undefined),
|
||||
updateMcpGlobalPolicy: vi.fn(async () => undefined),
|
||||
initAiConfigs: vi.fn(async () => undefined),
|
||||
initDesktopSettings: vi.fn(async () => undefined),
|
||||
updateEditorSettingsAndPersist: vi.fn(async () => undefined),
|
||||
updateEditorSettings: vi.fn(),
|
||||
persistEditorSettings: vi.fn(async () => undefined),
|
||||
updateDesktopSettings: vi.fn(async () => undefined),
|
||||
reloadAiConfigs: vi.fn(async () => undefined),
|
||||
removeTemplateFromDefaultAndLastUsed: vi.fn(),
|
||||
setDefaultTemplatesForDbType: vi.fn(),
|
||||
updateAiConfigItem: vi.fn(),
|
||||
createAiConfig: vi.fn(),
|
||||
deleteAiConfig: vi.fn(),
|
||||
setDefaultAiConfig: vi.fn(),
|
||||
setDefaultAiMode: vi.fn(),
|
||||
setRestoreLastConversation: vi.fn(),
|
||||
};
|
||||
return { ...actual, useSettingsStore: () => store };
|
||||
});
|
||||
|
||||
import EditorSettingsDialog from "../EditorSettingsDialog.vue";
|
||||
|
||||
if (!("ResizeObserver" in globalThis)) {
|
||||
(globalThis as unknown as { ResizeObserver: unknown }).ResizeObserver = class {
|
||||
observe() {}
|
||||
unobserve() {}
|
||||
disconnect() {}
|
||||
};
|
||||
}
|
||||
|
||||
const mountedApps: Array<{ app: App; host: HTMLElement }> = [];
|
||||
|
||||
afterEach(() => {
|
||||
for (const { app, host } of mountedApps.splice(0)) {
|
||||
app.unmount();
|
||||
host.remove();
|
||||
}
|
||||
});
|
||||
|
||||
describe("EditorSettingsDialog web logout", () => {
|
||||
it("renders logout button under security tab and emits logout event", async () => {
|
||||
let logoutEmitted = false;
|
||||
const host = document.createElement("div");
|
||||
document.body.appendChild(host);
|
||||
|
||||
const app = createApp(
|
||||
defineComponent({
|
||||
setup() {
|
||||
return () =>
|
||||
h(EditorSettingsDialog, {
|
||||
variant: "page",
|
||||
initialTab: "security" as any,
|
||||
onLogout: () => {
|
||||
logoutEmitted = true;
|
||||
},
|
||||
});
|
||||
},
|
||||
}),
|
||||
);
|
||||
app.use(createPinia());
|
||||
app.mount(host);
|
||||
mountedApps.push({ app, host });
|
||||
|
||||
await nextTick();
|
||||
await Promise.resolve();
|
||||
|
||||
const buttons = Array.from(host.querySelectorAll("button"));
|
||||
const logoutBtn = buttons.find((btn) => btn.textContent?.includes("auth.logout"));
|
||||
expect(logoutBtn).toBeDefined();
|
||||
|
||||
logoutBtn?.click();
|
||||
expect(logoutEmitted).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -2,7 +2,7 @@
|
||||
import { computed, ref, onMounted, onBeforeUnmount, h, nextTick, watch } from "vue";
|
||||
import { useI18n } from "vue-i18n";
|
||||
import { invoke } from "@tauri-apps/api/core";
|
||||
import { ChevronsRight, DatabaseZap, FilePlus2, Moon, Sun, SunMoon, History, Bot, ArrowLeftRight, FileCode, BookMarked, GitCompareArrows, TableProperties, Settings, CloudDownload, Package, PlugZap, FileDown, FolderTree, Pin, PinOff, CalendarClock, Waypoints } from "@lucide/vue";
|
||||
import { ChevronsRight, DatabaseZap, FilePlus2, Moon, Sun, SunMoon, History, Bot, ArrowLeftRight, FileCode, BookMarked, GitCompareArrows, TableProperties, Settings, LogOut, CloudDownload, Package, PlugZap, FileDown, FolderTree, Pin, PinOff, CalendarClock, Waypoints } from "@lucide/vue";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { Tooltip, TooltipContent, TooltipTrigger } from "@/components/ui/tooltip";
|
||||
import LightDropdown, { type LightDropdownItem } from "@/components/ui/LightDropdown.vue";
|
||||
@@ -53,6 +53,7 @@ const props = defineProps<{
|
||||
hasConnections: boolean;
|
||||
canNewQuery: boolean;
|
||||
hasSqlFileConnections: boolean;
|
||||
showLogout?: boolean;
|
||||
}>();
|
||||
|
||||
const emit = defineEmits<{
|
||||
@@ -75,6 +76,7 @@ const emit = defineEmits<{
|
||||
"open-data-compare": [];
|
||||
"open-backups": [];
|
||||
"open-mcp-settings": [];
|
||||
logout: [];
|
||||
}>();
|
||||
|
||||
const { t } = useI18n();
|
||||
@@ -782,6 +784,15 @@ const toolbarStyle = computed(() => {
|
||||
<TooltipContent>{{ hasMcpUpdateAvailable ? t("toolbar.mcpUpdateAvailable") : t("settings.title") }}</TooltipContent>
|
||||
</Tooltip>
|
||||
|
||||
<Tooltip v-if="showLogout">
|
||||
<TooltipTrigger as-child>
|
||||
<Button variant="ghost" size="icon" class="toolbar-action-button h-8 w-8 shrink-0" :aria-label="t('auth.logout')" @click="emit('logout')">
|
||||
<LogOut class="toolbar-action-icon h-4 w-4" />
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>{{ t("auth.logout") }}</TooltipContent>
|
||||
</Tooltip>
|
||||
|
||||
<WindowControls v-if="showControls" :is-maximized="isMaximized" @minimize="minimize" @toggle-maximize="toggleMaximize" @close="close" />
|
||||
</div>
|
||||
</template>
|
||||
|
||||
@@ -0,0 +1,154 @@
|
||||
// @vitest-environment happy-dom
|
||||
import { createApp, nextTick, type Component } from "vue";
|
||||
import { createPinia } from "pinia";
|
||||
import { createI18n } from "vue-i18n";
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
|
||||
|
||||
vi.mock("@/lib/backend/tauriRuntime", () => ({ isTauriRuntime: () => false }));
|
||||
vi.mock("@tauri-apps/api/core", () => ({ invoke: vi.fn(async () => undefined) }));
|
||||
vi.mock("@tauri-apps/api/event", () => ({
|
||||
listen: vi.fn(async () => () => {}),
|
||||
emit: vi.fn(async () => undefined),
|
||||
}));
|
||||
vi.mock("@tauri-apps/api/webviewWindow", () => ({
|
||||
getAllWebviewWindows: vi.fn(async () => []),
|
||||
WebviewWindow: { getByLabel: vi.fn(async () => null) },
|
||||
}));
|
||||
vi.mock("@tauri-apps/api/window", () => ({
|
||||
getCurrentWindow: () => ({
|
||||
label: "main",
|
||||
isMaximized: async () => false,
|
||||
isFullscreen: async () => false,
|
||||
isAlwaysOnTop: async () => false,
|
||||
setAlwaysOnTop: async () => {},
|
||||
onResized: async () => () => {},
|
||||
onFocusChanged: async () => () => {},
|
||||
minimize: async () => {},
|
||||
toggleMaximize: async () => {},
|
||||
}),
|
||||
}));
|
||||
|
||||
vi.mock("@/components/ui/button", () => ({
|
||||
Button: { name: "ButtonStub", props: ["ariaLabel"], template: `<button :aria-label="ariaLabel"><slot /></button>` },
|
||||
}));
|
||||
vi.mock("@/components/ui/tooltip", () => ({
|
||||
Tooltip: { name: "TooltipStub", template: `<span><slot /></span>` },
|
||||
TooltipTrigger: { name: "TooltipTriggerStub", template: `<span><slot /></span>` },
|
||||
TooltipContent: { name: "TooltipContentStub", template: `<span><slot /></span>` },
|
||||
}));
|
||||
vi.mock("@/components/ui/LightDropdown.vue", () => ({
|
||||
default: { name: "LightDropdownStub", template: `<div />` },
|
||||
}));
|
||||
vi.mock("@/components/layout/WindowControls.vue", () => ({
|
||||
default: { name: "WindowControlsStub", template: `<div />` },
|
||||
}));
|
||||
vi.mock("@/components/export/ExportProgressPopover.vue", () => ({
|
||||
default: { name: "ExportProgressPopoverStub", template: `<div />` },
|
||||
}));
|
||||
vi.mock("@/components/layout/ToolbarUpdateIcon.vue", () => ({
|
||||
default: { name: "ToolbarUpdateIconStub", template: `<span />` },
|
||||
}));
|
||||
|
||||
import AppToolbar from "../AppToolbar.vue";
|
||||
|
||||
const defaultToolbarProps = {
|
||||
isDark: false,
|
||||
themeMode: "system" as const,
|
||||
showSidebarExpand: false,
|
||||
showAiPanel: false,
|
||||
activeAiRunCount: 0,
|
||||
awaitingAiRunCount: 0,
|
||||
showHistory: false,
|
||||
showSqlLibrary: false,
|
||||
sqlLibrarySaveFeedbackId: 0,
|
||||
showSqlFilePanel: false,
|
||||
showDriverStore: false,
|
||||
showPluginCenter: false,
|
||||
showSettingsPage: false,
|
||||
checkingUpdates: false,
|
||||
hasUpdateAvailable: false,
|
||||
isDownloadingUpdate: false,
|
||||
downloadProgress: null,
|
||||
updateReadyToInstall: false,
|
||||
updateReady: false,
|
||||
agentDriverUpdateCount: 0,
|
||||
hasMcpUpdateAvailable: false,
|
||||
hasConnections: false,
|
||||
canNewQuery: false,
|
||||
hasSqlFileConnections: false,
|
||||
};
|
||||
|
||||
let pinia: ReturnType<typeof createPinia>;
|
||||
|
||||
function mount(props: Record<string, unknown>, onLogout?: () => void) {
|
||||
const host = document.createElement("div");
|
||||
document.body.appendChild(host);
|
||||
const app = createApp(AppToolbar, {
|
||||
...defaultToolbarProps,
|
||||
...props,
|
||||
onLogout,
|
||||
});
|
||||
app.use(pinia);
|
||||
app.use(
|
||||
createI18n({
|
||||
legacy: false,
|
||||
locale: "en",
|
||||
missingWarn: false,
|
||||
fallbackWarn: false,
|
||||
messages: {
|
||||
en: {
|
||||
auth: { logout: "Log out" },
|
||||
settings: { title: "Settings" },
|
||||
toolbar: { theme: "Theme" },
|
||||
updates: { check: "Check for updates" },
|
||||
},
|
||||
},
|
||||
}),
|
||||
);
|
||||
app.mount(host);
|
||||
return {
|
||||
host,
|
||||
unmount: () => {
|
||||
app.unmount();
|
||||
host.remove();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
describe("AppToolbar web logout", () => {
|
||||
beforeEach(() => {
|
||||
pinia = createPinia();
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
document.body.innerHTML = "";
|
||||
});
|
||||
|
||||
it("renders logout button when showLogout is true and emits logout on click", async () => {
|
||||
let logoutEmitted = false;
|
||||
const { host, unmount } = mount({ showLogout: true }, () => {
|
||||
logoutEmitted = true;
|
||||
});
|
||||
|
||||
await nextTick();
|
||||
const logoutBtn = host.querySelector('button[aria-label="Log out"]');
|
||||
expect(logoutBtn).not.toBeNull();
|
||||
|
||||
logoutBtn?.dispatchEvent(new MouseEvent("click", { bubbles: true }));
|
||||
expect(logoutEmitted).toBe(true);
|
||||
|
||||
unmount();
|
||||
});
|
||||
|
||||
it("does not render logout button when showLogout is false or undefined", async () => {
|
||||
const { host, unmount } = mount({ showLogout: false });
|
||||
await nextTick();
|
||||
expect(host.querySelector('button[aria-label="Log out"]')).toBeNull();
|
||||
unmount();
|
||||
|
||||
const { host: host2, unmount: unmount2 } = mount({});
|
||||
await nextTick();
|
||||
expect(host2.querySelector('button[aria-label="Log out"]')).toBeNull();
|
||||
unmount2();
|
||||
});
|
||||
});
|
||||
@@ -202,6 +202,9 @@ export default withEnglishFallback({
|
||||
passwordChanged: "Parol uğurla dəyişdirildi",
|
||||
changePasswordFailed: "Parolu dəyişmək mümkün olmadı",
|
||||
changePasswordDescription: "Cari parolunuzu daxil edin və yeni parol seçin",
|
||||
logout: "Çıxış",
|
||||
logoutDescription: "Cari sessiyanı sonlandırın və giriş səhifəsinə qayıdın",
|
||||
logoutConfirm: "Çıxış etmək istədiyinizdən əminsiniz?",
|
||||
},
|
||||
toolbar: {
|
||||
commitOutcomeUnknown: "Təsdiqləmə nəticəsi məlum deyil və sessiya artıq mövcud deyil. SQL-i yenidən icra etməzdən əvvəl məlumatları yoxlayın.",
|
||||
|
||||
@@ -378,6 +378,9 @@ export default {
|
||||
passwordChanged: "Password changed successfully",
|
||||
changePasswordFailed: "Failed to change password",
|
||||
changePasswordDescription: "Enter your current password and choose a new one",
|
||||
logout: "Log out",
|
||||
logoutDescription: "End the current session and return to the login page",
|
||||
logoutConfirm: "Are you sure you want to log out?",
|
||||
},
|
||||
toolbar: {
|
||||
commitOutcomeUnknown: "Commit result is unknown and the session no longer exists. Verify the data before running this SQL again.",
|
||||
|
||||
@@ -371,6 +371,9 @@ export default withEnglishFallback({
|
||||
passwordChanged: "Contraseña cambiada exitosamente",
|
||||
changePasswordFailed: "Error al cambiar la contraseña",
|
||||
changePasswordDescription: "Ingresa tu contraseña actual y elige una nueva",
|
||||
logout: "Cerrar sesión",
|
||||
logoutDescription: "Finalizar la sesión actual y volver a la página de inicio de sesión",
|
||||
logoutConfirm: "¿Seguro que deseas cerrar sesión?",
|
||||
},
|
||||
toolbar: {
|
||||
commitOutcomeUnknown: "El resultado del commit es desconocido y la sesión ya no existe. Compruebe los datos antes de volver a ejecutar el SQL.",
|
||||
|
||||
@@ -317,6 +317,9 @@ export default withEnglishFallback({
|
||||
passwordChanged: "Kata sandi berhasil diubah",
|
||||
changePasswordFailed: "Gagal mengubah kata sandi",
|
||||
changePasswordDescription: "Masukkan kata sandi Anda saat ini dan pilih yang baru",
|
||||
logout: "Keluar",
|
||||
logoutDescription: "Akhiri sesi saat ini dan kembali ke halaman masuk",
|
||||
logoutConfirm: "Apakah Anda yakin ingin keluar?",
|
||||
},
|
||||
toolbar: {
|
||||
commitOutcomeUnknown: "Hasil commit tidak diketahui dan sesi sudah tidak ada lagi. Verifikasi data sebelum menjalankan SQL ini lagi.",
|
||||
|
||||
@@ -365,6 +365,9 @@ export default withEnglishFallback({
|
||||
passwordChanged: "Password modificata con successo",
|
||||
changePasswordFailed: "Impossibile modificare la password",
|
||||
changePasswordDescription: "Inserisci la password attuale e scegline una nuova",
|
||||
logout: "Disconnetti",
|
||||
logoutDescription: "Termina la sessione corrente e torna alla pagina di accesso",
|
||||
logoutConfirm: "Sei sicuro di voler uscire?",
|
||||
},
|
||||
toolbar: {
|
||||
commitOutcomeUnknown: "L'esito del commit è sconosciuto e la sessione non esiste più. Verificare i dati prima di eseguire nuovamente SQL.",
|
||||
|
||||
@@ -366,6 +366,9 @@ export default withEnglishFallback({
|
||||
passwordChanged: "パスワードが変更されました",
|
||||
changePasswordFailed: "パスワードの変更に失敗しました",
|
||||
changePasswordDescription: "現在のパスワードと新しいパスワードを入力してください",
|
||||
logout: "ログアウト",
|
||||
logoutDescription: "現在のセッションを終了してログイン画面に戻ります",
|
||||
logoutConfirm: "ログアウトしてもよろしいですか?",
|
||||
},
|
||||
toolbar: {
|
||||
commitOutcomeUnknown: "コミット結果は不明で、セッションは既に存在しません。SQL を再実行する前にデータを確認してください。",
|
||||
|
||||
@@ -374,6 +374,9 @@ export default withEnglishFallback({
|
||||
passwordChanged: "비밀번호가 변경되었습니다",
|
||||
changePasswordFailed: "비밀번호 변경에 실패했습니다",
|
||||
changePasswordDescription: "현재 비밀번호를 입력하고 새 비밀번호를 선택하세요",
|
||||
logout: "로그아웃",
|
||||
logoutDescription: "현재 세션을 종료하고 로그인 페이지로 돌아갑니다",
|
||||
logoutConfirm: "로그아웃하시겠습니까?",
|
||||
},
|
||||
toolbar: {
|
||||
commitOutcomeUnknown: "커밋 결과를 알 수 없고 세션이 더 이상 존재하지 않습니다. SQL을 다시 실행하기 전에 데이터를 확인하세요。",
|
||||
|
||||
@@ -366,6 +366,9 @@ export default withEnglishFallback({
|
||||
passwordChanged: "Senha alterada com sucesso",
|
||||
changePasswordFailed: "Falha ao alterar a senha",
|
||||
changePasswordDescription: "Digite sua senha atual e escolha uma nova",
|
||||
logout: "Sair",
|
||||
logoutDescription: "Encerrar a sessão atual e retornar à página de login",
|
||||
logoutConfirm: "Tem certeza de que deseja sair?",
|
||||
},
|
||||
toolbar: {
|
||||
commitOutcomeUnknown: "O resultado do commit é desconhecido e a sessão não existe mais. Verifique os dados antes de executar o SQL novamente.",
|
||||
|
||||
@@ -348,6 +348,9 @@ export default withEnglishFallback({
|
||||
passwordChanged: "Пароль успешно изменён",
|
||||
changePasswordFailed: "Не удалось сменить пароль",
|
||||
changePasswordDescription: "Введите текущий пароль и выберите новый",
|
||||
logout: "Выйти",
|
||||
logoutDescription: "Завершить текущий сеанс и вернуться на страницу входа",
|
||||
logoutConfirm: "Вы действительно хотите выйти?",
|
||||
},
|
||||
toolbar: {
|
||||
commitOutcomeUnknown: "Результат фиксации неизвестен, а сессия больше не существует. Проверьте данные перед повторным выполнением этого SQL.",
|
||||
|
||||
@@ -202,6 +202,9 @@ export default withEnglishFallback({
|
||||
passwordChanged: "Parola başarıyla değiştirildi",
|
||||
changePasswordFailed: "Parola değiştirilemedi",
|
||||
changePasswordDescription: "Mevcut parolanızı girin ve yeni bir parola seçin",
|
||||
logout: "Çıkış Yap",
|
||||
logoutDescription: "Mevcut oturumu sonlandırın ve giriş sayfasına dönün",
|
||||
logoutConfirm: "Çıkış yapmak istediğinizden emin misiniz?",
|
||||
},
|
||||
toolbar: {
|
||||
commitOutcomeUnknown: "Onaylama sonucu bilinmiyor ve oturum artık mevcut değil. SQL'i yeniden çalıştırmadan önce verileri doğrulayın.",
|
||||
|
||||
@@ -315,6 +315,9 @@ export default withEnglishFallback({
|
||||
passwordChanged: "密码修改成功",
|
||||
changePasswordFailed: "密码修改失败",
|
||||
changePasswordDescription: "输入当前密码并设置新密码",
|
||||
logout: "退出登录",
|
||||
logoutDescription: "退出当前会话并返回登录页面",
|
||||
logoutConfirm: "确定要退出登录吗?",
|
||||
},
|
||||
toolbar: {
|
||||
commitOutcomeUnknown: "提交结果未知,事务会话已不存在。请核对数据后再决定是否重新执行 SQL。",
|
||||
|
||||
@@ -371,6 +371,9 @@ export default withEnglishFallback({
|
||||
passwordChanged: "密碼修改成功",
|
||||
changePasswordFailed: "密碼修改失敗",
|
||||
changePasswordDescription: "輸入目前密碼並設定新密碼",
|
||||
logout: "登出",
|
||||
logoutDescription: "結束目前工作階段並返回登入頁面",
|
||||
logoutConfirm: "確定要登出嗎?",
|
||||
},
|
||||
toolbar: {
|
||||
commitOutcomeUnknown: "提交結果未知,交易工作階段已不存在。請核對資料後再決定是否重新執行 SQL。",
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// @vitest-environment happy-dom
|
||||
|
||||
import { afterEach, describe, expect, it, vi } from "vitest";
|
||||
import { checkStartupAuthentication } from "@/lib/startup/startupAuthentication";
|
||||
import { checkStartupAuthentication, logoutWeb } from "@/lib/startup/startupAuthentication";
|
||||
|
||||
afterEach(() => vi.unstubAllGlobals());
|
||||
|
||||
@@ -31,4 +31,22 @@ describe("startup authentication", () => {
|
||||
await expect(checkStartupAuthentication(controller.signal)).rejects.toThrow("AUTH_CHECK_FAILED");
|
||||
expect(fetchMock.mock.calls[0]?.[1].signal).toBe(controller.signal);
|
||||
});
|
||||
|
||||
describe("logoutWeb", () => {
|
||||
it("calls POST /api/auth/logout with same-origin credentials", async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue({ ok: true, json: async () => ({ ok: true }) });
|
||||
vi.stubGlobal("fetch", fetchMock);
|
||||
await logoutWeb();
|
||||
expect(fetchMock).toHaveBeenCalledWith("/api/auth/logout", {
|
||||
method: "POST",
|
||||
credentials: "same-origin",
|
||||
});
|
||||
});
|
||||
|
||||
it("throws AUTH_LOGOUT_FAILED when server responds with error status", async () => {
|
||||
const fetchMock = vi.fn().mockResolvedValue({ ok: false, status: 500 });
|
||||
vi.stubGlobal("fetch", fetchMock);
|
||||
await expect(logoutWeb()).rejects.toThrow("AUTH_LOGOUT_FAILED");
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -19,3 +19,13 @@ export async function checkStartupAuthentication(signal?: AbortSignal): Promise<
|
||||
setup_required: "setup_required" in result && result.setup_required === true,
|
||||
};
|
||||
}
|
||||
|
||||
export async function logoutWeb(): Promise<void> {
|
||||
const response = await fetch(apiUrl("/api/auth/logout"), {
|
||||
method: "POST",
|
||||
credentials: "same-origin",
|
||||
});
|
||||
if (!response.ok) {
|
||||
throw new Error("AUTH_LOGOUT_FAILED");
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user