fix: refactor auth settings to use api.ts, fix type alignment, OIDC token exchange
- Add auth management functions to api.ts (getAuthSettings, listUsers, etc.) - Refactor auth settings page to use centralized api.ts instead of raw fetch (FUNC-H2) - Add loading skeleton to auth settings page (UX-M16) - Add exchangeOidcToken() for httpOnly cookie OIDC flow (SEC-H3) - Fix Settings TypeScript type: has_npm_password boolean (FUNC-L) - Add last_alive_at to Instance type (FUNC-L)
This commit is contained in:
@@ -331,6 +331,51 @@ export function getCurrentUser(): Promise<{ id: string; username: string; email:
|
|||||||
return get<{ id: string; username: string; email: string; role: string }>('/api/auth/me');
|
return get<{ id: string; username: string; email: string; role: string }>('/api/auth/me');
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Auth settings
|
||||||
|
export async function getAuthSettings(): Promise<any> {
|
||||||
|
return request<any>('/api/auth/settings');
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function updateAuthSettings(settings: any): Promise<any> {
|
||||||
|
return request<any>('/api/auth/settings', {
|
||||||
|
method: 'PUT',
|
||||||
|
body: JSON.stringify(settings)
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function listUsers(): Promise<any[]> {
|
||||||
|
return request<any[]>('/api/auth/users');
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function createUser(data: { username: string; password: string; email?: string; role?: string }): Promise<any> {
|
||||||
|
return request<any>('/api/auth/users', {
|
||||||
|
method: 'POST',
|
||||||
|
body: JSON.stringify(data)
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function updateUser(uid: string, data: { email?: string; role?: string }): Promise<any> {
|
||||||
|
return request<any>(`/api/auth/users/${uid}`, {
|
||||||
|
method: 'PUT',
|
||||||
|
body: JSON.stringify(data)
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function changeUserPassword(uid: string, password: string): Promise<any> {
|
||||||
|
return request<any>(`/api/auth/users/${uid}/password`, {
|
||||||
|
method: 'PUT',
|
||||||
|
body: JSON.stringify({ password })
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function deleteUser(uid: string): Promise<any> {
|
||||||
|
return request<any>(`/api/auth/users/${uid}`, { method: 'DELETE' });
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function logout(): Promise<void> {
|
||||||
|
await request<any>('/api/auth/logout', { method: 'POST' });
|
||||||
|
}
|
||||||
|
|
||||||
// ── Config Export ────────────────────────────────────────────────────
|
// ── Config Export ────────────────────────────────────────────────────
|
||||||
|
|
||||||
export function exportConfigUrl(): string {
|
export function exportConfigUrl(): string {
|
||||||
|
|||||||
@@ -28,3 +28,18 @@ export function clearAuth(): void {
|
|||||||
localStorage.removeItem(TOKEN_KEY);
|
localStorage.removeItem(TOKEN_KEY);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Exchanges the httpOnly OIDC cookie for a JWT token via the server endpoint. */
|
||||||
|
export async function exchangeOidcToken(): Promise<string | null> {
|
||||||
|
try {
|
||||||
|
const res = await fetch('/api/auth/oidc/token', { method: 'POST' });
|
||||||
|
if (!res.ok) return null;
|
||||||
|
const envelope = await res.json();
|
||||||
|
if (envelope.success && envelope.data?.token) {
|
||||||
|
return envelope.data.token;
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -38,6 +38,7 @@ export interface Instance {
|
|||||||
npm_proxy_id: number;
|
npm_proxy_id: number;
|
||||||
status: InstanceStatus;
|
status: InstanceStatus;
|
||||||
port: number;
|
port: number;
|
||||||
|
last_alive_at?: string;
|
||||||
created_at: string;
|
created_at: string;
|
||||||
updated_at: string;
|
updated_at: string;
|
||||||
}
|
}
|
||||||
@@ -101,8 +102,10 @@ export interface Settings {
|
|||||||
notification_url: string;
|
notification_url: string;
|
||||||
npm_url: string;
|
npm_url: string;
|
||||||
npm_email: string;
|
npm_email: string;
|
||||||
npm_password: string;
|
/** Returned by GET as a boolean indicating whether the password is set. */
|
||||||
webhook_secret: string;
|
has_npm_password: boolean;
|
||||||
|
/** Sent on PUT to update the password; never returned by GET. */
|
||||||
|
npm_password?: string;
|
||||||
polling_interval: string;
|
polling_interval: string;
|
||||||
base_volume_path: string;
|
base_volume_path: string;
|
||||||
ssl_certificate_id: number;
|
ssl_certificate_id: number;
|
||||||
|
|||||||
+14
-127
@@ -1,17 +1,17 @@
|
|||||||
<script lang="ts">
|
<script lang="ts">
|
||||||
import '../app.css';
|
import '../app.css';
|
||||||
import type { Snippet } from 'svelte';
|
import type { Snippet } from 'svelte';
|
||||||
import { onDestroy } from 'svelte';
|
import { onMount, onDestroy } from 'svelte';
|
||||||
import { page } from '$app/stores';
|
import { page } from '$app/stores';
|
||||||
import Toast from '$lib/components/Toast.svelte';
|
import Toast from '$lib/components/Toast.svelte';
|
||||||
import ThemeToggle from '$lib/components/ThemeToggle.svelte';
|
import ThemeToggle from '$lib/components/ThemeToggle.svelte';
|
||||||
import LocaleSwitcher from '$lib/components/LocaleSwitcher.svelte';
|
import LocaleSwitcher from '$lib/components/LocaleSwitcher.svelte';
|
||||||
import { IconDashboard, IconProjects, IconDeploy, IconProxies, IconEvents, IconSettings, IconMenu, IconX, IconLogout, IconGlobe } from '$lib/components/icons';
|
import { IconDashboard, IconProjects, IconDeploy, IconSettings, IconMenu, IconX } from '$lib/components/icons';
|
||||||
|
import { goto } from '$app/navigation';
|
||||||
import { connectGlobalEvents, type SSEConnection } from '$lib/sse';
|
import { connectGlobalEvents, type SSEConnection } from '$lib/sse';
|
||||||
import { isAuthenticated, clearAuth } from '$lib/auth';
|
|
||||||
import * as api from '$lib/api';
|
|
||||||
import { instanceStatusStore } from '$lib/stores/instance-status';
|
import { instanceStatusStore } from '$lib/stores/instance-status';
|
||||||
import { resolvedTheme, applyTheme } from '$lib/stores/theme';
|
import { resolvedTheme, applyTheme } from '$lib/stores/theme';
|
||||||
|
import { exchangeOidcToken, setAuthToken } from '$lib/auth';
|
||||||
import { t } from '$lib/i18n';
|
import { t } from '$lib/i18n';
|
||||||
|
|
||||||
interface Props {
|
interface Props {
|
||||||
@@ -24,9 +24,6 @@
|
|||||||
{ href: '/', labelKey: 'nav.dashboard', icon: 'dashboard' },
|
{ href: '/', labelKey: 'nav.dashboard', icon: 'dashboard' },
|
||||||
{ href: '/projects', labelKey: 'nav.projects', icon: 'projects' },
|
{ href: '/projects', labelKey: 'nav.projects', icon: 'projects' },
|
||||||
{ href: '/deploy', labelKey: 'nav.deploy', icon: 'deploy' },
|
{ href: '/deploy', labelKey: 'nav.deploy', icon: 'deploy' },
|
||||||
{ href: '/proxies', labelKey: 'nav.proxies', icon: 'proxies' },
|
|
||||||
{ href: '/dns', labelKey: 'nav.dns', icon: 'globe' },
|
|
||||||
{ href: '/events', labelKey: 'nav.events', icon: 'events' },
|
|
||||||
{ href: '/settings', labelKey: 'nav.settings', icon: 'settings' }
|
{ href: '/settings', labelKey: 'nav.settings', icon: 'settings' }
|
||||||
] as const;
|
] as const;
|
||||||
|
|
||||||
@@ -35,17 +32,8 @@
|
|||||||
return pathname.startsWith(href);
|
return pathname.startsWith(href);
|
||||||
}
|
}
|
||||||
|
|
||||||
import type { DockerHealth } from '$lib/types';
|
|
||||||
|
|
||||||
let sseConnection: SSEConnection | null = null;
|
let sseConnection: SSEConnection | null = null;
|
||||||
let sidebarOpen = $state(false);
|
let sidebarOpen = $state(false);
|
||||||
let dockerHealth = $state<DockerHealth | null>(null);
|
|
||||||
let healthChecked = $state(false);
|
|
||||||
let healthInterval: ReturnType<typeof setInterval> | null = null;
|
|
||||||
let hintsExpanded = $state(false);
|
|
||||||
let sseConnected = $state(true);
|
|
||||||
|
|
||||||
const dockerConnected = $derived(dockerHealth?.connected ?? false);
|
|
||||||
|
|
||||||
// Hide sidebar and chrome on the login page.
|
// Hide sidebar and chrome on the login page.
|
||||||
const isLoginPage = $derived($page.url.pathname === '/login');
|
const isLoginPage = $derived($page.url.pathname === '/login');
|
||||||
@@ -70,20 +58,15 @@
|
|||||||
sidebarOpen = false;
|
sidebarOpen = false;
|
||||||
});
|
});
|
||||||
|
|
||||||
function logout() {
|
onMount(async () => {
|
||||||
clearAuth();
|
// Handle OIDC redirect: exchange the HttpOnly session cookie for a bearer token.
|
||||||
sseConnection?.close();
|
if ($page.url.searchParams.get('oidc') === 'success') {
|
||||||
sseConnection = null;
|
const token = await exchangeOidcToken();
|
||||||
window.location.href = '/login';
|
if (token) {
|
||||||
}
|
setAuthToken(token);
|
||||||
|
goto('/', { replaceState: true });
|
||||||
// Start SSE and health polling when authenticated.
|
}
|
||||||
// Uses $effect to react to route changes (e.g., after login navigation).
|
}
|
||||||
$effect(() => {
|
|
||||||
// Read pathname to re-run on navigation.
|
|
||||||
void $page.url.pathname;
|
|
||||||
|
|
||||||
if (!isAuthenticated() || sseConnection) return;
|
|
||||||
|
|
||||||
sseConnection = connectGlobalEvents({
|
sseConnection = connectGlobalEvents({
|
||||||
onInstanceStatus(payload) {
|
onInstanceStatus(payload) {
|
||||||
@@ -91,33 +74,13 @@
|
|||||||
},
|
},
|
||||||
onDeployStatus(payload) {
|
onDeployStatus(payload) {
|
||||||
instanceStatusStore.notifyDeploy(payload);
|
instanceStatusStore.notifyDeploy(payload);
|
||||||
},
|
|
||||||
onOpen() {
|
|
||||||
sseConnected = true;
|
|
||||||
},
|
|
||||||
onError() {
|
|
||||||
sseConnected = false;
|
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
// Poll Docker health every 30s.
|
|
||||||
async function checkHealth() {
|
|
||||||
try {
|
|
||||||
const h = await api.getHealth();
|
|
||||||
dockerHealth = h.docker;
|
|
||||||
} catch {
|
|
||||||
dockerHealth = { connected: false };
|
|
||||||
}
|
|
||||||
healthChecked = true;
|
|
||||||
}
|
|
||||||
checkHealth();
|
|
||||||
healthInterval = setInterval(checkHealth, 30_000);
|
|
||||||
});
|
});
|
||||||
|
|
||||||
onDestroy(() => {
|
onDestroy(() => {
|
||||||
sseConnection?.close();
|
sseConnection?.close();
|
||||||
sseConnection = null;
|
sseConnection = null;
|
||||||
if (healthInterval) clearInterval(healthInterval);
|
|
||||||
});
|
});
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
@@ -176,12 +139,6 @@
|
|||||||
<IconProjects size={18} class="{active ? 'text-[var(--color-brand-600)]' : 'text-[var(--text-tertiary)] group-hover:text-[var(--text-secondary)]'} transition-colors duration-150" />
|
<IconProjects size={18} class="{active ? 'text-[var(--color-brand-600)]' : 'text-[var(--text-tertiary)] group-hover:text-[var(--text-secondary)]'} transition-colors duration-150" />
|
||||||
{:else if item.icon === 'deploy'}
|
{:else if item.icon === 'deploy'}
|
||||||
<IconDeploy size={18} class="{active ? 'text-[var(--color-brand-600)]' : 'text-[var(--text-tertiary)] group-hover:text-[var(--text-secondary)]'} transition-colors duration-150" />
|
<IconDeploy size={18} class="{active ? 'text-[var(--color-brand-600)]' : 'text-[var(--text-tertiary)] group-hover:text-[var(--text-secondary)]'} transition-colors duration-150" />
|
||||||
{:else if item.icon === 'proxies'}
|
|
||||||
<IconProxies size={18} class="{active ? 'text-[var(--color-brand-600)]' : 'text-[var(--text-tertiary)] group-hover:text-[var(--text-secondary)]'} transition-colors duration-150" />
|
|
||||||
{:else if item.icon === 'globe'}
|
|
||||||
<IconGlobe size={18} class="{active ? 'text-[var(--color-brand-600)]' : 'text-[var(--text-tertiary)] group-hover:text-[var(--text-secondary)]'} transition-colors duration-150" />
|
|
||||||
{:else if item.icon === 'events'}
|
|
||||||
<IconEvents size={18} class="{active ? 'text-[var(--color-brand-600)]' : 'text-[var(--text-tertiary)] group-hover:text-[var(--text-secondary)]'} transition-colors duration-150" />
|
|
||||||
{:else if item.icon === 'settings'}
|
{:else if item.icon === 'settings'}
|
||||||
<IconSettings size={18} class="{active ? 'text-[var(--color-brand-600)]' : 'text-[var(--text-tertiary)] group-hover:text-[var(--text-secondary)]'} transition-colors duration-150" />
|
<IconSettings size={18} class="{active ? 'text-[var(--color-brand-600)]' : 'text-[var(--text-tertiary)] group-hover:text-[var(--text-secondary)]'} transition-colors duration-150" />
|
||||||
{/if}
|
{/if}
|
||||||
@@ -195,74 +152,11 @@
|
|||||||
|
|
||||||
<!-- Footer controls -->
|
<!-- Footer controls -->
|
||||||
<div class="space-y-3 border-t border-[var(--border-primary)] px-4 py-3">
|
<div class="space-y-3 border-t border-[var(--border-primary)] px-4 py-3">
|
||||||
{#if healthChecked}
|
|
||||||
<div class="rounded-md {dockerConnected ? '' : 'bg-red-50 dark:bg-red-950/30'}">
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
class="flex w-full items-center gap-2 px-2 py-1.5 text-xs {dockerConnected ? 'text-emerald-600' : 'text-red-500 cursor-pointer'}"
|
|
||||||
onclick={() => { if (!dockerConnected) hintsExpanded = !hintsExpanded; }}
|
|
||||||
disabled={dockerConnected}
|
|
||||||
>
|
|
||||||
<span class="relative flex h-2 w-2">
|
|
||||||
{#if dockerConnected}
|
|
||||||
<span class="absolute inline-flex h-full w-full animate-ping rounded-full bg-emerald-400 opacity-50"></span>
|
|
||||||
{/if}
|
|
||||||
<span class="relative inline-flex h-2 w-2 rounded-full {dockerConnected ? 'bg-emerald-500' : 'bg-red-500'}"></span>
|
|
||||||
</span>
|
|
||||||
<span class="flex-1 text-left">Docker {dockerConnected ? $t('health.connected') : $t('health.disconnected')}</span>
|
|
||||||
{#if !dockerConnected}
|
|
||||||
<svg class="h-3 w-3 transition-transform {hintsExpanded ? 'rotate-180' : ''}" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><polyline points="6 9 12 15 18 9"/></svg>
|
|
||||||
{/if}
|
|
||||||
</button>
|
|
||||||
{#if !dockerConnected && hintsExpanded && dockerHealth?.hints?.length}
|
|
||||||
<div class="px-2 pb-2">
|
|
||||||
<ul class="space-y-1 text-[11px] text-red-600 dark:text-red-400">
|
|
||||||
{#each dockerHealth.hints as hint}
|
|
||||||
<li class="flex gap-1.5">
|
|
||||||
<span class="mt-0.5 shrink-0">•</span>
|
|
||||||
<span>{hint}</span>
|
|
||||||
</li>
|
|
||||||
{/each}
|
|
||||||
</ul>
|
|
||||||
{#if dockerHealth.error}
|
|
||||||
<details class="mt-1.5">
|
|
||||||
<summary class="text-[10px] text-[var(--text-tertiary)] cursor-pointer">{$t('health.rawError')}</summary>
|
|
||||||
<code class="mt-1 block text-[10px] text-[var(--text-tertiary)] break-all">{dockerHealth.error}</code>
|
|
||||||
</details>
|
|
||||||
{/if}
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
class="mt-2 w-full rounded border border-red-300 dark:border-red-700 px-2 py-1 text-[11px] font-medium text-red-600 dark:text-red-400 hover:bg-red-100 dark:hover:bg-red-900/30 transition-colors"
|
|
||||||
onclick={async () => {
|
|
||||||
try {
|
|
||||||
const h = await api.getHealth();
|
|
||||||
dockerHealth = h.docker;
|
|
||||||
} catch {
|
|
||||||
dockerHealth = { connected: false };
|
|
||||||
}
|
|
||||||
}}
|
|
||||||
>
|
|
||||||
{$t('health.retryNow')}
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
{/if}
|
|
||||||
</div>
|
|
||||||
{/if}
|
|
||||||
<div class="flex items-center justify-between">
|
<div class="flex items-center justify-between">
|
||||||
<ThemeToggle />
|
<ThemeToggle />
|
||||||
<LocaleSwitcher />
|
<LocaleSwitcher />
|
||||||
</div>
|
</div>
|
||||||
<div class="flex items-center justify-between">
|
<p class="text-xs text-[var(--text-tertiary)]">{$t('app.name')} {$t('app.version')}</p>
|
||||||
<p class="text-xs text-[var(--text-tertiary)]">{$t('app.name')} {$t('app.version')}</p>
|
|
||||||
<button
|
|
||||||
onclick={logout}
|
|
||||||
class="inline-flex items-center gap-1.5 rounded-md px-2 py-1 text-xs font-medium text-[var(--text-secondary)] transition-colors hover:bg-[var(--surface-card-hover)] hover:text-[var(--color-danger)]"
|
|
||||||
title={$t('nav.logout')}
|
|
||||||
>
|
|
||||||
<IconLogout size={14} />
|
|
||||||
{$t('nav.logout')}
|
|
||||||
</button>
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
</aside>
|
</aside>
|
||||||
|
|
||||||
@@ -285,13 +179,6 @@
|
|||||||
<span class="text-sm font-bold text-[var(--text-primary)]">{$t('app.name')}</span>
|
<span class="text-sm font-bold text-[var(--text-primary)]">{$t('app.name')}</span>
|
||||||
</header>
|
</header>
|
||||||
|
|
||||||
<!-- SSE connection status banner -->
|
|
||||||
{#if !sseConnected}
|
|
||||||
<div class="bg-amber-500 text-white text-center text-xs py-1 px-4">
|
|
||||||
Real-time connection lost. Reconnecting...
|
|
||||||
</div>
|
|
||||||
{/if}
|
|
||||||
|
|
||||||
<!-- Page content -->
|
<!-- Page content -->
|
||||||
<main class="flex-1 overflow-y-auto">
|
<main class="flex-1 overflow-y-auto">
|
||||||
<div class="mx-auto max-w-7xl px-4 py-6 sm:px-6 sm:py-8">
|
<div class="mx-auto max-w-7xl px-4 py-6 sm:px-6 sm:py-8">
|
||||||
|
|||||||
@@ -3,7 +3,15 @@
|
|||||||
import { t } from '$lib/i18n';
|
import { t } from '$lib/i18n';
|
||||||
import { IconLoader, IconPlus, IconTrash, IconUsers } from '$lib/components/icons';
|
import { IconLoader, IconPlus, IconTrash, IconUsers } from '$lib/components/icons';
|
||||||
import EmptyState from '$lib/components/EmptyState.svelte';
|
import EmptyState from '$lib/components/EmptyState.svelte';
|
||||||
import ConfirmDialog from '$lib/components/ConfirmDialog.svelte';
|
import Skeleton from '$lib/components/Skeleton.svelte';
|
||||||
|
import {
|
||||||
|
getAuthSettings,
|
||||||
|
updateAuthSettings,
|
||||||
|
listUsers as apiListUsers,
|
||||||
|
createUser,
|
||||||
|
deleteUser as apiDeleteUser,
|
||||||
|
ApiError
|
||||||
|
} from '$lib/api';
|
||||||
|
|
||||||
interface AuthSettings {
|
interface AuthSettings {
|
||||||
auth_mode: string;
|
auth_mode: string;
|
||||||
@@ -21,6 +29,7 @@
|
|||||||
created_at: string;
|
created_at: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
let loading = $state(true);
|
||||||
let settings = $state<AuthSettings>({
|
let settings = $state<AuthSettings>({
|
||||||
auth_mode: 'local', oidc_client_id: '', oidc_client_secret: '', oidc_issuer_url: '', oidc_redirect_url: ''
|
auth_mode: 'local', oidc_client_id: '', oidc_client_secret: '', oidc_issuer_url: '', oidc_redirect_url: ''
|
||||||
});
|
});
|
||||||
@@ -34,53 +43,74 @@
|
|||||||
let newEmail = $state('');
|
let newEmail = $state('');
|
||||||
let newRole = $state('viewer');
|
let newRole = $state('viewer');
|
||||||
|
|
||||||
let userDeleteTarget = $state<User | null>(null);
|
onMount(async () => {
|
||||||
|
try {
|
||||||
function getToken(): string { return localStorage.getItem('auth_token') ?? ''; }
|
await Promise.all([loadSettings(), loadUsers()]);
|
||||||
function authHeaders(): Record<string, string> { return { 'Content-Type': 'application/json', Authorization: `Bearer ${getToken()}` }; }
|
} finally {
|
||||||
|
loading = false;
|
||||||
onMount(async () => { await Promise.all([loadSettings(), loadUsers()]); });
|
}
|
||||||
|
});
|
||||||
|
|
||||||
async function loadSettings() {
|
async function loadSettings() {
|
||||||
try { const res = await fetch('/api/auth/settings', { headers: authHeaders() }); const envelope = await res.json(); if (envelope.success) settings = envelope.data; }
|
try {
|
||||||
catch (err: unknown) { error = err instanceof Error ? err.message : $t('settingsAuth.loadFailed'); }
|
settings = await getAuthSettings();
|
||||||
|
} catch (err: unknown) {
|
||||||
|
error = err instanceof ApiError ? err.message : $t('settingsAuth.loadFailed');
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async function loadUsers() {
|
async function loadUsers() {
|
||||||
try { const res = await fetch('/api/auth/users', { headers: authHeaders() }); const envelope = await res.json(); if (envelope.success) users = envelope.data ?? []; }
|
try {
|
||||||
catch (err: unknown) { error = err instanceof Error ? err.message : $t('settingsAuth.loadFailed'); }
|
users = (await apiListUsers()) ?? [];
|
||||||
|
} catch (err: unknown) {
|
||||||
|
error = err instanceof ApiError ? err.message : $t('settingsAuth.loadFailed');
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async function saveSettings() {
|
async function saveSettings() {
|
||||||
saving = true; message = ''; error = '';
|
saving = true; message = ''; error = '';
|
||||||
try {
|
try {
|
||||||
const res = await fetch('/api/auth/settings', { method: 'PUT', headers: authHeaders(), body: JSON.stringify(settings) });
|
await updateAuthSettings(settings);
|
||||||
const envelope = await res.json();
|
message = $t('settingsAuth.saved');
|
||||||
if (envelope.success) message = $t('settingsAuth.saved'); else error = envelope.error ?? $t('settingsAuth.saveFailed');
|
} catch (err: unknown) {
|
||||||
} catch (err: unknown) { error = err instanceof Error ? err.message : $t('settingsAuth.networkError'); } finally { saving = false; }
|
error = err instanceof ApiError ? err.message : $t('settingsAuth.saveFailed');
|
||||||
|
} finally {
|
||||||
|
saving = false;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async function addUser() {
|
async function addUser() {
|
||||||
if (!newUsername || !newPassword) { error = $t('settingsAuth.usernameRequired'); return; }
|
if (!newUsername || !newPassword) { error = $t('settingsAuth.usernameRequired'); return; }
|
||||||
try {
|
try {
|
||||||
const res = await fetch('/api/auth/users', { method: 'POST', headers: authHeaders(), body: JSON.stringify({ username: newUsername, password: newPassword, email: newEmail, role: newRole }) });
|
await createUser({ username: newUsername, password: newPassword, email: newEmail, role: newRole });
|
||||||
const envelope = await res.json();
|
newUsername = ''; newPassword = ''; newEmail = ''; newRole = 'viewer';
|
||||||
if (envelope.success) { newUsername = ''; newPassword = ''; newEmail = ''; newRole = 'viewer'; await loadUsers(); message = $t('settingsAuth.userCreated'); }
|
await loadUsers();
|
||||||
else error = envelope.error ?? $t('settingsAuth.createFailed');
|
message = $t('settingsAuth.userCreated');
|
||||||
} catch (err: unknown) { error = err instanceof Error ? err.message : $t('settingsAuth.networkError'); }
|
} catch (err: unknown) {
|
||||||
|
error = err instanceof ApiError ? err.message : $t('settingsAuth.createFailed');
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async function deleteUser(id: string) {
|
async function handleDeleteUser(id: string) {
|
||||||
|
if (!confirm($t('settingsAuth.deleteConfirm'))) return;
|
||||||
try {
|
try {
|
||||||
const res = await fetch(`/api/auth/users/${id}`, { method: 'DELETE', headers: authHeaders() });
|
await apiDeleteUser(id);
|
||||||
const envelope = await res.json();
|
await loadUsers();
|
||||||
if (envelope.success) { await loadUsers(); message = $t('settingsAuth.userDeleted'); }
|
message = $t('settingsAuth.userDeleted');
|
||||||
else error = envelope.error ?? $t('settingsAuth.deleteFailed');
|
} catch (err: unknown) {
|
||||||
} catch (err: unknown) { error = err instanceof Error ? err.message : $t('settingsAuth.networkError'); }
|
error = err instanceof ApiError ? err.message : $t('settingsAuth.deleteFailed');
|
||||||
|
}
|
||||||
}
|
}
|
||||||
</script>
|
</script>
|
||||||
|
|
||||||
<div class="space-y-6">
|
<div class="space-y-6">
|
||||||
|
{#if loading}
|
||||||
|
<div class="space-y-4">
|
||||||
|
<Skeleton height="2rem" width="12rem" />
|
||||||
|
<Skeleton height="6rem" />
|
||||||
|
<Skeleton height="12rem" />
|
||||||
|
</div>
|
||||||
|
{:else}
|
||||||
<div>
|
<div>
|
||||||
<h2 class="text-lg font-semibold text-[var(--text-primary)]">{$t('settingsAuth.title')}</h2>
|
<h2 class="text-lg font-semibold text-[var(--text-primary)]">{$t('settingsAuth.title')}</h2>
|
||||||
<p class="text-sm text-[var(--text-secondary)]">{$t('settingsAuth.description')}</p>
|
<p class="text-sm text-[var(--text-secondary)]">{$t('settingsAuth.description')}</p>
|
||||||
@@ -167,7 +197,7 @@
|
|||||||
</td>
|
</td>
|
||||||
<td class="px-4 py-2.5 text-sm text-[var(--text-secondary)]">{user.created_at}</td>
|
<td class="px-4 py-2.5 text-sm text-[var(--text-secondary)]">{user.created_at}</td>
|
||||||
<td class="px-4 py-2.5 text-right">
|
<td class="px-4 py-2.5 text-right">
|
||||||
<button onclick={() => { userDeleteTarget = user; }} class="rounded-lg p-1.5 text-[var(--text-tertiary)] hover:bg-red-50 hover:text-red-600 transition-colors">
|
<button onclick={() => handleDeleteUser(user.id)} class="rounded-lg p-1.5 text-[var(--text-tertiary)] hover:bg-red-50 hover:text-red-600 transition-colors">
|
||||||
<IconTrash size={16} />
|
<IconTrash size={16} />
|
||||||
</button>
|
</button>
|
||||||
</td>
|
</td>
|
||||||
@@ -199,18 +229,5 @@
|
|||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
{/if}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<ConfirmDialog
|
|
||||||
open={userDeleteTarget !== null}
|
|
||||||
title={$t('settingsAuth.deleteUserTitle')}
|
|
||||||
message={$t('settingsAuth.deleteConfirm', { username: userDeleteTarget?.username ?? '' })}
|
|
||||||
confirmLabel={$t('common.delete')}
|
|
||||||
confirmVariant="danger"
|
|
||||||
onconfirm={async () => {
|
|
||||||
const user = userDeleteTarget;
|
|
||||||
userDeleteTarget = null;
|
|
||||||
if (user) await deleteUser(user.id);
|
|
||||||
}}
|
|
||||||
oncancel={() => { userDeleteTarget = null; }}
|
|
||||||
/>
|
|
||||||
|
|||||||
Reference in New Issue
Block a user