feat: implement local caching for vCon data
Persist clients, storage stats, and file lists in local cache to improve initial load performance. Added breadcrumb navigation to the AdminPageHeader.
This commit is contained in:
1 parent
b42029f67d
commit
1a1c19d7bb
25 files changed
+791
-241
No files matched your search
@@ -0,0 +1,134 @@
|
|||||||
|
import {
|
||||||
|
createAdminSessionToken,
|
||||||
|
getAdminSessionPayload,
|
||||||
|
getSessionCookieOptions,
|
||||||
|
} from "@/core/auth/adminSession";
|
||||||
|
import {
|
||||||
|
getAdminAccountInfo,
|
||||||
|
updateAdminAccount,
|
||||||
|
} from "@/core/auth/adminUsers";
|
||||||
|
import { NextRequest, NextResponse } from "next/server";
|
||||||
|
|
||||||
|
const SESSION_COOKIE = "datastack_admin_session";
|
||||||
|
const SESSION_SECONDS = 8 * 60 * 60;
|
||||||
|
|
||||||
|
function validEmail(email: string) {
|
||||||
|
return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function GET(request: NextRequest) {
|
||||||
|
const sessionSecret =
|
||||||
|
process.env.DATASTACK_ADMIN_SESSION_SECRET ||
|
||||||
|
"datastack-admin-session-default-secret-32-chars";
|
||||||
|
const token = request.cookies.get(SESSION_COOKIE)?.value || "";
|
||||||
|
const session = await getAdminSessionPayload(token, sessionSecret);
|
||||||
|
|
||||||
|
if (!session) {
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: "Authentication required." },
|
||||||
|
{ status: 401 },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const account = await getAdminAccountInfo(session.email);
|
||||||
|
return NextResponse.json({
|
||||||
|
profile: {
|
||||||
|
email: account.email,
|
||||||
|
role: "Owner",
|
||||||
|
storageMode: account.storageMode,
|
||||||
|
createdAt: account.createdAt,
|
||||||
|
sessionExpiresAt: new Date(session.expiresAt).toISOString(),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function PUT(request: NextRequest) {
|
||||||
|
const sessionSecret =
|
||||||
|
process.env.DATASTACK_ADMIN_SESSION_SECRET ||
|
||||||
|
"datastack-admin-session-default-secret-32-chars";
|
||||||
|
const token = request.cookies.get(SESSION_COOKIE)?.value || "";
|
||||||
|
const session = await getAdminSessionPayload(token, sessionSecret);
|
||||||
|
|
||||||
|
if (!session) {
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: "Authentication required." },
|
||||||
|
{ status: 401 },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const body = await request.json();
|
||||||
|
const nextEmail =
|
||||||
|
typeof body.email === "string"
|
||||||
|
? body.email.trim().toLowerCase()
|
||||||
|
: session.email;
|
||||||
|
const currentPassword =
|
||||||
|
typeof body.currentPassword === "string" ? body.currentPassword : "";
|
||||||
|
const newPassword =
|
||||||
|
typeof body.newPassword === "string" ? body.newPassword : "";
|
||||||
|
|
||||||
|
if (!validEmail(nextEmail)) {
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: "Enter a valid email address." },
|
||||||
|
{ status: 400 },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!currentPassword) {
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: "Current password is required to save changes." },
|
||||||
|
{ status: 400 },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (newPassword && (newPassword.length < 8 || newPassword.length > 256)) {
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: "New password must be between 8 and 256 characters." },
|
||||||
|
{ status: 400 },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const account = await getAdminAccountInfo(session.email);
|
||||||
|
const result = await updateAdminAccount({
|
||||||
|
currentEmail: account.email,
|
||||||
|
currentPassword,
|
||||||
|
nextEmail,
|
||||||
|
nextPassword: newPassword || undefined,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!result.ok) {
|
||||||
|
return NextResponse.json({ error: result.error }, { status: 401 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const expiresAt = Date.now() + SESSION_SECONDS * 1000;
|
||||||
|
const nextToken = await createAdminSessionToken(
|
||||||
|
result.email,
|
||||||
|
sessionSecret,
|
||||||
|
expiresAt,
|
||||||
|
);
|
||||||
|
|
||||||
|
const response = NextResponse.json({
|
||||||
|
success: true,
|
||||||
|
profile: {
|
||||||
|
email: result.email,
|
||||||
|
role: "Owner",
|
||||||
|
storageMode: account.storageMode,
|
||||||
|
createdAt: account.createdAt,
|
||||||
|
sessionExpiresAt: new Date(expiresAt).toISOString(),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
response.cookies.set(
|
||||||
|
SESSION_COOKIE,
|
||||||
|
nextToken,
|
||||||
|
getSessionCookieOptions(request, SESSION_SECONDS),
|
||||||
|
);
|
||||||
|
|
||||||
|
return response;
|
||||||
|
} catch {
|
||||||
|
return NextResponse.json(
|
||||||
|
{ error: "Unable to update profile." },
|
||||||
|
{ status: 400 },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -8,26 +8,26 @@ import { NewClientModal } from '@/components/sections/NewClientModal';
|
|||||||
import { Button } from '@/components/ui/Button';
|
import { Button } from '@/components/ui/Button';
|
||||||
import { StatStrip } from '@/components/ui/StatStrip';
|
import { StatStrip } from '@/components/ui/StatStrip';
|
||||||
import { useToast } from '@/components/ui/Toast';
|
import { useToast } from '@/components/ui/Toast';
|
||||||
|
import { getCached, setCached } from '@/lib/vconCache';
|
||||||
import { useCallback, useEffect, useMemo, useState } from 'react';
|
import { useCallback, useEffect, useMemo, useState } from 'react';
|
||||||
|
|
||||||
export default function ClientsPage() {
|
export default function ClientsPage() {
|
||||||
const { error } = useToast();
|
const { error } = useToast();
|
||||||
const [modalOpen, setModalOpen] = useState(false);
|
const [modalOpen, setModalOpen] = useState(false);
|
||||||
const [clients, setClients] = useState<ClientItem[]>([]);
|
const [clients, setClients] = useState<ClientItem[]>(() => getCached<ClientItem[]>('vcon:clients', []));
|
||||||
const [search, setSearch] = useState('');
|
const [search, setSearch] = useState('');
|
||||||
const [statusFilter, setStatusFilter] = useState<ClientStatusFilter>('all');
|
const [statusFilter, setStatusFilter] = useState<ClientStatusFilter>('all');
|
||||||
const [now, setNow] = useState(0);
|
const [now, setNow] = useState(() => Date.now());
|
||||||
|
|
||||||
const fetchClients = useCallback(async () => {
|
const fetchClients = useCallback(async () => {
|
||||||
const response = await fetch('/api/clients');
|
const response = await fetch('/api/clients');
|
||||||
if (!response.ok) throw new Error('Unable to load clients');
|
if (!response.ok) throw new Error('Unable to load clients');
|
||||||
const data = await response.json();
|
const data = await response.json();
|
||||||
setClients(data.clients || []);
|
setClients(setCached('vcon:clients', data.clients || []));
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
fetchClients().catch(() => {
|
fetchClients().catch(() => {
|
||||||
setClients([]);
|
|
||||||
error('Unable to load clients', 'Could not fetch registered clients.');
|
error('Unable to load clients', 'Could not fetch registered clients.');
|
||||||
});
|
});
|
||||||
}, [error, fetchClients]);
|
}, [error, fetchClients]);
|
||||||
|
|||||||
@@ -0,0 +1,5 @@
|
|||||||
|
import { ProfileWorkspace } from '@/components/sections/ProfileWorkspace';
|
||||||
|
|
||||||
|
export default function ProfilePage() {
|
||||||
|
return <ProfileWorkspace />;
|
||||||
|
}
|
||||||
+11
-5
@@ -7,12 +7,16 @@ import { CodeBlock } from '@/components/ui/CodeBlock';
|
|||||||
import { Select } from '@/components/ui/Input';
|
import { Select } from '@/components/ui/Input';
|
||||||
import { Panel } from '@/components/ui/Panel';
|
import { Panel } from '@/components/ui/Panel';
|
||||||
import { useToast } from '@/components/ui/Toast';
|
import { useToast } from '@/components/ui/Toast';
|
||||||
|
import { getCached, setCached } from '@/lib/vconCache';
|
||||||
import { useEffect, useState } from 'react';
|
import { useEffect, useState } from 'react';
|
||||||
|
|
||||||
export default function SdkGuidePage() {
|
export default function SdkGuidePage() {
|
||||||
const { success } = useToast();
|
const { success } = useToast();
|
||||||
const [clients, setClients] = useState<any[]>([]);
|
const [clients, setClients] = useState<any[]>(() => getCached<any[]>('vcon:clients', []));
|
||||||
const [selectedClientId, setSelectedClientId] = useState<string>('');
|
const [selectedClientId, setSelectedClientId] = useState<string>(() => {
|
||||||
|
const cached = getCached<any[]>('vcon:clients', []);
|
||||||
|
return cached[0]?.clientId ?? '';
|
||||||
|
});
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
async function loadClients() {
|
async function loadClients() {
|
||||||
@@ -20,10 +24,10 @@ export default function SdkGuidePage() {
|
|||||||
const res = await fetch('/api/clients');
|
const res = await fetch('/api/clients');
|
||||||
if (res.ok) {
|
if (res.ok) {
|
||||||
const data = await res.json();
|
const data = await res.json();
|
||||||
const list = data.clients || [];
|
const list = setCached('vcon:clients', data.clients || []);
|
||||||
setClients(list);
|
setClients(list);
|
||||||
if (list.length > 0) {
|
if (list.length > 0) {
|
||||||
setSelectedClientId(list[0].clientId);
|
setSelectedClientId((prev) => prev || list[0].clientId);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} catch {
|
} catch {
|
||||||
@@ -65,7 +69,7 @@ if client.connect():
|
|||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<section className="flex w-full flex-col gap-2.5">
|
<section className="w-full">
|
||||||
<AdminPageHeader
|
<AdminPageHeader
|
||||||
title="Python SDK"
|
title="Python SDK"
|
||||||
actions={
|
actions={
|
||||||
@@ -80,6 +84,7 @@ if client.connect():
|
|||||||
}
|
}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
|
<div className="flex max-w-[860px] flex-col gap-2.5">
|
||||||
<Card compact className="flex items-center justify-between bg-[var(--surface)] px-3 py-2 font-mono text-[11.5px]">
|
<Card compact className="flex items-center justify-between bg-[var(--surface)] px-3 py-2 font-mono text-[11.5px]">
|
||||||
<span className="text-[var(--accent)]">pip install ./sdk-python</span>
|
<span className="text-[var(--accent)]">pip install ./sdk-python</span>
|
||||||
<Button
|
<Button
|
||||||
@@ -112,6 +117,7 @@ if client.connect():
|
|||||||
>
|
>
|
||||||
<CodeBlock>{pythonSnippet}</CodeBlock>
|
<CodeBlock>{pythonSnippet}</CodeBlock>
|
||||||
</Panel>
|
</Panel>
|
||||||
|
</div>
|
||||||
</section>
|
</section>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -6,12 +6,16 @@ import { CodeBlock } from '@/components/ui/CodeBlock';
|
|||||||
import { Select, Textarea } from '@/components/ui/Input';
|
import { Select, Textarea } from '@/components/ui/Input';
|
||||||
import { Panel } from '@/components/ui/Panel';
|
import { Panel } from '@/components/ui/Panel';
|
||||||
import { useToast } from '@/components/ui/Toast';
|
import { useToast } from '@/components/ui/Toast';
|
||||||
|
import { getCached, setCached } from '@/lib/vconCache';
|
||||||
import { useEffect, useState } from 'react';
|
import { useEffect, useState } from 'react';
|
||||||
|
|
||||||
export default function SimulatorPage() {
|
export default function SimulatorPage() {
|
||||||
const { success, error } = useToast();
|
const { success, error } = useToast();
|
||||||
const [clients, setClients] = useState<any[]>([]);
|
const [clients, setClients] = useState<any[]>(() => getCached<any[]>('vcon:clients', []));
|
||||||
const [selectedClient, setSelectedClient] = useState<string>('');
|
const [selectedClient, setSelectedClient] = useState<string>(() => {
|
||||||
|
const cached = getCached<any[]>('vcon:clients', []);
|
||||||
|
return cached[0]?.clientId ?? '';
|
||||||
|
});
|
||||||
const [payloadText, setPayloadText] = useState<string>(
|
const [payloadText, setPayloadText] = useState<string>(
|
||||||
JSON.stringify(
|
JSON.stringify(
|
||||||
{
|
{
|
||||||
@@ -34,9 +38,9 @@ export default function SimulatorPage() {
|
|||||||
const res = await fetch('/api/clients');
|
const res = await fetch('/api/clients');
|
||||||
if (res.ok) {
|
if (res.ok) {
|
||||||
const data = await res.json();
|
const data = await res.json();
|
||||||
const list = data.clients || [];
|
const list = setCached('vcon:clients', data.clients || []);
|
||||||
setClients(list);
|
setClients(list);
|
||||||
if (list.length > 0) setSelectedClient(list[0].clientId);
|
if (list.length > 0) setSelectedClient((prev) => prev || list[0].clientId);
|
||||||
}
|
}
|
||||||
} catch {
|
} catch {
|
||||||
// ignore
|
// ignore
|
||||||
@@ -136,7 +140,7 @@ export default function SimulatorPage() {
|
|||||||
}
|
}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<div className="grid grid-cols-1 gap-2.5 xl:grid-cols-2">
|
<div className="grid grid-cols-1 gap-2.5 lg:grid-cols-2">
|
||||||
<Panel title="Payload" bodyClassName="flex flex-col gap-2.5 p-3">
|
<Panel title="Payload" bodyClassName="flex flex-col gap-2.5 p-3">
|
||||||
<Select
|
<Select
|
||||||
compact
|
compact
|
||||||
|
|||||||
@@ -15,12 +15,13 @@ import {
|
|||||||
TableWrap,
|
TableWrap,
|
||||||
} from '@/components/ui/Table';
|
} from '@/components/ui/Table';
|
||||||
import { useToast } from '@/components/ui/Toast';
|
import { useToast } from '@/components/ui/Toast';
|
||||||
|
import { getCached, setCached } from '@/lib/vconCache';
|
||||||
import { useCallback, useEffect, useState } from 'react';
|
import { useCallback, useEffect, useState } from 'react';
|
||||||
|
|
||||||
export default function StoragePage() {
|
export default function StoragePage() {
|
||||||
const { success, error } = useToast();
|
const { success, error } = useToast();
|
||||||
const [stats, setStats] = useState<any>(null);
|
const [stats, setStats] = useState<any>(() => getCached<any>('vcon:storage-stats', null));
|
||||||
const [files, setFiles] = useState<any[]>([]);
|
const [files, setFiles] = useState<any[]>(() => getCached<any[]>('vcon:storage-files', []));
|
||||||
const [flushing, setFlushing] = useState(false);
|
const [flushing, setFlushing] = useState(false);
|
||||||
|
|
||||||
const fetchStorageData = useCallback(async () => {
|
const fetchStorageData = useCallback(async () => {
|
||||||
@@ -28,8 +29,8 @@ export default function StoragePage() {
|
|||||||
const res = await fetch('/api/storage');
|
const res = await fetch('/api/storage');
|
||||||
if (!res.ok) throw new Error('Unable to load storage partitions');
|
if (!res.ok) throw new Error('Unable to load storage partitions');
|
||||||
const data = await res.json();
|
const data = await res.json();
|
||||||
setStats(data.stats);
|
setStats(setCached('vcon:storage-stats', data.stats));
|
||||||
setFiles(data.files || []);
|
setFiles(setCached('vcon:storage-files', data.files || []));
|
||||||
} catch {
|
} catch {
|
||||||
error('Storage load failed', 'Could not load storage partitions.');
|
error('Storage load failed', 'Could not load storage partitions.');
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,3 +1,4 @@
|
|||||||
|
import Link from 'next/link';
|
||||||
import React from 'react';
|
import React from 'react';
|
||||||
|
|
||||||
interface AdminPageHeaderProps {
|
interface AdminPageHeaderProps {
|
||||||
@@ -7,8 +8,21 @@ interface AdminPageHeaderProps {
|
|||||||
|
|
||||||
export function AdminPageHeader({ title, actions }: AdminPageHeaderProps) {
|
export function AdminPageHeader({ title, actions }: AdminPageHeaderProps) {
|
||||||
return (
|
return (
|
||||||
<header className="mb-3 flex flex-wrap items-center justify-between gap-2">
|
<header className="mb-3 flex min-h-8 flex-wrap items-center justify-between gap-2 border-b border-[var(--border)] pb-2.5">
|
||||||
<h1 className="text-[14px] font-medium tracking-tight text-[var(--text)]">{title}</h1>
|
<div className="flex min-w-0 items-center gap-1.5">
|
||||||
|
<Link
|
||||||
|
href="/vcon/dashboard"
|
||||||
|
className="text-[11.5px] text-[var(--text-faint)] hover:text-[var(--text-muted)]"
|
||||||
|
>
|
||||||
|
Console
|
||||||
|
</Link>
|
||||||
|
<span className="text-[11px] text-[var(--border-strong)]" aria-hidden="true">
|
||||||
|
/
|
||||||
|
</span>
|
||||||
|
<h1 className="truncate text-[13.5px] font-medium tracking-tight text-[var(--text)]">
|
||||||
|
{title}
|
||||||
|
</h1>
|
||||||
|
</div>
|
||||||
{actions && <div className="flex items-center gap-1.5">{actions}</div>}
|
{actions && <div className="flex items-center gap-1.5">{actions}</div>}
|
||||||
</header>
|
</header>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -1,6 +1,5 @@
|
|||||||
'use client';
|
'use client';
|
||||||
|
|
||||||
import { cn } from '@/lib/utils';
|
|
||||||
import React, { useState } from 'react';
|
import React, { useState } from 'react';
|
||||||
import { Footer } from './Footer';
|
import { Footer } from './Footer';
|
||||||
import { Navbar } from './Navbar';
|
import { Navbar } from './Navbar';
|
||||||
@@ -17,34 +16,40 @@ export const MainLayout: React.FC<MainLayoutProps> = ({
|
|||||||
}) => {
|
}) => {
|
||||||
const [sidebarOpen, setSidebarOpen] = useState(false);
|
const [sidebarOpen, setSidebarOpen] = useState(false);
|
||||||
|
|
||||||
|
if (showSidebar) {
|
||||||
return (
|
return (
|
||||||
<div className="min-h-dvh flex flex-col bg-[var(--bg-main)] text-[var(--text)] antialiased">
|
<div className="min-h-dvh bg-[var(--bg-main)] text-[var(--text)] antialiased md:grid md:grid-cols-[184px_1fr]">
|
||||||
<Navbar
|
|
||||||
showSidebarToggle={showSidebar}
|
|
||||||
onToggleSidebar={() => setSidebarOpen((prev) => !prev)}
|
|
||||||
/>
|
|
||||||
|
|
||||||
<div className="flex-1 flex min-h-0 min-w-0 overflow-hidden">
|
|
||||||
{showSidebar && (
|
|
||||||
<Sidebar
|
<Sidebar
|
||||||
isOpen={sidebarOpen}
|
isOpen={sidebarOpen}
|
||||||
onClose={() => setSidebarOpen(false)}
|
onClose={() => setSidebarOpen(false)}
|
||||||
/>
|
/>
|
||||||
)}
|
<div className="flex min-h-dvh min-w-0 flex-col">
|
||||||
<main className="flex-1 min-h-0 overflow-y-auto flex flex-col min-w-0">
|
<Navbar
|
||||||
<div className={cn(
|
showSidebarToggle={true}
|
||||||
'flex-1 min-w-0 w-full mx-auto',
|
onToggleSidebar={() => setSidebarOpen((prev) => !prev)}
|
||||||
showSidebar
|
/>
|
||||||
? 'max-w-[var(--console-width)] px-3.5 py-3 sm:px-5 sm:py-4'
|
<main className="flex flex-1 min-w-0 flex-col">
|
||||||
: 'max-w-[var(--container-width)] px-6 py-0'
|
<div className="w-full max-w-[var(--console-width)] flex-1 px-3.5 py-3 sm:px-5 sm:py-3.5">
|
||||||
)}>
|
|
||||||
{children}
|
{children}
|
||||||
</div>
|
</div>
|
||||||
<Footer isAdmin={showSidebar} />
|
<Footer isAdmin={true} />
|
||||||
</main>
|
</main>
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="min-h-dvh flex flex-col bg-[var(--bg-main)] text-[var(--text)] antialiased">
|
||||||
|
<Navbar showSidebarToggle={false} />
|
||||||
|
<main className="flex-1 flex flex-col min-w-0">
|
||||||
|
<div className="flex-1 min-w-0 w-full mx-auto max-w-[var(--container-width)] px-6 py-0">
|
||||||
|
{children}
|
||||||
|
</div>
|
||||||
|
<Footer isAdmin={false} />
|
||||||
|
</main>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
};
|
};
|
||||||
|
|
||||||
export default MainLayout;
|
export default MainLayout;
|
||||||
@@ -10,6 +10,18 @@ interface NavbarProps {
|
|||||||
showSidebarToggle?: boolean;
|
showSidebarToggle?: boolean;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
const VCON_LABELS: Record<string, string> = {
|
||||||
|
'/vcon/dashboard': 'Dashboard',
|
||||||
|
'/vcon/data': 'Events',
|
||||||
|
'/vcon/clients': 'Clients',
|
||||||
|
'/vcon/export': 'Export',
|
||||||
|
'/vcon/storage': 'Storage',
|
||||||
|
'/vcon/sdk': 'Python SDK',
|
||||||
|
'/vcon/simulator': 'Simulator',
|
||||||
|
'/vcon/profile': 'Profile',
|
||||||
|
'/vcon/settings': 'Settings',
|
||||||
|
};
|
||||||
|
|
||||||
export const Navbar: React.FC<NavbarProps> = ({
|
export const Navbar: React.FC<NavbarProps> = ({
|
||||||
onToggleSidebar,
|
onToggleSidebar,
|
||||||
showSidebarToggle = false,
|
showSidebarToggle = false,
|
||||||
@@ -34,24 +46,44 @@ export const Navbar: React.FC<NavbarProps> = ({
|
|||||||
};
|
};
|
||||||
|
|
||||||
const isVcon = pathname?.startsWith('/vcon');
|
const isVcon = pathname?.startsWith('/vcon');
|
||||||
|
const currentSectionLabel = (pathname && VCON_LABELS[pathname]) || 'Console';
|
||||||
|
|
||||||
|
if (showSidebarToggle && isVcon) {
|
||||||
return (
|
return (
|
||||||
<header className="h-11 shrink-0 bg-[var(--bg-activity)] border-b border-[var(--border)] px-3.5 sm:px-5 flex items-center justify-between gap-4 z-40 select-none">
|
<header className="sticky top-0 z-30 flex h-10 shrink-0 items-center justify-between gap-3 border-b border-[var(--border)] bg-[var(--surface)] px-3.5 select-none md:hidden">
|
||||||
{/* Left: Mobile hamburger + Brand */}
|
<div className="flex min-w-0 items-center gap-2">
|
||||||
<div className="flex items-center gap-2.5 min-w-0">
|
|
||||||
{showSidebarToggle && (
|
|
||||||
<Button
|
<Button
|
||||||
type="button"
|
type="button"
|
||||||
variant="icon"
|
variant="icon"
|
||||||
size="icon"
|
size="icon"
|
||||||
icon="Menu"
|
icon="Menu"
|
||||||
onClick={onToggleSidebar}
|
onClick={onToggleSidebar}
|
||||||
className="lg:hidden h-7 w-7 shrink-0 border border-[var(--border)] bg-[var(--bg-elevated)]"
|
className="h-6.5 w-6.5 shrink-0 border border-[var(--border)] bg-[var(--surface-2)]"
|
||||||
aria-label="Toggle Navigation"
|
aria-label="Toggle Navigation"
|
||||||
title="Toggle Navigation"
|
title="Toggle Navigation"
|
||||||
/>
|
/>
|
||||||
)}
|
<span className="truncate text-[12px] font-medium text-[var(--text)]">
|
||||||
|
{currentSectionLabel}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="icon"
|
||||||
|
size="icon"
|
||||||
|
icon={theme === 'dark' ? 'Sun' : 'Moon'}
|
||||||
|
onClick={toggleTheme}
|
||||||
|
aria-label="Toggle Theme"
|
||||||
|
title="Toggle Theme"
|
||||||
|
className="h-6.5 w-6.5 border border-[var(--border)] bg-[var(--surface-2)]"
|
||||||
|
/>
|
||||||
|
</header>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<header className="h-11 shrink-0 bg-[var(--bg-activity)] border-b border-[var(--border)] px-3.5 sm:px-5 flex items-center justify-between gap-4 z-40 select-none">
|
||||||
|
<div className="flex items-center gap-2.5 min-w-0">
|
||||||
<Link href="/" className="flex items-center gap-1.5 min-w-0 text-[13px] font-medium whitespace-nowrap shrink-0">
|
<Link href="/" className="flex items-center gap-1.5 min-w-0 text-[13px] font-medium whitespace-nowrap shrink-0">
|
||||||
<span className="grid h-3.5 w-3.5 shrink-0 place-items-center bg-[var(--accent)]">
|
<span className="grid h-3.5 w-3.5 shrink-0 place-items-center bg-[var(--accent)]">
|
||||||
<span className="h-1.5 w-1.5 bg-[var(--bg)]" />
|
<span className="h-1.5 w-1.5 bg-[var(--bg)]" />
|
||||||
@@ -62,44 +94,12 @@ export const Navbar: React.FC<NavbarProps> = ({
|
|||||||
</Link>
|
</Link>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Middle: Links */}
|
|
||||||
<nav className="hidden sm:flex items-center gap-5 text-[12px]">
|
<nav className="hidden sm:flex items-center gap-5 text-[12px]">
|
||||||
{isVcon ? (
|
|
||||||
<>
|
|
||||||
<Link href="/" className="text-[var(--text-muted)] hover:text-[var(--text)] whitespace-nowrap shrink-0">
|
|
||||||
Overview
|
|
||||||
</Link>
|
|
||||||
<Link
|
|
||||||
href="/vcon/dashboard"
|
|
||||||
className={`px-2 py-1.5 transition-colors border-b-2 whitespace-nowrap shrink-0 ${
|
|
||||||
pathname !== '/vcon/export'
|
|
||||||
? 'border-[var(--accent)] text-[var(--text)] font-medium'
|
|
||||||
: 'border-transparent text-[var(--text-muted)] hover:text-[var(--text)]'
|
|
||||||
}`}
|
|
||||||
>
|
|
||||||
Console
|
|
||||||
</Link>
|
|
||||||
<Link
|
|
||||||
href="/vcon/export"
|
|
||||||
className={`px-2 py-1.5 transition-colors border-b-2 whitespace-nowrap shrink-0 ${
|
|
||||||
pathname === '/vcon/export'
|
|
||||||
? 'border-[var(--accent)] text-[var(--text)] font-medium'
|
|
||||||
: 'border-transparent text-[var(--text-muted)] hover:text-[var(--text)]'
|
|
||||||
}`}
|
|
||||||
>
|
|
||||||
Export
|
|
||||||
</Link>
|
|
||||||
</>
|
|
||||||
) : (
|
|
||||||
<>
|
|
||||||
<Link href="#features" className="text-[var(--text-muted)] hover:text-[var(--text)] whitespace-nowrap shrink-0">Features</Link>
|
<Link href="#features" className="text-[var(--text-muted)] hover:text-[var(--text)] whitespace-nowrap shrink-0">Features</Link>
|
||||||
<Link href="#sdk" className="text-[var(--text-muted)] hover:text-[var(--text)] whitespace-nowrap shrink-0">SDK</Link>
|
<Link href="#sdk" className="text-[var(--text-muted)] hover:text-[var(--text)] whitespace-nowrap shrink-0">SDK</Link>
|
||||||
<Link href="#about" className="text-[var(--text-muted)] hover:text-[var(--text)] whitespace-nowrap shrink-0">About</Link>
|
<Link href="#about" className="text-[var(--text-muted)] hover:text-[var(--text)] whitespace-nowrap shrink-0">About</Link>
|
||||||
</>
|
|
||||||
)}
|
|
||||||
</nav>
|
</nav>
|
||||||
|
|
||||||
{/* Right: Theme switcher or public CTA */}
|
|
||||||
<div className="flex items-center gap-2 shrink-0">
|
<div className="flex items-center gap-2 shrink-0">
|
||||||
<Button
|
<Button
|
||||||
type="button"
|
type="button"
|
||||||
@@ -112,13 +112,11 @@ export const Navbar: React.FC<NavbarProps> = ({
|
|||||||
className="h-7 w-7 border border-[var(--border)] bg-[var(--bg-elevated)]"
|
className="h-7 w-7 border border-[var(--border)] bg-[var(--bg-elevated)]"
|
||||||
/>
|
/>
|
||||||
|
|
||||||
{!isVcon && (
|
<Link href="/vcon/dashboard">
|
||||||
<Link href="#sdk">
|
|
||||||
<Button size="xs" variant="primary">
|
<Button size="xs" variant="primary">
|
||||||
SDK Guide
|
Console
|
||||||
</Button>
|
</Button>
|
||||||
</Link>
|
</Link>
|
||||||
)}
|
|
||||||
</div>
|
</div>
|
||||||
</header>
|
</header>
|
||||||
);
|
);
|
||||||
|
|||||||
+115
-94
@@ -4,7 +4,7 @@ import { Button } from '@/components/ui/Button';
|
|||||||
import { Icon } from '@/components/ui/Icon';
|
import { Icon } from '@/components/ui/Icon';
|
||||||
import { cn } from '@/lib/utils';
|
import { cn } from '@/lib/utils';
|
||||||
import Link from 'next/link';
|
import Link from 'next/link';
|
||||||
import { usePathname, useRouter } from 'next/navigation';
|
import { usePathname } from 'next/navigation';
|
||||||
import React, { useEffect, useState } from 'react';
|
import React, { useEffect, useState } from 'react';
|
||||||
|
|
||||||
interface SidebarProps {
|
interface SidebarProps {
|
||||||
@@ -12,126 +12,125 @@ interface SidebarProps {
|
|||||||
onClose?: () => void;
|
onClose?: () => void;
|
||||||
}
|
}
|
||||||
|
|
||||||
export const Sidebar: React.FC<SidebarProps> = ({
|
const NAVIGATION_SECTIONS = [
|
||||||
isOpen = false,
|
|
||||||
onClose,
|
|
||||||
}) => {
|
|
||||||
const pathname = usePathname();
|
|
||||||
const router = useRouter();
|
|
||||||
const [isSigningOut, setIsSigningOut] = useState(false);
|
|
||||||
const [signOutError, setSignOutError] = useState('');
|
|
||||||
|
|
||||||
const navigation = [
|
|
||||||
{
|
{
|
||||||
group: 'Monitoring',
|
group: 'Main',
|
||||||
items: [
|
items: [
|
||||||
{ name: 'Dashboard', href: '/vcon/dashboard', icon: 'LayoutDashboard' },
|
{ name: 'Dashboard', href: '/vcon/dashboard', icon: 'LayoutDashboard' },
|
||||||
{ name: 'Events', href: '/vcon/data', icon: 'Activity' },
|
{ name: 'Events', href: '/vcon/data', icon: 'Activity' },
|
||||||
],
|
{ name: 'Clients', href: '/vcon/clients', icon: 'Key' },
|
||||||
},
|
|
||||||
{
|
|
||||||
group: 'Data',
|
|
||||||
items: [
|
|
||||||
{ name: 'Export', href: '/vcon/export', icon: 'Download' },
|
{ name: 'Export', href: '/vcon/export', icon: 'Download' },
|
||||||
{ name: 'Storage', href: '/vcon/storage', icon: 'HardDrive' },
|
{ name: 'Storage', href: '/vcon/storage', icon: 'HardDrive' },
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
group: 'Administration',
|
group: 'System',
|
||||||
items: [
|
|
||||||
{ name: 'Clients', href: '/vcon/clients', icon: 'Key' },
|
|
||||||
{ name: 'Settings', href: '/vcon/settings', icon: 'Sliders' },
|
|
||||||
],
|
|
||||||
},
|
|
||||||
{
|
|
||||||
group: 'Tools',
|
|
||||||
items: [
|
items: [
|
||||||
{ name: 'Python SDK', href: '/vcon/sdk', icon: 'FileCode2' },
|
{ name: 'Python SDK', href: '/vcon/sdk', icon: 'FileCode2' },
|
||||||
{ name: 'Simulator', href: '/vcon/simulator', icon: 'Play' },
|
{ name: 'Simulator', href: '/vcon/simulator', icon: 'Play' },
|
||||||
|
{ name: 'Settings', href: '/vcon/settings', icon: 'Sliders' },
|
||||||
|
{ name: 'Profile', href: '/vcon/profile', icon: 'User' },
|
||||||
],
|
],
|
||||||
},
|
},
|
||||||
];
|
];
|
||||||
const activeGroup = navigation.find((section) =>
|
|
||||||
section.items.some((item) => item.href === pathname)
|
export const Sidebar: React.FC<SidebarProps> = ({
|
||||||
)?.group;
|
isOpen = false,
|
||||||
const [openGroup, setOpenGroup] = useState(activeGroup ?? navigation[0].group);
|
onClose,
|
||||||
|
}) => {
|
||||||
|
const pathname = usePathname();
|
||||||
|
const [isSigningOut, setIsSigningOut] = useState(false);
|
||||||
|
const [theme, setTheme] = useState<'dark' | 'light'>('dark');
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (activeGroup) setOpenGroup(activeGroup);
|
const saved = localStorage.getItem('datastack-theme') as 'dark' | 'light' | null;
|
||||||
}, [activeGroup]);
|
const initial = saved === 'light' ? 'light' : 'dark';
|
||||||
|
setTheme(initial);
|
||||||
|
document.documentElement.classList.toggle('light', initial === 'light');
|
||||||
|
document.documentElement.classList.toggle('dark', initial === 'dark');
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
const toggleTheme = () => {
|
||||||
|
const nextTheme = theme === 'dark' ? 'light' : 'dark';
|
||||||
|
setTheme(nextTheme);
|
||||||
|
localStorage.setItem('datastack-theme', nextTheme);
|
||||||
|
document.documentElement.classList.toggle('light', nextTheme === 'light');
|
||||||
|
document.documentElement.classList.toggle('dark', nextTheme === 'dark');
|
||||||
|
};
|
||||||
|
|
||||||
const signOut = async () => {
|
const signOut = async () => {
|
||||||
setIsSigningOut(true);
|
setIsSigningOut(true);
|
||||||
setSignOutError('');
|
|
||||||
try {
|
try {
|
||||||
const response = await fetch('/api/auth/logout', {
|
const response = await fetch('/api/auth/logout', {
|
||||||
method: 'POST',
|
method: 'POST',
|
||||||
credentials: 'include',
|
credentials: 'include',
|
||||||
});
|
});
|
||||||
if (!response.ok) throw new Error('Unable to sign out. Please try again.');
|
if (!response.ok) throw new Error('Unable to sign out');
|
||||||
window.location.assign('/vcon/login');
|
window.location.assign('/vcon/login');
|
||||||
} catch (error) {
|
} catch {
|
||||||
setSignOutError(
|
|
||||||
error instanceof Error ? error.message : 'Unable to sign out. Please try again.',
|
|
||||||
);
|
|
||||||
} finally {
|
|
||||||
setIsSigningOut(false);
|
setIsSigningOut(false);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
{/* Mobile Backdrop */}
|
|
||||||
{isOpen && (
|
{isOpen && (
|
||||||
<div
|
<div
|
||||||
onClick={onClose}
|
onClick={onClose}
|
||||||
className="fixed inset-x-0 top-11 bottom-0 z-40 bg-black/50 lg:hidden"
|
className="fixed inset-0 z-40 bg-black/55 md:hidden"
|
||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{/* Sidebar Container */}
|
|
||||||
<aside
|
<aside
|
||||||
className={cn(
|
className={cn(
|
||||||
'fixed left-0 top-11 bottom-0 z-50 w-[216px] shrink-0 overflow-hidden bg-[var(--bg-sidebar)] border-r border-[var(--border)] flex flex-col transition-transform duration-150 ease-in-out lg:static lg:w-[216px] lg:translate-x-0',
|
'fixed inset-y-0 left-0 z-50 flex w-[184px] shrink-0 flex-col border-r border-[var(--border)] bg-[var(--surface)] transition-transform duration-150 ease-out md:sticky md:top-0 md:h-dvh md:translate-x-0',
|
||||||
isOpen ? 'translate-x-0' : '-translate-x-full'
|
isOpen ? 'translate-x-0' : '-translate-x-full'
|
||||||
)}
|
)}
|
||||||
>
|
>
|
||||||
{/* Mobile Close Header */}
|
{/* Brand Header */}
|
||||||
<div className="h-9 px-3 flex items-center justify-between border-b border-[var(--border)] bg-[var(--bg-activity)] shrink-0 lg:hidden">
|
<div className="flex h-10 shrink-0 items-center justify-between border-b border-[var(--border)] px-3">
|
||||||
<span className="text-[11px] font-medium text-[var(--text-muted)]">Menu</span>
|
<Link
|
||||||
<button
|
href="/vcon/dashboard"
|
||||||
onClick={onClose}
|
onClick={onClose}
|
||||||
className="text-[var(--text-dim)] hover:text-[var(--text)] p-1 cursor-pointer"
|
className="flex min-w-0 items-center gap-2 text-[12.5px] font-medium text-[var(--text)]"
|
||||||
aria-label="Close menu"
|
|
||||||
>
|
>
|
||||||
<Icon name="X" size={12} />
|
<span className="grid h-3 w-3 shrink-0 place-items-center bg-[var(--accent)]">
|
||||||
</button>
|
<span className="h-1 w-1 bg-[var(--bg)]" />
|
||||||
|
</span>
|
||||||
|
<span className="truncate">DataStack</span>
|
||||||
|
</Link>
|
||||||
|
|
||||||
|
<Link
|
||||||
|
href="/"
|
||||||
|
title="Public Home"
|
||||||
|
aria-label="Public Home"
|
||||||
|
className="hidden text-[10.5px] text-[var(--text-faint)] hover:text-[var(--text)] md:inline"
|
||||||
|
>
|
||||||
|
Site ↗
|
||||||
|
</Link>
|
||||||
|
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="icon"
|
||||||
|
size="icon"
|
||||||
|
icon="X"
|
||||||
|
onClick={onClose}
|
||||||
|
aria-label="Close navigation"
|
||||||
|
title="Close navigation"
|
||||||
|
className="h-6 w-6 md:hidden"
|
||||||
|
/>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{/* Navigation items */}
|
{/* Clean 2-Group Navigation */}
|
||||||
<nav aria-label="Admin navigation" className="flex-1 min-h-0 overflow-y-auto p-1.5 flex flex-col">
|
<nav
|
||||||
{navigation.map((section) => {
|
aria-label="Admin navigation"
|
||||||
const isExpanded = openGroup === section.group;
|
className="flex-1 overflow-y-auto px-2 py-2.5 flex flex-col gap-3.5"
|
||||||
const groupId = `nav-${section.group.toLowerCase().replaceAll(' ', '-')}`;
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div key={section.group} className="border-b border-[var(--border)] last:border-b-0">
|
|
||||||
<button
|
|
||||||
type="button"
|
|
||||||
aria-expanded={isExpanded}
|
|
||||||
aria-controls={groupId}
|
|
||||||
onClick={() => setOpenGroup(isExpanded ? '' : section.group)}
|
|
||||||
className="w-full h-8 px-2.5 flex items-center justify-between gap-2 text-left text-[11px] font-medium text-[var(--text-muted)] hover:text-[var(--text)] transition-colors cursor-pointer"
|
|
||||||
>
|
>
|
||||||
<span className="truncate">{section.group}</span>
|
{NAVIGATION_SECTIONS.map((section) => (
|
||||||
<Icon
|
<div key={section.group} className="flex flex-col gap-0.5">
|
||||||
name="ChevronDown"
|
<div className="px-2 pb-1 text-[9.5px] font-medium uppercase tracking-wider text-[var(--text-faint)]">
|
||||||
size={11}
|
{section.group}
|
||||||
className={cn('transition-transform', isExpanded && 'rotate-180')}
|
</div>
|
||||||
/>
|
|
||||||
</button>
|
|
||||||
{isExpanded && (
|
|
||||||
<div id={groupId} className="pb-1 flex flex-col gap-0.5">
|
|
||||||
{section.items.map((item) => {
|
{section.items.map((item) => {
|
||||||
const isActive = pathname === item.href;
|
const isActive = pathname === item.href;
|
||||||
return (
|
return (
|
||||||
@@ -140,48 +139,70 @@ export const Sidebar: React.FC<SidebarProps> = ({
|
|||||||
href={item.href}
|
href={item.href}
|
||||||
onClick={onClose}
|
onClick={onClose}
|
||||||
className={cn(
|
className={cn(
|
||||||
'flex h-8 min-w-0 items-center gap-2 px-2.5 text-[12px] transition-colors border',
|
'flex h-7 min-w-0 items-center gap-2 border-l-2 px-2 text-[12px] transition-colors select-none',
|
||||||
isActive
|
isActive
|
||||||
? 'bg-[var(--accent-soft)] text-[var(--accent-hover)] font-medium border-[var(--accent)]'
|
? 'border-l-[var(--accent)] bg-[var(--surface-2)] font-medium text-[var(--text)]'
|
||||||
: 'border-transparent text-[var(--text-muted)] hover:text-[var(--text)] hover:bg-[var(--bg-hover)]'
|
: 'border-l-transparent text-[var(--text-muted)] hover:bg-[var(--surface-2)] hover:text-[var(--text)]'
|
||||||
)}
|
)}
|
||||||
>
|
>
|
||||||
<Icon
|
<Icon
|
||||||
name={item.icon}
|
name={item.icon}
|
||||||
size={13}
|
size={13}
|
||||||
className={isActive ? 'text-[var(--accent)]' : 'text-[var(--text-dim)]'}
|
className={isActive ? 'text-[var(--accent)]' : 'text-[var(--text-faint)]'}
|
||||||
/>
|
/>
|
||||||
<span className="truncate">{item.name}</span>
|
<span className="truncate">{item.name}</span>
|
||||||
</Link>
|
</Link>
|
||||||
);
|
);
|
||||||
})}
|
})}
|
||||||
</div>
|
</div>
|
||||||
)}
|
))}
|
||||||
</div>
|
|
||||||
);
|
|
||||||
})}
|
|
||||||
</nav>
|
</nav>
|
||||||
|
|
||||||
{/* Sign out action */}
|
{/* Bottom Dock: Identity + Theme Toggle + Sign Out */}
|
||||||
{pathname !== '/vcon/setup' && (
|
<div className="flex shrink-0 items-center gap-1 border-t border-[var(--border)] bg-[var(--bg)] px-2.5 py-2">
|
||||||
<div className="p-1.5 border-t border-[var(--border)] bg-[var(--bg-main)] shrink-0">
|
<Link
|
||||||
{signOutError && (
|
href="/vcon/profile"
|
||||||
<p role="alert" className="px-2 pb-1 text-[11px] text-[var(--danger)]">{signOutError}</p>
|
onClick={onClose}
|
||||||
)}
|
className="flex flex-1 min-w-0 items-center gap-2 hover:opacity-90"
|
||||||
|
title="Admin Profile"
|
||||||
|
>
|
||||||
|
<div className="grid h-6 w-6 shrink-0 place-items-center border border-[var(--border-strong)] bg-[var(--surface-3)] text-[10.5px] font-medium text-[var(--text)]">
|
||||||
|
A
|
||||||
|
</div>
|
||||||
|
<div className="min-w-0 flex-1 leading-tight">
|
||||||
|
<div className="truncate text-[11px] font-medium text-[var(--text)]">
|
||||||
|
Admin
|
||||||
|
</div>
|
||||||
|
<div className="truncate text-[9px] uppercase tracking-wider text-[var(--text-faint)]">
|
||||||
|
Owner
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</Link>
|
||||||
|
|
||||||
<Button
|
<Button
|
||||||
type="button"
|
type="button"
|
||||||
variant="ghost"
|
variant="icon"
|
||||||
size="xs"
|
size="icon"
|
||||||
|
icon={theme === 'dark' ? 'Sun' : 'Moon'}
|
||||||
|
onClick={toggleTheme}
|
||||||
|
title="Toggle theme"
|
||||||
|
aria-label="Toggle theme"
|
||||||
|
className="h-6 w-6 border border-[var(--border)] bg-[var(--surface)]"
|
||||||
|
/>
|
||||||
|
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="icon"
|
||||||
|
size="icon"
|
||||||
icon="LogOut"
|
icon="LogOut"
|
||||||
loading={isSigningOut}
|
loading={isSigningOut}
|
||||||
disabled={isSigningOut}
|
disabled={isSigningOut}
|
||||||
onClick={signOut}
|
onClick={signOut}
|
||||||
className="w-full justify-start px-2.5 text-[11.5px] h-7"
|
title="Sign out"
|
||||||
>
|
aria-label="Sign out"
|
||||||
Sign out
|
className="h-6 w-6 border border-[var(--border)] bg-[var(--surface)] hover:border-[var(--danger)] hover:text-[var(--danger)]"
|
||||||
</Button>
|
/>
|
||||||
</div>
|
</div>
|
||||||
)}
|
|
||||||
</aside>
|
</aside>
|
||||||
</>
|
</>
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -15,6 +15,7 @@ import {
|
|||||||
TableWrap,
|
TableWrap,
|
||||||
} from '@/components/ui/Table';
|
} from '@/components/ui/Table';
|
||||||
import { useToast } from '@/components/ui/Toast';
|
import { useToast } from '@/components/ui/Toast';
|
||||||
|
import { useRouter } from 'next/navigation';
|
||||||
import { useState } from 'react';
|
import { useState } from 'react';
|
||||||
import type { ClientCredentials, ClientItem } from './clients/types';
|
import type { ClientCredentials, ClientItem } from './clients/types';
|
||||||
|
|
||||||
@@ -35,6 +36,7 @@ function relativeTime(timestamp: string | undefined, now: number) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export function ClientsTable({ clients, now, onStatusChange }: ClientsTableProps) {
|
export function ClientsTable({ clients, now, onStatusChange }: ClientsTableProps) {
|
||||||
|
const router = useRouter();
|
||||||
const { success, error } = useToast();
|
const { success, error } = useToast();
|
||||||
const [credentials, setCredentials] = useState<ClientCredentials | null>(null);
|
const [credentials, setCredentials] = useState<ClientCredentials | null>(null);
|
||||||
const [confirmAction, setConfirmAction] = useState<{
|
const [confirmAction, setConfirmAction] = useState<{
|
||||||
@@ -160,7 +162,7 @@ export function ClientsTable({ clients, now, onStatusChange }: ClientsTableProps
|
|||||||
className="h-6 w-6 border border-transparent hover:border-[var(--border)] hover:bg-[var(--surface-2)]"
|
className="h-6 w-6 border border-transparent hover:border-[var(--border)] hover:bg-[var(--surface-2)]"
|
||||||
title={`View events for ${client.clientId}`}
|
title={`View events for ${client.clientId}`}
|
||||||
aria-label={`View events for ${client.clientId}`}
|
aria-label={`View events for ${client.clientId}`}
|
||||||
onClick={() => window.location.assign(`/vcon/data?clientId=${encodeURIComponent(client.clientId)}`)}
|
onClick={() => router.push(`/vcon/data?clientId=${encodeURIComponent(client.clientId)}`)}
|
||||||
/>
|
/>
|
||||||
<Button
|
<Button
|
||||||
type="button"
|
type="button"
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ import { AdminPageHeader } from '@/components/layout/AdminPageHeader';
|
|||||||
import { Button } from '@/components/ui/Button';
|
import { Button } from '@/components/ui/Button';
|
||||||
import { ClientList, type ClientListItem } from '@/components/ui/ClientList';
|
import { ClientList, type ClientListItem } from '@/components/ui/ClientList';
|
||||||
import { Panel } from '@/components/ui/Panel';
|
import { Panel } from '@/components/ui/Panel';
|
||||||
import { StatCard } from '@/components/ui/StatCard';
|
import { StatStrip } from '@/components/ui/StatStrip';
|
||||||
import {
|
import {
|
||||||
Table,
|
Table,
|
||||||
TableBody,
|
TableBody,
|
||||||
@@ -14,6 +14,7 @@ import {
|
|||||||
TableRow,
|
TableRow,
|
||||||
TableWrap,
|
TableWrap,
|
||||||
} from '@/components/ui/Table';
|
} from '@/components/ui/Table';
|
||||||
|
import { getCached, setCached } from '@/lib/vconCache';
|
||||||
import Link from 'next/link';
|
import Link from 'next/link';
|
||||||
import React, { useCallback, useEffect, useState } from 'react';
|
import React, { useCallback, useEffect, useState } from 'react';
|
||||||
|
|
||||||
@@ -48,10 +49,10 @@ type StorageFile = {
|
|||||||
};
|
};
|
||||||
|
|
||||||
export const DashboardOverview: React.FC = () => {
|
export const DashboardOverview: React.FC = () => {
|
||||||
const [metrics, setMetrics] = useState<DashboardMetrics | null>(null);
|
const [metrics, setMetrics] = useState<DashboardMetrics | null>(() => getCached<DashboardMetrics | null>('vcon:metrics', null));
|
||||||
const [events, setEvents] = useState<EventItem[]>([]);
|
const [events, setEvents] = useState<EventItem[]>(() => getCached<EventItem[]>('vcon:dashboard-events', []));
|
||||||
const [clients, setClients] = useState<ClientListItem[]>([]);
|
const [clients, setClients] = useState<ClientListItem[]>(() => getCached<ClientListItem[]>('vcon:clients', []));
|
||||||
const [files, setFiles] = useState<StorageFile[]>([]);
|
const [files, setFiles] = useState<StorageFile[]>(() => getCached<StorageFile[]>('vcon:storage-files', []));
|
||||||
const [isRefreshing, setIsRefreshing] = useState(false);
|
const [isRefreshing, setIsRefreshing] = useState(false);
|
||||||
|
|
||||||
const refresh = useCallback(async () => {
|
const refresh = useCallback(async () => {
|
||||||
@@ -64,18 +65,22 @@ export const DashboardOverview: React.FC = () => {
|
|||||||
fetch('/api/clients', { cache: 'no-store' }),
|
fetch('/api/clients', { cache: 'no-store' }),
|
||||||
]);
|
]);
|
||||||
|
|
||||||
if (metricsResponse.ok) setMetrics(await metricsResponse.json());
|
if (metricsResponse.ok) {
|
||||||
|
const nextMetrics = await metricsResponse.json();
|
||||||
|
setMetrics(setCached('vcon:metrics', nextMetrics));
|
||||||
|
}
|
||||||
if (eventsResponse.ok) {
|
if (eventsResponse.ok) {
|
||||||
const data = await eventsResponse.json();
|
const data = await eventsResponse.json();
|
||||||
setEvents(data.events ?? []);
|
setEvents(setCached('vcon:dashboard-events', data.events ?? []));
|
||||||
}
|
}
|
||||||
if (storageResponse.ok) {
|
if (storageResponse.ok) {
|
||||||
const data = await storageResponse.json();
|
const data = await storageResponse.json();
|
||||||
setFiles(data.files ?? []);
|
setFiles(setCached('vcon:storage-files', data.files ?? []));
|
||||||
|
if (data.stats) setCached('vcon:storage-stats', data.stats);
|
||||||
}
|
}
|
||||||
if (clientsResponse.ok) {
|
if (clientsResponse.ok) {
|
||||||
const data = await clientsResponse.json();
|
const data = await clientsResponse.json();
|
||||||
setClients(data.clients ?? []);
|
setClients(setCached('vcon:clients', data.clients ?? []));
|
||||||
}
|
}
|
||||||
} catch {
|
} catch {
|
||||||
// Keep the last successful dashboard snapshot when one request fails.
|
// Keep the last successful dashboard snapshot when one request fails.
|
||||||
@@ -131,27 +136,16 @@ export const DashboardOverview: React.FC = () => {
|
|||||||
}
|
}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<div className="mb-2.5 grid grid-cols-2 gap-2.5 xl:grid-cols-4">
|
<StatStrip
|
||||||
<StatCard
|
items={[
|
||||||
label="Events today"
|
{ label: 'Events today', value: eventsToday.toLocaleString() },
|
||||||
value={eventsToday.toLocaleString()}
|
{ label: 'Active clients', value: `${activeClients} / ${totalClients}`, dot: activeClients > 0 ? 'ok' : 'off' },
|
||||||
|
{ label: 'Storage used', value: `${storageValue} ${storageUnit}` },
|
||||||
|
{ label: 'Stored rows', value: totalRows.toLocaleString() },
|
||||||
|
]}
|
||||||
/>
|
/>
|
||||||
<StatCard
|
|
||||||
label="Active clients"
|
|
||||||
value={`${activeClients} / ${totalClients}`}
|
|
||||||
/>
|
|
||||||
<StatCard
|
|
||||||
label="Storage used"
|
|
||||||
value={storageValue}
|
|
||||||
unit={storageUnit}
|
|
||||||
/>
|
|
||||||
<StatCard
|
|
||||||
label="Stored rows"
|
|
||||||
value={totalRows.toLocaleString()}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="grid min-w-0 grid-cols-1 gap-2.5 xl:grid-cols-[minmax(0,2fr)_minmax(0,1fr)]">
|
<div className="grid min-w-0 grid-cols-1 gap-2.5 lg:grid-cols-[minmax(0,1.85fr)_minmax(0,1fr)]">
|
||||||
<Panel
|
<Panel
|
||||||
title="Recent events"
|
title="Recent events"
|
||||||
meta={`${events.length}`}
|
meta={`${events.length}`}
|
||||||
|
|||||||
@@ -16,6 +16,7 @@ import {
|
|||||||
TableRow,
|
TableRow,
|
||||||
TableWrap,
|
TableWrap,
|
||||||
} from '@/components/ui/Table';
|
} from '@/components/ui/Table';
|
||||||
|
import { useRouter } from 'next/navigation';
|
||||||
import { useCallback, useEffect, useState } from 'react';
|
import { useCallback, useEffect, useState } from 'react';
|
||||||
|
|
||||||
interface StreamEvent {
|
interface StreamEvent {
|
||||||
@@ -34,6 +35,7 @@ interface Client {
|
|||||||
const PAGE_SIZE = 12;
|
const PAGE_SIZE = 12;
|
||||||
|
|
||||||
export function DataBrowser() {
|
export function DataBrowser() {
|
||||||
|
const router = useRouter();
|
||||||
const [events, setEvents] = useState<StreamEvent[]>([]);
|
const [events, setEvents] = useState<StreamEvent[]>([]);
|
||||||
const [clients, setClients] = useState<Client[]>([]);
|
const [clients, setClients] = useState<Client[]>([]);
|
||||||
const [total, setTotal] = useState(0);
|
const [total, setTotal] = useState(0);
|
||||||
@@ -150,7 +152,7 @@ export function DataBrowser() {
|
|||||||
variant="primary"
|
variant="primary"
|
||||||
size="xs"
|
size="xs"
|
||||||
icon="Download"
|
icon="Download"
|
||||||
onClick={() => window.location.assign('/vcon/export')}
|
onClick={() => router.push('/vcon/export')}
|
||||||
>
|
>
|
||||||
Export CSV
|
Export CSV
|
||||||
</Button>
|
</Button>
|
||||||
|
|||||||
@@ -7,7 +7,9 @@ import { Panel } from '@/components/ui/Panel';
|
|||||||
import { Pill } from '@/components/ui/Pill';
|
import { Pill } from '@/components/ui/Pill';
|
||||||
import { StatStrip } from '@/components/ui/StatStrip';
|
import { StatStrip } from '@/components/ui/StatStrip';
|
||||||
import { useToast } from '@/components/ui/Toast';
|
import { useToast } from '@/components/ui/Toast';
|
||||||
|
import { getCached, setCached } from '@/lib/vconCache';
|
||||||
import { Braces, FileText } from 'lucide-react';
|
import { Braces, FileText } from 'lucide-react';
|
||||||
|
import Link from 'next/link';
|
||||||
import { useEffect, useMemo, useState } from 'react';
|
import { useEffect, useMemo, useState } from 'react';
|
||||||
|
|
||||||
interface Client {
|
interface Client {
|
||||||
@@ -48,22 +50,18 @@ function relativeTime(value: string, now: number) {
|
|||||||
|
|
||||||
export function ExportWorkspace() {
|
export function ExportWorkspace() {
|
||||||
const { error, info } = useToast();
|
const { error, info } = useToast();
|
||||||
const [clients, setClients] = useState<Client[]>([]);
|
const [clients, setClients] = useState<Client[]>(() => getCached<Client[]>('vcon:clients', []));
|
||||||
const [files, setFiles] = useState<StorageFile[]>([]);
|
const [files, setFiles] = useState<StorageFile[]>(() => getCached<StorageFile[]>('vcon:storage-files', []));
|
||||||
const [selectedClient, setSelectedClient] = useState('all');
|
const [selectedClient, setSelectedClient] = useState('all');
|
||||||
const [fromDate, setFromDate] = useState('');
|
const [fromDate, setFromDate] = useState(() => dateString(new Date()));
|
||||||
const [toDate, setToDate] = useState('');
|
const [toDate, setToDate] = useState(() => dateString(new Date()));
|
||||||
const [format, setFormat] = useState<ExportFormat>('csv');
|
const [format, setFormat] = useState<ExportFormat>('csv');
|
||||||
const [preset, setPreset] = useState<RangePreset>('today');
|
const [preset, setPreset] = useState<RangePreset>('today');
|
||||||
const [loading, setLoading] = useState(true);
|
const [loading, setLoading] = useState(() => getCached<StorageFile[]>('vcon:storage-files', []).length === 0);
|
||||||
const [loadError, setLoadError] = useState('');
|
const [loadError, setLoadError] = useState('');
|
||||||
const [now, setNow] = useState(0);
|
const [now, setNow] = useState(() => Date.now());
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const today = dateString(new Date());
|
|
||||||
setFromDate(today);
|
|
||||||
setToDate(today);
|
|
||||||
|
|
||||||
Promise.all([
|
Promise.all([
|
||||||
fetch('/api/clients').then(async (response) => {
|
fetch('/api/clients').then(async (response) => {
|
||||||
if (!response.ok) throw new Error('Unable to load clients');
|
if (!response.ok) throw new Error('Unable to load clients');
|
||||||
@@ -75,8 +73,9 @@ export function ExportWorkspace() {
|
|||||||
}),
|
}),
|
||||||
])
|
])
|
||||||
.then(([clientData, storageData]) => {
|
.then(([clientData, storageData]) => {
|
||||||
setClients(clientData.clients || []);
|
setClients(setCached('vcon:clients', clientData.clients || []));
|
||||||
setFiles(storageData.files || []);
|
setFiles(setCached('vcon:storage-files', storageData.files || []));
|
||||||
|
if (storageData.stats) setCached('vcon:storage-stats', storageData.stats);
|
||||||
setLoadError('');
|
setLoadError('');
|
||||||
})
|
})
|
||||||
.catch((fetchError) => {
|
.catch((fetchError) => {
|
||||||
@@ -164,7 +163,7 @@ export function ExportWorkspace() {
|
|||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<section className="mx-auto w-full max-w-[var(--console-width)]">
|
<section className="w-full">
|
||||||
<AdminPageHeader title="Export" />
|
<AdminPageHeader title="Export" />
|
||||||
|
|
||||||
<StatStrip
|
<StatStrip
|
||||||
@@ -176,8 +175,8 @@ export function ExportWorkspace() {
|
|||||||
]}
|
]}
|
||||||
/>
|
/>
|
||||||
|
|
||||||
<div className="grid grid-cols-1 items-start gap-2.5 xl:grid-cols-5">
|
<div className="grid grid-cols-1 items-start gap-2.5 lg:grid-cols-5">
|
||||||
<Panel title="Export builder" bodyClassName="flex flex-col gap-3 p-3" className="min-w-0 xl:col-span-3">
|
<Panel title="Export builder" bodyClassName="flex flex-col gap-3 p-3" className="min-w-0 lg:col-span-3">
|
||||||
<div className="flex flex-wrap items-center gap-1">
|
<div className="flex flex-wrap items-center gap-1">
|
||||||
<span className="mr-1 text-[10px] uppercase tracking-wider text-[var(--text-faint)]">Range</span>
|
<span className="mr-1 text-[10px] uppercase tracking-wider text-[var(--text-faint)]">Range</span>
|
||||||
{([
|
{([
|
||||||
@@ -241,9 +240,9 @@ export function ExportWorkspace() {
|
|||||||
|
|
||||||
<Panel
|
<Panel
|
||||||
title="Files"
|
title="Files"
|
||||||
action={<a href="/vcon/storage" className="text-[11px] text-[var(--text-muted)] hover:text-[var(--text)]">View all</a>}
|
action={<Link href="/vcon/storage" className="text-[11px] text-[var(--text-muted)] hover:text-[var(--text)]">View all</Link>}
|
||||||
bodyClassName="divide-y divide-[var(--border)]"
|
bodyClassName="divide-y divide-[var(--border)]"
|
||||||
className="min-w-0 xl:col-span-2"
|
className="min-w-0 lg:col-span-2"
|
||||||
>
|
>
|
||||||
{loading ? (
|
{loading ? (
|
||||||
<p className="px-3 py-4 text-[11.5px] text-[var(--text-faint)]">Loading...</p>
|
<p className="px-3 py-4 text-[11.5px] text-[var(--text-faint)]">Loading...</p>
|
||||||
|
|||||||
@@ -0,0 +1,244 @@
|
|||||||
|
'use client';
|
||||||
|
|
||||||
|
import { AdminPageHeader } from '@/components/layout/AdminPageHeader';
|
||||||
|
import { Button } from '@/components/ui/Button';
|
||||||
|
import { Input } from '@/components/ui/Input';
|
||||||
|
import { SettingsField, SettingsGroup } from '@/components/ui/SettingsLayout';
|
||||||
|
import { StatStrip } from '@/components/ui/StatStrip';
|
||||||
|
import { useToast } from '@/components/ui/Toast';
|
||||||
|
import { getCached, setCached } from '@/lib/vconCache';
|
||||||
|
import Link from 'next/link';
|
||||||
|
import { useEffect, useState } from 'react';
|
||||||
|
|
||||||
|
interface AdminProfileData {
|
||||||
|
email: string;
|
||||||
|
role: string;
|
||||||
|
storageMode: string;
|
||||||
|
createdAt: string;
|
||||||
|
sessionExpiresAt: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
const DEFAULT_PROFILE: AdminProfileData = {
|
||||||
|
email: 'admin@datastack.dev',
|
||||||
|
role: 'Owner',
|
||||||
|
storageMode: 'In-Memory',
|
||||||
|
createdAt: '',
|
||||||
|
sessionExpiresAt: '',
|
||||||
|
};
|
||||||
|
|
||||||
|
export function ProfileWorkspace() {
|
||||||
|
const { success, error } = useToast();
|
||||||
|
const [profile, setProfile] = useState<AdminProfileData>(() => getCached<AdminProfileData>('vcon:profile', DEFAULT_PROFILE));
|
||||||
|
const [email, setEmail] = useState(() => getCached<AdminProfileData>('vcon:profile', DEFAULT_PROFILE).email);
|
||||||
|
const [currentPassword, setCurrentPassword] = useState('');
|
||||||
|
const [newPassword, setNewPassword] = useState('');
|
||||||
|
const [confirmPassword, setConfirmPassword] = useState('');
|
||||||
|
const [loading, setLoading] = useState(() => !getCached<boolean>('vcon:profile-loaded', false));
|
||||||
|
const [saving, setSaving] = useState(false);
|
||||||
|
const [signingOut, setSigningOut] = useState(false);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
fetch('/api/auth/profile', { credentials: 'include' })
|
||||||
|
.then(async (res) => {
|
||||||
|
if (!res.ok) throw new Error('Unable to load profile');
|
||||||
|
return res.json();
|
||||||
|
})
|
||||||
|
.then((data) => {
|
||||||
|
if (data.profile) {
|
||||||
|
setProfile(setCached('vcon:profile', data.profile));
|
||||||
|
setEmail(data.profile.email);
|
||||||
|
setCached('vcon:profile-loaded', true);
|
||||||
|
}
|
||||||
|
})
|
||||||
|
.catch(() => {
|
||||||
|
error('Profile load failed', 'Could not load administrator profile.');
|
||||||
|
})
|
||||||
|
.finally(() => setLoading(false));
|
||||||
|
}, [error]);
|
||||||
|
|
||||||
|
const handleSave = async (event: React.FormEvent<HTMLFormElement>) => {
|
||||||
|
event.preventDefault();
|
||||||
|
const trimmedEmail = email.trim().toLowerCase();
|
||||||
|
if (!trimmedEmail) {
|
||||||
|
error('Validation error', 'Admin email is required.');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (!currentPassword) {
|
||||||
|
error('Validation error', 'Enter your current password to save changes.');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
if (newPassword && newPassword !== confirmPassword) {
|
||||||
|
error('Validation error', 'New password and confirmation do not match.');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
setSaving(true);
|
||||||
|
try {
|
||||||
|
const response = await fetch('/api/auth/profile', {
|
||||||
|
method: 'PUT',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
credentials: 'include',
|
||||||
|
body: JSON.stringify({
|
||||||
|
email: trimmedEmail,
|
||||||
|
currentPassword,
|
||||||
|
newPassword: newPassword || undefined,
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
const data = await response.json();
|
||||||
|
if (!response.ok) throw new Error(data.error || 'Profile update failed');
|
||||||
|
setProfile(setCached('vcon:profile', data.profile));
|
||||||
|
setEmail(data.profile.email);
|
||||||
|
setCurrentPassword('');
|
||||||
|
setNewPassword('');
|
||||||
|
setConfirmPassword('');
|
||||||
|
success('Profile updated', 'Administrator credentials updated.');
|
||||||
|
} catch (saveError) {
|
||||||
|
error('Update failed', saveError instanceof Error ? saveError.message : 'Unable to update profile');
|
||||||
|
} finally {
|
||||||
|
setSaving(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const handleSignOut = async () => {
|
||||||
|
setSigningOut(true);
|
||||||
|
try {
|
||||||
|
const response = await fetch('/api/auth/logout', {
|
||||||
|
method: 'POST',
|
||||||
|
credentials: 'include',
|
||||||
|
});
|
||||||
|
if (!response.ok) throw new Error('Unable to sign out');
|
||||||
|
window.location.assign('/vcon/login');
|
||||||
|
} catch {
|
||||||
|
error('Sign out failed', 'Please try again.');
|
||||||
|
setSigningOut(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<section className="w-full">
|
||||||
|
<AdminPageHeader
|
||||||
|
title="Profile"
|
||||||
|
actions={
|
||||||
|
<>
|
||||||
|
<Link href="/vcon/settings">
|
||||||
|
<Button type="button" size="xs" variant="secondary" icon="Sliders">
|
||||||
|
Settings
|
||||||
|
</Button>
|
||||||
|
</Link>
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
size="xs"
|
||||||
|
variant="danger"
|
||||||
|
icon="LogOut"
|
||||||
|
loading={signingOut}
|
||||||
|
onClick={handleSignOut}
|
||||||
|
>
|
||||||
|
Sign out
|
||||||
|
</Button>
|
||||||
|
</>
|
||||||
|
}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<StatStrip
|
||||||
|
items={[
|
||||||
|
{ label: 'Administrator', value: profile.email },
|
||||||
|
{ label: 'Role', value: profile.role, dot: 'ok' },
|
||||||
|
{ label: 'Auth Store', value: profile.storageMode },
|
||||||
|
{
|
||||||
|
label: 'Session Expires',
|
||||||
|
value: profile.sessionExpiresAt
|
||||||
|
? new Date(profile.sessionExpiresAt).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', hour12: false })
|
||||||
|
: 'Active',
|
||||||
|
},
|
||||||
|
]}
|
||||||
|
/>
|
||||||
|
|
||||||
|
<form onSubmit={handleSave} className="max-w-[780px] border border-[var(--border)] bg-[var(--surface)]">
|
||||||
|
<SettingsGroup title="Account identity">
|
||||||
|
<SettingsField label="Admin email">
|
||||||
|
<Input
|
||||||
|
compact
|
||||||
|
type="email"
|
||||||
|
value={email}
|
||||||
|
onChange={(event) => setEmail(event.target.value)}
|
||||||
|
required
|
||||||
|
/>
|
||||||
|
</SettingsField>
|
||||||
|
<SettingsField label="Access role">
|
||||||
|
<Input
|
||||||
|
compact
|
||||||
|
value={profile.role}
|
||||||
|
readOnly
|
||||||
|
className="border-[var(--border)] bg-[var(--surface-2)] text-[var(--text-muted)]"
|
||||||
|
/>
|
||||||
|
</SettingsField>
|
||||||
|
</SettingsGroup>
|
||||||
|
|
||||||
|
<SettingsGroup title="Security & password">
|
||||||
|
<SettingsField label="Current password">
|
||||||
|
<Input
|
||||||
|
compact
|
||||||
|
type="password"
|
||||||
|
autoComplete="current-password"
|
||||||
|
placeholder="Required to confirm changes"
|
||||||
|
value={currentPassword}
|
||||||
|
onChange={(event) => setCurrentPassword(event.target.value)}
|
||||||
|
required
|
||||||
|
/>
|
||||||
|
</SettingsField>
|
||||||
|
<SettingsField label="New password">
|
||||||
|
<Input
|
||||||
|
compact
|
||||||
|
type="password"
|
||||||
|
autoComplete="new-password"
|
||||||
|
placeholder="Leave blank to keep current"
|
||||||
|
value={newPassword}
|
||||||
|
onChange={(event) => setNewPassword(event.target.value)}
|
||||||
|
/>
|
||||||
|
</SettingsField>
|
||||||
|
<SettingsField label="Confirm new password">
|
||||||
|
<Input
|
||||||
|
compact
|
||||||
|
type="password"
|
||||||
|
autoComplete="new-password"
|
||||||
|
placeholder="Repeat new password"
|
||||||
|
value={confirmPassword}
|
||||||
|
onChange={(event) => setConfirmPassword(event.target.value)}
|
||||||
|
/>
|
||||||
|
</SettingsField>
|
||||||
|
</SettingsGroup>
|
||||||
|
|
||||||
|
<footer className="flex flex-wrap items-center justify-between gap-2 border-t border-[var(--border)] bg-[var(--surface)] px-3 py-2">
|
||||||
|
<span className="text-[11px] text-[var(--text-muted)]">
|
||||||
|
{loading ? 'Loading profile...' : 'Confirm current password to update credentials'}
|
||||||
|
</span>
|
||||||
|
<div className="flex items-center gap-2">
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
size="xs"
|
||||||
|
disabled={saving}
|
||||||
|
onClick={() => {
|
||||||
|
setEmail(profile.email);
|
||||||
|
setCurrentPassword('');
|
||||||
|
setNewPassword('');
|
||||||
|
setConfirmPassword('');
|
||||||
|
}}
|
||||||
|
>
|
||||||
|
Reset
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
type="submit"
|
||||||
|
variant="primary"
|
||||||
|
size="xs"
|
||||||
|
icon="Save"
|
||||||
|
loading={saving}
|
||||||
|
disabled={loading || saving}
|
||||||
|
>
|
||||||
|
Update profile
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</footer>
|
||||||
|
</form>
|
||||||
|
</section>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -6,6 +6,7 @@ import { FormSwitch } from '@/components/ui/Form';
|
|||||||
import { Input } from '@/components/ui/Input';
|
import { Input } from '@/components/ui/Input';
|
||||||
import { SettingsField, SettingsGroup, SettingsTabs } from '@/components/ui/SettingsLayout';
|
import { SettingsField, SettingsGroup, SettingsTabs } from '@/components/ui/SettingsLayout';
|
||||||
import { useToast } from '@/components/ui/Toast';
|
import { useToast } from '@/components/ui/Toast';
|
||||||
|
import { getCached, setCached } from '@/lib/vconCache';
|
||||||
import { useEffect, useMemo, useState } from 'react';
|
import { useEffect, useMemo, useState } from 'react';
|
||||||
|
|
||||||
interface EditableSettings {
|
interface EditableSettings {
|
||||||
@@ -45,15 +46,15 @@ type TabId = (typeof TABS)[number]['id'];
|
|||||||
|
|
||||||
export function SettingsWorkspace() {
|
export function SettingsWorkspace() {
|
||||||
const { success, error } = useToast();
|
const { success, error } = useToast();
|
||||||
const [settings, setSettings] = useState<EditableSettings>(DEFAULT_SETTINGS);
|
const [settings, setSettings] = useState<EditableSettings>(() => getCached<EditableSettings>('vcon:settings', DEFAULT_SETTINGS));
|
||||||
const [savedSettings, setSavedSettings] = useState<EditableSettings>(DEFAULT_SETTINGS);
|
const [savedSettings, setSavedSettings] = useState<EditableSettings>(() => getCached<EditableSettings>('vcon:settings', DEFAULT_SETTINGS));
|
||||||
const [activeTab, setActiveTab] = useState<TabId>('general');
|
const [activeTab, setActiveTab] = useState<TabId>('general');
|
||||||
const [jwtSecret, setJwtSecret] = useState('');
|
const [jwtSecret, setJwtSecret] = useState('');
|
||||||
const [storagePath, setStoragePath] = useState('');
|
const [storagePath, setStoragePath] = useState(() => getCached<string>('vcon:storage-path', ''));
|
||||||
const [baseUrl, setBaseUrl] = useState('');
|
const [baseUrl, setBaseUrl] = useState('');
|
||||||
const [webSocketUrl, setWebSocketUrl] = useState('');
|
const [webSocketUrl, setWebSocketUrl] = useState('');
|
||||||
const [serverPort, setServerPort] = useState(4000);
|
const [serverPort, setServerPort] = useState(() => getCached<number>('vcon:server-port', 4000));
|
||||||
const [loading, setLoading] = useState(true);
|
const [loading, setLoading] = useState(() => !getCached<boolean>('vcon:settings-loaded', false));
|
||||||
const [saving, setSaving] = useState(false);
|
const [saving, setSaving] = useState(false);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
@@ -85,10 +86,11 @@ export function SettingsWorkspace() {
|
|||||||
enableIdempotency: Boolean(settingsData.settings.enableIdempotency ?? DEFAULT_SETTINGS.enableIdempotency),
|
enableIdempotency: Boolean(settingsData.settings.enableIdempotency ?? DEFAULT_SETTINGS.enableIdempotency),
|
||||||
autoPruneDays: Number(settingsData.settings.autoPruneDays ?? DEFAULT_SETTINGS.autoPruneDays),
|
autoPruneDays: Number(settingsData.settings.autoPruneDays ?? DEFAULT_SETTINGS.autoPruneDays),
|
||||||
};
|
};
|
||||||
setSettings(loaded);
|
setSettings(setCached('vcon:settings', loaded));
|
||||||
setSavedSettings(loaded);
|
setSavedSettings(loaded);
|
||||||
setServerPort(Number((settingsData.settings as PublicSettings).serverPort ?? 4000));
|
setServerPort(setCached('vcon:server-port', Number((settingsData.settings as PublicSettings).serverPort ?? 4000)));
|
||||||
setStoragePath(String(storageData.stats?.storageDirectory ?? ''));
|
setStoragePath(setCached('vcon:storage-path', String(storageData.stats?.storageDirectory ?? '')));
|
||||||
|
setCached('vcon:settings-loaded', true);
|
||||||
})
|
})
|
||||||
.catch(() => {
|
.catch(() => {
|
||||||
error('Settings load failed', 'Using default runtime settings.');
|
error('Settings load failed', 'Using default runtime settings.');
|
||||||
@@ -128,7 +130,7 @@ export function SettingsWorkspace() {
|
|||||||
});
|
});
|
||||||
const data = await response.json();
|
const data = await response.json();
|
||||||
if (!response.ok) throw new Error(data.error || 'Settings update failed');
|
if (!response.ok) throw new Error(data.error || 'Settings update failed');
|
||||||
setSettings(normalized);
|
setSettings(setCached('vcon:settings', normalized));
|
||||||
setSavedSettings(normalized);
|
setSavedSettings(normalized);
|
||||||
setJwtSecret('');
|
setJwtSecret('');
|
||||||
success('Settings saved', 'Runtime settings updated.');
|
success('Settings saved', 'Runtime settings updated.');
|
||||||
@@ -145,9 +147,10 @@ export function SettingsWorkspace() {
|
|||||||
};
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<section className="mx-auto w-full max-w-[var(--console-width)]">
|
<section className="w-full">
|
||||||
<AdminPageHeader title="Settings" />
|
<AdminPageHeader title="Settings" />
|
||||||
|
|
||||||
|
<div className="max-w-[780px]">
|
||||||
<SettingsTabs items={TABS} value={activeTab} onChange={(tab) => setActiveTab(tab as TabId)} />
|
<SettingsTabs items={TABS} value={activeTab} onChange={(tab) => setActiveTab(tab as TabId)} />
|
||||||
|
|
||||||
<form onSubmit={saveSettings}>
|
<form onSubmit={saveSettings}>
|
||||||
@@ -243,6 +246,7 @@ export function SettingsWorkspace() {
|
|||||||
<Button type="submit" variant="primary" size="xs" icon="Save" loading={saving} disabled={loading || !isDirty}>Save</Button>
|
<Button type="submit" variant="primary" size="xs" icon="Save" loading={saving} disabled={loading || !isDirty}>Save</Button>
|
||||||
</footer>
|
</footer>
|
||||||
</form>
|
</form>
|
||||||
|
</div>
|
||||||
</section>
|
</section>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -4,4 +4,5 @@ export * from "./ClientsTable";
|
|||||||
export * from "./DataBrowser";
|
export * from "./DataBrowser";
|
||||||
export * from "./ExportWorkspace";
|
export * from "./ExportWorkspace";
|
||||||
export * from "./NewClientModal";
|
export * from "./NewClientModal";
|
||||||
|
export * from "./ProfileWorkspace";
|
||||||
export * from "./SettingsWorkspace";
|
export * from "./SettingsWorkspace";
|
||||||
@@ -15,7 +15,11 @@ export function SettingsTabs({
|
|||||||
onChange: (value: string) => void;
|
onChange: (value: string) => void;
|
||||||
}) {
|
}) {
|
||||||
return (
|
return (
|
||||||
<div className="flex overflow-x-auto border-b border-[var(--border)]" role="tablist" aria-label="Settings categories">
|
<div
|
||||||
|
className="flex overflow-x-auto overflow-y-hidden border-b border-[var(--border)] [scrollbar-width:none] [&::-webkit-scrollbar]:hidden"
|
||||||
|
role="tablist"
|
||||||
|
aria-label="Settings categories"
|
||||||
|
>
|
||||||
{items.map((item) => (
|
{items.map((item) => (
|
||||||
<button
|
<button
|
||||||
key={item.id}
|
key={item.id}
|
||||||
@@ -24,7 +28,11 @@ export function SettingsTabs({
|
|||||||
role="tab"
|
role="tab"
|
||||||
aria-selected={value === item.id}
|
aria-selected={value === item.id}
|
||||||
aria-controls={`settings-panel-${item.id}`}
|
aria-controls={`settings-panel-${item.id}`}
|
||||||
className={`mb-[-1px] shrink-0 border-b-2 px-3 py-1.5 text-[11.5px] transition-colors cursor-pointer whitespace-nowrap ${value === item.id ? 'border-[var(--accent)] text-[var(--text)] font-medium' : 'border-transparent text-[var(--text-muted)] hover:text-[var(--text)]'}`}
|
className={`shrink-0 border-b-2 px-3 py-1.5 text-[11.5px] transition-colors cursor-pointer whitespace-nowrap ${
|
||||||
|
value === item.id
|
||||||
|
? 'border-[var(--accent)] text-[var(--text)] font-medium'
|
||||||
|
: 'border-transparent text-[var(--text-muted)] hover:text-[var(--text)]'
|
||||||
|
}`}
|
||||||
onClick={() => onChange(item.id)}
|
onClick={() => onChange(item.id)}
|
||||||
>
|
>
|
||||||
{item.label}
|
{item.label}
|
||||||
@@ -59,7 +67,7 @@ export function SettingsField({
|
|||||||
children: React.ReactNode;
|
children: React.ReactNode;
|
||||||
}) {
|
}) {
|
||||||
return (
|
return (
|
||||||
<div className="grid grid-cols-1 items-center gap-1.5 py-1.5 sm:grid-cols-[1fr_2fr] sm:gap-4">
|
<div className="grid grid-cols-1 items-center gap-1.5 py-1.5 sm:grid-cols-[180px_minmax(0,380px)] sm:justify-between sm:gap-4">
|
||||||
<div className="min-w-0">
|
<div className="min-w-0">
|
||||||
<div className="text-[11.5px] leading-snug text-[var(--text)]">{label}</div>
|
<div className="text-[11.5px] leading-snug text-[var(--text)]">{label}</div>
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
@@ -46,9 +46,12 @@ export async function createAdminSessionToken(
|
|||||||
return `${payload}.${encodeBase64Url(new Uint8Array(signature))}`;
|
return `${payload}.${encodeBase64Url(new Uint8Array(signature))}`;
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function verifyAdminSessionToken(token: string, secret: string) {
|
export async function getAdminSessionPayload(
|
||||||
|
token: string,
|
||||||
|
secret: string,
|
||||||
|
): Promise<AdminSessionPayload | null> {
|
||||||
const [payload, signature, extra] = token.split(".");
|
const [payload, signature, extra] = token.split(".");
|
||||||
if (!payload || !signature || extra) return false;
|
if (!payload || !signature || extra) return null;
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const valid = await crypto.subtle.verify(
|
const valid = await crypto.subtle.verify(
|
||||||
@@ -57,19 +60,27 @@ export async function verifyAdminSessionToken(token: string, secret: string) {
|
|||||||
decodeBase64Url(signature),
|
decodeBase64Url(signature),
|
||||||
encoder.encode(payload),
|
encoder.encode(payload),
|
||||||
);
|
);
|
||||||
if (!valid) return false;
|
if (!valid) return null;
|
||||||
|
|
||||||
const session = JSON.parse(
|
const session = JSON.parse(
|
||||||
new TextDecoder().decode(decodeBase64Url(payload)),
|
new TextDecoder().decode(decodeBase64Url(payload)),
|
||||||
) as AdminSessionPayload;
|
) as AdminSessionPayload;
|
||||||
return (
|
if (
|
||||||
typeof session.email === "string" &&
|
typeof session.email === "string" &&
|
||||||
typeof session.expiresAt === "number" &&
|
typeof session.expiresAt === "number" &&
|
||||||
session.expiresAt > Date.now()
|
session.expiresAt > Date.now()
|
||||||
);
|
) {
|
||||||
} catch {
|
return session;
|
||||||
return false;
|
|
||||||
}
|
}
|
||||||
|
return null;
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function verifyAdminSessionToken(token: string, secret: string) {
|
||||||
|
const session = await getAdminSessionPayload(token, secret);
|
||||||
|
return Boolean(session);
|
||||||
}
|
}
|
||||||
|
|
||||||
export function getSessionCookieOptions(request: Request, maxAge: number) {
|
export function getSessionCookieOptions(request: Request, maxAge: number) {
|
||||||
|
|||||||
@@ -468,3 +468,83 @@ export async function verifyAdminCredentials(email: string, password: string) {
|
|||||||
const actualHash = await derivePasswordHash(password, inMem.passwordSalt);
|
const actualHash = await derivePasswordHash(password, inMem.passwordSalt);
|
||||||
return timingSafeEqual(actualHash, inMem.passwordHash);
|
return timingSafeEqual(actualHash, inMem.passwordHash);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export async function getAdminAccountInfo(fallbackEmail?: string) {
|
||||||
|
const pool = getPool();
|
||||||
|
if (pool) {
|
||||||
|
try {
|
||||||
|
await ensureAdminTable();
|
||||||
|
const result = await pool.query(
|
||||||
|
`SELECT email, created_at FROM admin_users WHERE id = 1`,
|
||||||
|
);
|
||||||
|
if (result.rowCount && result.rowCount > 0) {
|
||||||
|
const row = result.rows[0] as { email: string; created_at: Date | string };
|
||||||
|
return {
|
||||||
|
email: row.email,
|
||||||
|
createdAt: new Date(row.created_at).toISOString(),
|
||||||
|
storageMode: "PostgreSQL" as const,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
// Fall back to in-memory admin
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const inMem = await getOrInitInMemoryAdmin();
|
||||||
|
return {
|
||||||
|
email: fallbackEmail || inMem.email,
|
||||||
|
createdAt: inMem.createdAt.toISOString(),
|
||||||
|
storageMode: "In-Memory" as const,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function updateAdminAccount({
|
||||||
|
currentEmail,
|
||||||
|
currentPassword,
|
||||||
|
nextEmail,
|
||||||
|
nextPassword,
|
||||||
|
}: {
|
||||||
|
currentEmail: string;
|
||||||
|
currentPassword: string;
|
||||||
|
nextEmail: string;
|
||||||
|
nextPassword?: string;
|
||||||
|
}) {
|
||||||
|
const verified = await verifyAdminCredentials(currentEmail, currentPassword);
|
||||||
|
if (!verified) {
|
||||||
|
return { ok: false as const, error: "Current password is incorrect." };
|
||||||
|
}
|
||||||
|
|
||||||
|
const cleanEmail = nextEmail.trim().toLowerCase();
|
||||||
|
const passwordToSave =
|
||||||
|
nextPassword && nextPassword.length > 0 ? nextPassword : currentPassword;
|
||||||
|
const salt = randomBytes(PASSWORD_SALT_BYTES);
|
||||||
|
const passwordHash = await derivePasswordHash(passwordToSave, salt);
|
||||||
|
|
||||||
|
const pool = getPool();
|
||||||
|
if (pool) {
|
||||||
|
try {
|
||||||
|
await ensureAdminTable();
|
||||||
|
const updated = await pool.query(
|
||||||
|
`UPDATE admin_users
|
||||||
|
SET email = $1, password_salt = $2, password_hash = $3
|
||||||
|
WHERE id = 1`,
|
||||||
|
[cleanEmail, salt, passwordHash],
|
||||||
|
);
|
||||||
|
if (updated.rowCount && updated.rowCount > 0) {
|
||||||
|
return { ok: true as const, email: cleanEmail };
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
// Fall back to in-memory update
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const existing = await getOrInitInMemoryAdmin();
|
||||||
|
globals.__dataStackInMemoryAdmin = {
|
||||||
|
id: 1,
|
||||||
|
email: cleanEmail,
|
||||||
|
passwordSalt: salt,
|
||||||
|
passwordHash,
|
||||||
|
createdAt: existing.createdAt,
|
||||||
|
};
|
||||||
|
return { ok: true as const, email: cleanEmail };
|
||||||
|
}
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
// In-memory Stale-While-Revalidate (SWR) cache for VCON Admin Control Panel views.
|
||||||
|
// Ensures 0ms instant state hydration when navigating across /vcon/* routes while
|
||||||
|
// silently refreshing live telemetry, clients, storage, settings, and profile data in the background.
|
||||||
|
|
||||||
|
const memoryStore = new Map<string, unknown>();
|
||||||
|
|
||||||
|
export function getCached<T>(key: string, fallback: T): T {
|
||||||
|
if (memoryStore.has(key)) {
|
||||||
|
return memoryStore.get(key) as T;
|
||||||
|
}
|
||||||
|
return fallback;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function setCached<T>(key: string, value: T): T {
|
||||||
|
memoryStore.set(key, value);
|
||||||
|
return value;
|
||||||
|
}
|
||||||
Binary file not shown.
|
After Width: | Height: | Size: 78 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 37 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 46 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 66 KiB |
Reference in new issue
Block a user