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
+892
-342
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 { StatStrip } from '@/components/ui/StatStrip';
|
||||
import { useToast } from '@/components/ui/Toast';
|
||||
import { getCached, setCached } from '@/lib/vconCache';
|
||||
import { useCallback, useEffect, useMemo, useState } from 'react';
|
||||
|
||||
export default function ClientsPage() {
|
||||
const { error } = useToast();
|
||||
const [modalOpen, setModalOpen] = useState(false);
|
||||
const [clients, setClients] = useState<ClientItem[]>([]);
|
||||
const [clients, setClients] = useState<ClientItem[]>(() => getCached<ClientItem[]>('vcon:clients', []));
|
||||
const [search, setSearch] = useState('');
|
||||
const [statusFilter, setStatusFilter] = useState<ClientStatusFilter>('all');
|
||||
const [now, setNow] = useState(0);
|
||||
const [now, setNow] = useState(() => Date.now());
|
||||
|
||||
const fetchClients = useCallback(async () => {
|
||||
const response = await fetch('/api/clients');
|
||||
if (!response.ok) throw new Error('Unable to load clients');
|
||||
const data = await response.json();
|
||||
setClients(data.clients || []);
|
||||
setClients(setCached('vcon:clients', data.clients || []));
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
fetchClients().catch(() => {
|
||||
setClients([]);
|
||||
error('Unable to load clients', 'Could not fetch registered clients.');
|
||||
});
|
||||
}, [error, fetchClients]);
|
||||
|
||||
@@ -0,0 +1,5 @@
|
||||
import { ProfileWorkspace } from '@/components/sections/ProfileWorkspace';
|
||||
|
||||
export default function ProfilePage() {
|
||||
return <ProfileWorkspace />;
|
||||
}
|
||||
+42
-36
@@ -7,12 +7,16 @@ import { CodeBlock } from '@/components/ui/CodeBlock';
|
||||
import { Select } from '@/components/ui/Input';
|
||||
import { Panel } from '@/components/ui/Panel';
|
||||
import { useToast } from '@/components/ui/Toast';
|
||||
import { getCached, setCached } from '@/lib/vconCache';
|
||||
import { useEffect, useState } from 'react';
|
||||
|
||||
export default function SdkGuidePage() {
|
||||
const { success } = useToast();
|
||||
const [clients, setClients] = useState<any[]>([]);
|
||||
const [selectedClientId, setSelectedClientId] = useState<string>('');
|
||||
const [clients, setClients] = useState<any[]>(() => getCached<any[]>('vcon:clients', []));
|
||||
const [selectedClientId, setSelectedClientId] = useState<string>(() => {
|
||||
const cached = getCached<any[]>('vcon:clients', []);
|
||||
return cached[0]?.clientId ?? '';
|
||||
});
|
||||
|
||||
useEffect(() => {
|
||||
async function loadClients() {
|
||||
@@ -20,10 +24,10 @@ export default function SdkGuidePage() {
|
||||
const res = await fetch('/api/clients');
|
||||
if (res.ok) {
|
||||
const data = await res.json();
|
||||
const list = data.clients || [];
|
||||
const list = setCached('vcon:clients', data.clients || []);
|
||||
setClients(list);
|
||||
if (list.length > 0) {
|
||||
setSelectedClientId(list[0].clientId);
|
||||
setSelectedClientId((prev) => prev || list[0].clientId);
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
@@ -65,7 +69,7 @@ if client.connect():
|
||||
};
|
||||
|
||||
return (
|
||||
<section className="flex w-full flex-col gap-2.5">
|
||||
<section className="w-full">
|
||||
<AdminPageHeader
|
||||
title="Python SDK"
|
||||
actions={
|
||||
@@ -80,38 +84,40 @@ if client.connect():
|
||||
}
|
||||
/>
|
||||
|
||||
<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>
|
||||
<Button
|
||||
size="xs"
|
||||
variant="ghost"
|
||||
icon="Copy"
|
||||
onClick={() => copySnippet('pip install ./sdk-python', 'Pip command')}
|
||||
/>
|
||||
</Card>
|
||||
<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]">
|
||||
<span className="text-[var(--accent)]">pip install ./sdk-python</span>
|
||||
<Button
|
||||
size="xs"
|
||||
variant="ghost"
|
||||
icon="Copy"
|
||||
onClick={() => copySnippet('pip install ./sdk-python', 'Pip command')}
|
||||
/>
|
||||
</Card>
|
||||
|
||||
<Panel
|
||||
title="Client Snippet"
|
||||
action={
|
||||
clients.length > 0 ? (
|
||||
<div className="w-[170px]">
|
||||
<Select
|
||||
compact
|
||||
value={selectedClientId}
|
||||
onChange={(e) => setSelectedClientId(e.target.value)}
|
||||
>
|
||||
{clients.map((c) => (
|
||||
<option key={c.clientId} value={c.clientId}>
|
||||
{c.clientId}
|
||||
</option>
|
||||
))}
|
||||
</Select>
|
||||
</div>
|
||||
) : undefined
|
||||
}
|
||||
>
|
||||
<CodeBlock>{pythonSnippet}</CodeBlock>
|
||||
</Panel>
|
||||
<Panel
|
||||
title="Client Snippet"
|
||||
action={
|
||||
clients.length > 0 ? (
|
||||
<div className="w-[170px]">
|
||||
<Select
|
||||
compact
|
||||
value={selectedClientId}
|
||||
onChange={(e) => setSelectedClientId(e.target.value)}
|
||||
>
|
||||
{clients.map((c) => (
|
||||
<option key={c.clientId} value={c.clientId}>
|
||||
{c.clientId}
|
||||
</option>
|
||||
))}
|
||||
</Select>
|
||||
</div>
|
||||
) : undefined
|
||||
}
|
||||
>
|
||||
<CodeBlock>{pythonSnippet}</CodeBlock>
|
||||
</Panel>
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -6,12 +6,16 @@ import { CodeBlock } from '@/components/ui/CodeBlock';
|
||||
import { Select, Textarea } from '@/components/ui/Input';
|
||||
import { Panel } from '@/components/ui/Panel';
|
||||
import { useToast } from '@/components/ui/Toast';
|
||||
import { getCached, setCached } from '@/lib/vconCache';
|
||||
import { useEffect, useState } from 'react';
|
||||
|
||||
export default function SimulatorPage() {
|
||||
const { success, error } = useToast();
|
||||
const [clients, setClients] = useState<any[]>([]);
|
||||
const [selectedClient, setSelectedClient] = useState<string>('');
|
||||
const [clients, setClients] = useState<any[]>(() => getCached<any[]>('vcon:clients', []));
|
||||
const [selectedClient, setSelectedClient] = useState<string>(() => {
|
||||
const cached = getCached<any[]>('vcon:clients', []);
|
||||
return cached[0]?.clientId ?? '';
|
||||
});
|
||||
const [payloadText, setPayloadText] = useState<string>(
|
||||
JSON.stringify(
|
||||
{
|
||||
@@ -34,9 +38,9 @@ export default function SimulatorPage() {
|
||||
const res = await fetch('/api/clients');
|
||||
if (res.ok) {
|
||||
const data = await res.json();
|
||||
const list = data.clients || [];
|
||||
const list = setCached('vcon:clients', data.clients || []);
|
||||
setClients(list);
|
||||
if (list.length > 0) setSelectedClient(list[0].clientId);
|
||||
if (list.length > 0) setSelectedClient((prev) => prev || list[0].clientId);
|
||||
}
|
||||
} catch {
|
||||
// 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">
|
||||
<Select
|
||||
compact
|
||||
|
||||
@@ -15,12 +15,13 @@ import {
|
||||
TableWrap,
|
||||
} from '@/components/ui/Table';
|
||||
import { useToast } from '@/components/ui/Toast';
|
||||
import { getCached, setCached } from '@/lib/vconCache';
|
||||
import { useCallback, useEffect, useState } from 'react';
|
||||
|
||||
export default function StoragePage() {
|
||||
const { success, error } = useToast();
|
||||
const [stats, setStats] = useState<any>(null);
|
||||
const [files, setFiles] = useState<any[]>([]);
|
||||
const [stats, setStats] = useState<any>(() => getCached<any>('vcon:storage-stats', null));
|
||||
const [files, setFiles] = useState<any[]>(() => getCached<any[]>('vcon:storage-files', []));
|
||||
const [flushing, setFlushing] = useState(false);
|
||||
|
||||
const fetchStorageData = useCallback(async () => {
|
||||
@@ -28,8 +29,8 @@ export default function StoragePage() {
|
||||
const res = await fetch('/api/storage');
|
||||
if (!res.ok) throw new Error('Unable to load storage partitions');
|
||||
const data = await res.json();
|
||||
setStats(data.stats);
|
||||
setFiles(data.files || []);
|
||||
setStats(setCached('vcon:storage-stats', data.stats));
|
||||
setFiles(setCached('vcon:storage-files', data.files || []));
|
||||
} catch {
|
||||
error('Storage load failed', 'Could not load storage partitions.');
|
||||
}
|
||||
|
||||
@@ -1,3 +1,4 @@
|
||||
import Link from 'next/link';
|
||||
import React from 'react';
|
||||
|
||||
interface AdminPageHeaderProps {
|
||||
@@ -7,8 +8,21 @@ interface AdminPageHeaderProps {
|
||||
|
||||
export function AdminPageHeader({ title, actions }: AdminPageHeaderProps) {
|
||||
return (
|
||||
<header className="mb-3 flex flex-wrap items-center justify-between gap-2">
|
||||
<h1 className="text-[14px] font-medium tracking-tight text-[var(--text)]">{title}</h1>
|
||||
<header className="mb-3 flex min-h-8 flex-wrap items-center justify-between gap-2 border-b border-[var(--border)] pb-2.5">
|
||||
<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>}
|
||||
</header>
|
||||
);
|
||||
|
||||
@@ -1,6 +1,5 @@
|
||||
'use client';
|
||||
|
||||
import { cn } from '@/lib/utils';
|
||||
import React, { useState } from 'react';
|
||||
import { Footer } from './Footer';
|
||||
import { Navbar } from './Navbar';
|
||||
@@ -17,32 +16,38 @@ export const MainLayout: React.FC<MainLayoutProps> = ({
|
||||
}) => {
|
||||
const [sidebarOpen, setSidebarOpen] = useState(false);
|
||||
|
||||
if (showSidebar) {
|
||||
return (
|
||||
<div className="min-h-dvh bg-[var(--bg-main)] text-[var(--text)] antialiased md:grid md:grid-cols-[184px_1fr]">
|
||||
<Sidebar
|
||||
isOpen={sidebarOpen}
|
||||
onClose={() => setSidebarOpen(false)}
|
||||
/>
|
||||
<div className="flex min-h-dvh min-w-0 flex-col">
|
||||
<Navbar
|
||||
showSidebarToggle={true}
|
||||
onToggleSidebar={() => setSidebarOpen((prev) => !prev)}
|
||||
/>
|
||||
<main className="flex flex-1 min-w-0 flex-col">
|
||||
<div className="w-full max-w-[var(--console-width)] flex-1 px-3.5 py-3 sm:px-5 sm:py-3.5">
|
||||
{children}
|
||||
</div>
|
||||
<Footer isAdmin={true} />
|
||||
</main>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="min-h-dvh flex flex-col bg-[var(--bg-main)] text-[var(--text)] antialiased">
|
||||
<Navbar
|
||||
showSidebarToggle={showSidebar}
|
||||
onToggleSidebar={() => setSidebarOpen((prev) => !prev)}
|
||||
/>
|
||||
|
||||
<div className="flex-1 flex min-h-0 min-w-0 overflow-hidden">
|
||||
{showSidebar && (
|
||||
<Sidebar
|
||||
isOpen={sidebarOpen}
|
||||
onClose={() => setSidebarOpen(false)}
|
||||
/>
|
||||
)}
|
||||
<main className="flex-1 min-h-0 overflow-y-auto flex flex-col min-w-0">
|
||||
<div className={cn(
|
||||
'flex-1 min-w-0 w-full mx-auto',
|
||||
showSidebar
|
||||
? 'max-w-[var(--console-width)] px-3.5 py-3 sm:px-5 sm:py-4'
|
||||
: 'max-w-[var(--container-width)] px-6 py-0'
|
||||
)}>
|
||||
{children}
|
||||
</div>
|
||||
<Footer isAdmin={showSidebar} />
|
||||
</main>
|
||||
</div>
|
||||
<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>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -10,6 +10,18 @@ interface NavbarProps {
|
||||
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> = ({
|
||||
onToggleSidebar,
|
||||
showSidebarToggle = false,
|
||||
@@ -34,24 +46,44 @@ export const Navbar: React.FC<NavbarProps> = ({
|
||||
};
|
||||
|
||||
const isVcon = pathname?.startsWith('/vcon');
|
||||
const currentSectionLabel = (pathname && VCON_LABELS[pathname]) || 'Console';
|
||||
|
||||
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">
|
||||
{/* Left: Mobile hamburger + Brand */}
|
||||
<div className="flex items-center gap-2.5 min-w-0">
|
||||
{showSidebarToggle && (
|
||||
if (showSidebarToggle && isVcon) {
|
||||
return (
|
||||
<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">
|
||||
<div className="flex min-w-0 items-center gap-2">
|
||||
<Button
|
||||
type="button"
|
||||
variant="icon"
|
||||
size="icon"
|
||||
icon="Menu"
|
||||
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"
|
||||
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">
|
||||
<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)]" />
|
||||
@@ -62,44 +94,12 @@ export const Navbar: React.FC<NavbarProps> = ({
|
||||
</Link>
|
||||
</div>
|
||||
|
||||
{/* Middle: Links */}
|
||||
<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="#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="#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="#about" className="text-[var(--text-muted)] hover:text-[var(--text)] whitespace-nowrap shrink-0">About</Link>
|
||||
</nav>
|
||||
|
||||
{/* Right: Theme switcher or public CTA */}
|
||||
<div className="flex items-center gap-2 shrink-0">
|
||||
<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)]"
|
||||
/>
|
||||
|
||||
{!isVcon && (
|
||||
<Link href="#sdk">
|
||||
<Button size="xs" variant="primary">
|
||||
SDK Guide
|
||||
</Button>
|
||||
</Link>
|
||||
)}
|
||||
<Link href="/vcon/dashboard">
|
||||
<Button size="xs" variant="primary">
|
||||
Console
|
||||
</Button>
|
||||
</Link>
|
||||
</div>
|
||||
</header>
|
||||
);
|
||||
|
||||
+151
-130
@@ -4,7 +4,7 @@ import { Button } from '@/components/ui/Button';
|
||||
import { Icon } from '@/components/ui/Icon';
|
||||
import { cn } from '@/lib/utils';
|
||||
import Link from 'next/link';
|
||||
import { usePathname, useRouter } from 'next/navigation';
|
||||
import { usePathname } from 'next/navigation';
|
||||
import React, { useEffect, useState } from 'react';
|
||||
|
||||
interface SidebarProps {
|
||||
@@ -12,176 +12,197 @@ interface SidebarProps {
|
||||
onClose?: () => void;
|
||||
}
|
||||
|
||||
const NAVIGATION_SECTIONS = [
|
||||
{
|
||||
group: 'Main',
|
||||
items: [
|
||||
{ name: 'Dashboard', href: '/vcon/dashboard', icon: 'LayoutDashboard' },
|
||||
{ name: 'Events', href: '/vcon/data', icon: 'Activity' },
|
||||
{ name: 'Clients', href: '/vcon/clients', icon: 'Key' },
|
||||
{ name: 'Export', href: '/vcon/export', icon: 'Download' },
|
||||
{ name: 'Storage', href: '/vcon/storage', icon: 'HardDrive' },
|
||||
],
|
||||
},
|
||||
{
|
||||
group: 'System',
|
||||
items: [
|
||||
{ name: 'Python SDK', href: '/vcon/sdk', icon: 'FileCode2' },
|
||||
{ name: 'Simulator', href: '/vcon/simulator', icon: 'Play' },
|
||||
{ name: 'Settings', href: '/vcon/settings', icon: 'Sliders' },
|
||||
{ name: 'Profile', href: '/vcon/profile', icon: 'User' },
|
||||
],
|
||||
},
|
||||
];
|
||||
|
||||
export const Sidebar: React.FC<SidebarProps> = ({
|
||||
isOpen = false,
|
||||
onClose,
|
||||
}) => {
|
||||
const pathname = usePathname();
|
||||
const router = useRouter();
|
||||
const [isSigningOut, setIsSigningOut] = useState(false);
|
||||
const [signOutError, setSignOutError] = useState('');
|
||||
|
||||
const navigation = [
|
||||
{
|
||||
group: 'Monitoring',
|
||||
items: [
|
||||
{ name: 'Dashboard', href: '/vcon/dashboard', icon: 'LayoutDashboard' },
|
||||
{ name: 'Events', href: '/vcon/data', icon: 'Activity' },
|
||||
],
|
||||
},
|
||||
{
|
||||
group: 'Data',
|
||||
items: [
|
||||
{ name: 'Export', href: '/vcon/export', icon: 'Download' },
|
||||
{ name: 'Storage', href: '/vcon/storage', icon: 'HardDrive' },
|
||||
],
|
||||
},
|
||||
{
|
||||
group: 'Administration',
|
||||
items: [
|
||||
{ name: 'Clients', href: '/vcon/clients', icon: 'Key' },
|
||||
{ name: 'Settings', href: '/vcon/settings', icon: 'Sliders' },
|
||||
],
|
||||
},
|
||||
{
|
||||
group: 'Tools',
|
||||
items: [
|
||||
{ name: 'Python SDK', href: '/vcon/sdk', icon: 'FileCode2' },
|
||||
{ name: 'Simulator', href: '/vcon/simulator', icon: 'Play' },
|
||||
],
|
||||
},
|
||||
];
|
||||
const activeGroup = navigation.find((section) =>
|
||||
section.items.some((item) => item.href === pathname)
|
||||
)?.group;
|
||||
const [openGroup, setOpenGroup] = useState(activeGroup ?? navigation[0].group);
|
||||
const [theme, setTheme] = useState<'dark' | 'light'>('dark');
|
||||
|
||||
useEffect(() => {
|
||||
if (activeGroup) setOpenGroup(activeGroup);
|
||||
}, [activeGroup]);
|
||||
const saved = localStorage.getItem('datastack-theme') as 'dark' | 'light' | null;
|
||||
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 () => {
|
||||
setIsSigningOut(true);
|
||||
setSignOutError('');
|
||||
try {
|
||||
const response = await fetch('/api/auth/logout', {
|
||||
method: 'POST',
|
||||
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');
|
||||
} catch (error) {
|
||||
setSignOutError(
|
||||
error instanceof Error ? error.message : 'Unable to sign out. Please try again.',
|
||||
);
|
||||
} finally {
|
||||
} catch {
|
||||
setIsSigningOut(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
{/* Mobile Backdrop */}
|
||||
{isOpen && (
|
||||
<div
|
||||
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
|
||||
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'
|
||||
)}
|
||||
>
|
||||
{/* Mobile Close 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">
|
||||
<span className="text-[11px] font-medium text-[var(--text-muted)]">Menu</span>
|
||||
<button
|
||||
{/* Brand Header */}
|
||||
<div className="flex h-10 shrink-0 items-center justify-between border-b border-[var(--border)] px-3">
|
||||
<Link
|
||||
href="/vcon/dashboard"
|
||||
onClick={onClose}
|
||||
className="text-[var(--text-dim)] hover:text-[var(--text)] p-1 cursor-pointer"
|
||||
aria-label="Close menu"
|
||||
className="flex min-w-0 items-center gap-2 text-[12.5px] font-medium text-[var(--text)]"
|
||||
>
|
||||
<Icon name="X" size={12} />
|
||||
</button>
|
||||
<span className="grid h-3 w-3 shrink-0 place-items-center bg-[var(--accent)]">
|
||||
<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>
|
||||
|
||||
{/* Navigation items */}
|
||||
<nav aria-label="Admin navigation" className="flex-1 min-h-0 overflow-y-auto p-1.5 flex flex-col">
|
||||
{navigation.map((section) => {
|
||||
const isExpanded = openGroup === section.group;
|
||||
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>
|
||||
<Icon
|
||||
name="ChevronDown"
|
||||
size={11}
|
||||
className={cn('transition-transform', isExpanded && 'rotate-180')}
|
||||
/>
|
||||
</button>
|
||||
{isExpanded && (
|
||||
<div id={groupId} className="pb-1 flex flex-col gap-0.5">
|
||||
{section.items.map((item) => {
|
||||
const isActive = pathname === item.href;
|
||||
return (
|
||||
<Link
|
||||
key={item.href}
|
||||
href={item.href}
|
||||
onClick={onClose}
|
||||
className={cn(
|
||||
'flex h-8 min-w-0 items-center gap-2 px-2.5 text-[12px] transition-colors border',
|
||||
isActive
|
||||
? 'bg-[var(--accent-soft)] text-[var(--accent-hover)] font-medium border-[var(--accent)]'
|
||||
: 'border-transparent text-[var(--text-muted)] hover:text-[var(--text)] hover:bg-[var(--bg-hover)]'
|
||||
)}
|
||||
>
|
||||
<Icon
|
||||
name={item.icon}
|
||||
size={13}
|
||||
className={isActive ? 'text-[var(--accent)]' : 'text-[var(--text-dim)]'}
|
||||
/>
|
||||
<span className="truncate">{item.name}</span>
|
||||
</Link>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
{/* Clean 2-Group Navigation */}
|
||||
<nav
|
||||
aria-label="Admin navigation"
|
||||
className="flex-1 overflow-y-auto px-2 py-2.5 flex flex-col gap-3.5"
|
||||
>
|
||||
{NAVIGATION_SECTIONS.map((section) => (
|
||||
<div key={section.group} className="flex flex-col gap-0.5">
|
||||
<div className="px-2 pb-1 text-[9.5px] font-medium uppercase tracking-wider text-[var(--text-faint)]">
|
||||
{section.group}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
{section.items.map((item) => {
|
||||
const isActive = pathname === item.href;
|
||||
return (
|
||||
<Link
|
||||
key={item.href}
|
||||
href={item.href}
|
||||
onClick={onClose}
|
||||
className={cn(
|
||||
'flex h-7 min-w-0 items-center gap-2 border-l-2 px-2 text-[12px] transition-colors select-none',
|
||||
isActive
|
||||
? 'border-l-[var(--accent)] bg-[var(--surface-2)] font-medium text-[var(--text)]'
|
||||
: 'border-l-transparent text-[var(--text-muted)] hover:bg-[var(--surface-2)] hover:text-[var(--text)]'
|
||||
)}
|
||||
>
|
||||
<Icon
|
||||
name={item.icon}
|
||||
size={13}
|
||||
className={isActive ? 'text-[var(--accent)]' : 'text-[var(--text-faint)]'}
|
||||
/>
|
||||
<span className="truncate">{item.name}</span>
|
||||
</Link>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
))}
|
||||
</nav>
|
||||
|
||||
{/* Sign out action */}
|
||||
{pathname !== '/vcon/setup' && (
|
||||
<div className="p-1.5 border-t border-[var(--border)] bg-[var(--bg-main)] shrink-0">
|
||||
{signOutError && (
|
||||
<p role="alert" className="px-2 pb-1 text-[11px] text-[var(--danger)]">{signOutError}</p>
|
||||
)}
|
||||
<Button
|
||||
type="button"
|
||||
variant="ghost"
|
||||
size="xs"
|
||||
icon="LogOut"
|
||||
loading={isSigningOut}
|
||||
disabled={isSigningOut}
|
||||
onClick={signOut}
|
||||
className="w-full justify-start px-2.5 text-[11.5px] h-7"
|
||||
>
|
||||
Sign out
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
{/* Bottom Dock: Identity + Theme Toggle + Sign Out */}
|
||||
<div className="flex shrink-0 items-center gap-1 border-t border-[var(--border)] bg-[var(--bg)] px-2.5 py-2">
|
||||
<Link
|
||||
href="/vcon/profile"
|
||||
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
|
||||
type="button"
|
||||
variant="icon"
|
||||
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"
|
||||
loading={isSigningOut}
|
||||
disabled={isSigningOut}
|
||||
onClick={signOut}
|
||||
title="Sign out"
|
||||
aria-label="Sign out"
|
||||
className="h-6 w-6 border border-[var(--border)] bg-[var(--surface)] hover:border-[var(--danger)] hover:text-[var(--danger)]"
|
||||
/>
|
||||
</div>
|
||||
</aside>
|
||||
</>
|
||||
);
|
||||
|
||||
@@ -15,6 +15,7 @@ import {
|
||||
TableWrap,
|
||||
} from '@/components/ui/Table';
|
||||
import { useToast } from '@/components/ui/Toast';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { useState } from 'react';
|
||||
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) {
|
||||
const router = useRouter();
|
||||
const { success, error } = useToast();
|
||||
const [credentials, setCredentials] = useState<ClientCredentials | null>(null);
|
||||
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)]"
|
||||
title={`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
|
||||
type="button"
|
||||
|
||||
@@ -4,7 +4,7 @@ import { AdminPageHeader } from '@/components/layout/AdminPageHeader';
|
||||
import { Button } from '@/components/ui/Button';
|
||||
import { ClientList, type ClientListItem } from '@/components/ui/ClientList';
|
||||
import { Panel } from '@/components/ui/Panel';
|
||||
import { StatCard } from '@/components/ui/StatCard';
|
||||
import { StatStrip } from '@/components/ui/StatStrip';
|
||||
import {
|
||||
Table,
|
||||
TableBody,
|
||||
@@ -14,6 +14,7 @@ import {
|
||||
TableRow,
|
||||
TableWrap,
|
||||
} from '@/components/ui/Table';
|
||||
import { getCached, setCached } from '@/lib/vconCache';
|
||||
import Link from 'next/link';
|
||||
import React, { useCallback, useEffect, useState } from 'react';
|
||||
|
||||
@@ -48,10 +49,10 @@ type StorageFile = {
|
||||
};
|
||||
|
||||
export const DashboardOverview: React.FC = () => {
|
||||
const [metrics, setMetrics] = useState<DashboardMetrics | null>(null);
|
||||
const [events, setEvents] = useState<EventItem[]>([]);
|
||||
const [clients, setClients] = useState<ClientListItem[]>([]);
|
||||
const [files, setFiles] = useState<StorageFile[]>([]);
|
||||
const [metrics, setMetrics] = useState<DashboardMetrics | null>(() => getCached<DashboardMetrics | null>('vcon:metrics', null));
|
||||
const [events, setEvents] = useState<EventItem[]>(() => getCached<EventItem[]>('vcon:dashboard-events', []));
|
||||
const [clients, setClients] = useState<ClientListItem[]>(() => getCached<ClientListItem[]>('vcon:clients', []));
|
||||
const [files, setFiles] = useState<StorageFile[]>(() => getCached<StorageFile[]>('vcon:storage-files', []));
|
||||
const [isRefreshing, setIsRefreshing] = useState(false);
|
||||
|
||||
const refresh = useCallback(async () => {
|
||||
@@ -64,18 +65,22 @@ export const DashboardOverview: React.FC = () => {
|
||||
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) {
|
||||
const data = await eventsResponse.json();
|
||||
setEvents(data.events ?? []);
|
||||
setEvents(setCached('vcon:dashboard-events', data.events ?? []));
|
||||
}
|
||||
if (storageResponse.ok) {
|
||||
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) {
|
||||
const data = await clientsResponse.json();
|
||||
setClients(data.clients ?? []);
|
||||
setClients(setCached('vcon:clients', data.clients ?? []));
|
||||
}
|
||||
} catch {
|
||||
// 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">
|
||||
<StatCard
|
||||
label="Events today"
|
||||
value={eventsToday.toLocaleString()}
|
||||
/>
|
||||
<StatCard
|
||||
label="Active clients"
|
||||
value={`${activeClients} / ${totalClients}`}
|
||||
/>
|
||||
<StatCard
|
||||
label="Storage used"
|
||||
value={storageValue}
|
||||
unit={storageUnit}
|
||||
/>
|
||||
<StatCard
|
||||
label="Stored rows"
|
||||
value={totalRows.toLocaleString()}
|
||||
/>
|
||||
</div>
|
||||
<StatStrip
|
||||
items={[
|
||||
{ label: 'Events today', 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() },
|
||||
]}
|
||||
/>
|
||||
|
||||
<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
|
||||
title="Recent events"
|
||||
meta={`${events.length}`}
|
||||
|
||||
@@ -16,6 +16,7 @@ import {
|
||||
TableRow,
|
||||
TableWrap,
|
||||
} from '@/components/ui/Table';
|
||||
import { useRouter } from 'next/navigation';
|
||||
import { useCallback, useEffect, useState } from 'react';
|
||||
|
||||
interface StreamEvent {
|
||||
@@ -34,6 +35,7 @@ interface Client {
|
||||
const PAGE_SIZE = 12;
|
||||
|
||||
export function DataBrowser() {
|
||||
const router = useRouter();
|
||||
const [events, setEvents] = useState<StreamEvent[]>([]);
|
||||
const [clients, setClients] = useState<Client[]>([]);
|
||||
const [total, setTotal] = useState(0);
|
||||
@@ -150,7 +152,7 @@ export function DataBrowser() {
|
||||
variant="primary"
|
||||
size="xs"
|
||||
icon="Download"
|
||||
onClick={() => window.location.assign('/vcon/export')}
|
||||
onClick={() => router.push('/vcon/export')}
|
||||
>
|
||||
Export CSV
|
||||
</Button>
|
||||
|
||||
@@ -7,7 +7,9 @@ import { Panel } from '@/components/ui/Panel';
|
||||
import { Pill } from '@/components/ui/Pill';
|
||||
import { StatStrip } from '@/components/ui/StatStrip';
|
||||
import { useToast } from '@/components/ui/Toast';
|
||||
import { getCached, setCached } from '@/lib/vconCache';
|
||||
import { Braces, FileText } from 'lucide-react';
|
||||
import Link from 'next/link';
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
|
||||
interface Client {
|
||||
@@ -48,22 +50,18 @@ function relativeTime(value: string, now: number) {
|
||||
|
||||
export function ExportWorkspace() {
|
||||
const { error, info } = useToast();
|
||||
const [clients, setClients] = useState<Client[]>([]);
|
||||
const [files, setFiles] = useState<StorageFile[]>([]);
|
||||
const [clients, setClients] = useState<Client[]>(() => getCached<Client[]>('vcon:clients', []));
|
||||
const [files, setFiles] = useState<StorageFile[]>(() => getCached<StorageFile[]>('vcon:storage-files', []));
|
||||
const [selectedClient, setSelectedClient] = useState('all');
|
||||
const [fromDate, setFromDate] = useState('');
|
||||
const [toDate, setToDate] = useState('');
|
||||
const [fromDate, setFromDate] = useState(() => dateString(new Date()));
|
||||
const [toDate, setToDate] = useState(() => dateString(new Date()));
|
||||
const [format, setFormat] = useState<ExportFormat>('csv');
|
||||
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 [now, setNow] = useState(0);
|
||||
const [now, setNow] = useState(() => Date.now());
|
||||
|
||||
useEffect(() => {
|
||||
const today = dateString(new Date());
|
||||
setFromDate(today);
|
||||
setToDate(today);
|
||||
|
||||
Promise.all([
|
||||
fetch('/api/clients').then(async (response) => {
|
||||
if (!response.ok) throw new Error('Unable to load clients');
|
||||
@@ -75,8 +73,9 @@ export function ExportWorkspace() {
|
||||
}),
|
||||
])
|
||||
.then(([clientData, storageData]) => {
|
||||
setClients(clientData.clients || []);
|
||||
setFiles(storageData.files || []);
|
||||
setClients(setCached('vcon:clients', clientData.clients || []));
|
||||
setFiles(setCached('vcon:storage-files', storageData.files || []));
|
||||
if (storageData.stats) setCached('vcon:storage-stats', storageData.stats);
|
||||
setLoadError('');
|
||||
})
|
||||
.catch((fetchError) => {
|
||||
@@ -164,7 +163,7 @@ export function ExportWorkspace() {
|
||||
};
|
||||
|
||||
return (
|
||||
<section className="mx-auto w-full max-w-[var(--console-width)]">
|
||||
<section className="w-full">
|
||||
<AdminPageHeader title="Export" />
|
||||
|
||||
<StatStrip
|
||||
@@ -176,8 +175,8 @@ export function ExportWorkspace() {
|
||||
]}
|
||||
/>
|
||||
|
||||
<div className="grid grid-cols-1 items-start gap-2.5 xl:grid-cols-5">
|
||||
<Panel title="Export builder" bodyClassName="flex flex-col gap-3 p-3" className="min-w-0 xl:col-span-3">
|
||||
<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 lg:col-span-3">
|
||||
<div className="flex flex-wrap items-center gap-1">
|
||||
<span className="mr-1 text-[10px] uppercase tracking-wider text-[var(--text-faint)]">Range</span>
|
||||
{([
|
||||
@@ -241,9 +240,9 @@ export function ExportWorkspace() {
|
||||
|
||||
<Panel
|
||||
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)]"
|
||||
className="min-w-0 xl:col-span-2"
|
||||
className="min-w-0 lg:col-span-2"
|
||||
>
|
||||
{loading ? (
|
||||
<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 { SettingsField, SettingsGroup, SettingsTabs } from '@/components/ui/SettingsLayout';
|
||||
import { useToast } from '@/components/ui/Toast';
|
||||
import { getCached, setCached } from '@/lib/vconCache';
|
||||
import { useEffect, useMemo, useState } from 'react';
|
||||
|
||||
interface EditableSettings {
|
||||
@@ -45,15 +46,15 @@ type TabId = (typeof TABS)[number]['id'];
|
||||
|
||||
export function SettingsWorkspace() {
|
||||
const { success, error } = useToast();
|
||||
const [settings, setSettings] = useState<EditableSettings>(DEFAULT_SETTINGS);
|
||||
const [savedSettings, setSavedSettings] = useState<EditableSettings>(DEFAULT_SETTINGS);
|
||||
const [settings, setSettings] = useState<EditableSettings>(() => getCached<EditableSettings>('vcon:settings', DEFAULT_SETTINGS));
|
||||
const [savedSettings, setSavedSettings] = useState<EditableSettings>(() => getCached<EditableSettings>('vcon:settings', DEFAULT_SETTINGS));
|
||||
const [activeTab, setActiveTab] = useState<TabId>('general');
|
||||
const [jwtSecret, setJwtSecret] = useState('');
|
||||
const [storagePath, setStoragePath] = useState('');
|
||||
const [storagePath, setStoragePath] = useState(() => getCached<string>('vcon:storage-path', ''));
|
||||
const [baseUrl, setBaseUrl] = useState('');
|
||||
const [webSocketUrl, setWebSocketUrl] = useState('');
|
||||
const [serverPort, setServerPort] = useState(4000);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [serverPort, setServerPort] = useState(() => getCached<number>('vcon:server-port', 4000));
|
||||
const [loading, setLoading] = useState(() => !getCached<boolean>('vcon:settings-loaded', false));
|
||||
const [saving, setSaving] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
@@ -85,10 +86,11 @@ export function SettingsWorkspace() {
|
||||
enableIdempotency: Boolean(settingsData.settings.enableIdempotency ?? DEFAULT_SETTINGS.enableIdempotency),
|
||||
autoPruneDays: Number(settingsData.settings.autoPruneDays ?? DEFAULT_SETTINGS.autoPruneDays),
|
||||
};
|
||||
setSettings(loaded);
|
||||
setSettings(setCached('vcon:settings', loaded));
|
||||
setSavedSettings(loaded);
|
||||
setServerPort(Number((settingsData.settings as PublicSettings).serverPort ?? 4000));
|
||||
setStoragePath(String(storageData.stats?.storageDirectory ?? ''));
|
||||
setServerPort(setCached('vcon:server-port', Number((settingsData.settings as PublicSettings).serverPort ?? 4000)));
|
||||
setStoragePath(setCached('vcon:storage-path', String(storageData.stats?.storageDirectory ?? '')));
|
||||
setCached('vcon:settings-loaded', true);
|
||||
})
|
||||
.catch(() => {
|
||||
error('Settings load failed', 'Using default runtime settings.');
|
||||
@@ -128,7 +130,7 @@ export function SettingsWorkspace() {
|
||||
});
|
||||
const data = await response.json();
|
||||
if (!response.ok) throw new Error(data.error || 'Settings update failed');
|
||||
setSettings(normalized);
|
||||
setSettings(setCached('vcon:settings', normalized));
|
||||
setSavedSettings(normalized);
|
||||
setJwtSecret('');
|
||||
success('Settings saved', 'Runtime settings updated.');
|
||||
@@ -145,19 +147,20 @@ export function SettingsWorkspace() {
|
||||
};
|
||||
|
||||
return (
|
||||
<section className="mx-auto w-full max-w-[var(--console-width)]">
|
||||
<section className="w-full">
|
||||
<AdminPageHeader title="Settings" />
|
||||
|
||||
<SettingsTabs items={TABS} value={activeTab} onChange={(tab) => setActiveTab(tab as TabId)} />
|
||||
<div className="max-w-[780px]">
|
||||
<SettingsTabs items={TABS} value={activeTab} onChange={(tab) => setActiveTab(tab as TabId)} />
|
||||
|
||||
<form onSubmit={saveSettings}>
|
||||
<div
|
||||
id={`settings-panel-${activeTab}`}
|
||||
role="tabpanel"
|
||||
aria-labelledby={`settings-tab-${activeTab}`}
|
||||
className="border border-t-0 border-[var(--border)] bg-[var(--surface)]"
|
||||
>
|
||||
<>
|
||||
<form onSubmit={saveSettings}>
|
||||
<div
|
||||
id={`settings-panel-${activeTab}`}
|
||||
role="tabpanel"
|
||||
aria-labelledby={`settings-tab-${activeTab}`}
|
||||
className="border border-t-0 border-[var(--border)] bg-[var(--surface)]"
|
||||
>
|
||||
<>
|
||||
{activeTab === 'general' && (
|
||||
<>
|
||||
<SettingsGroup title="Identity">
|
||||
@@ -231,18 +234,19 @@ export function SettingsWorkspace() {
|
||||
</SettingsField>
|
||||
</SettingsGroup>
|
||||
)}
|
||||
</>
|
||||
</div>
|
||||
|
||||
<footer className="flex flex-wrap items-center gap-2 border border-t-0 border-[var(--border)] bg-[var(--surface)] px-3 py-2">
|
||||
<div className="flex flex-1 items-center gap-1.5 text-[11px] text-[var(--text-muted)]" role="status">
|
||||
<span className={`h-1.5 w-1.5 ${isDirty ? 'bg-[var(--warning)]' : 'bg-[var(--accent)]'}`} />
|
||||
{loading ? 'Loading' : isDirty ? 'Unsaved' : 'Saved'}
|
||||
</>
|
||||
</div>
|
||||
<Button type="button" size="xs" disabled={!isDirty || saving} onClick={discardChanges}>Discard</Button>
|
||||
<Button type="submit" variant="primary" size="xs" icon="Save" loading={saving} disabled={loading || !isDirty}>Save</Button>
|
||||
</footer>
|
||||
</form>
|
||||
|
||||
<footer className="flex flex-wrap items-center gap-2 border border-t-0 border-[var(--border)] bg-[var(--surface)] px-3 py-2">
|
||||
<div className="flex flex-1 items-center gap-1.5 text-[11px] text-[var(--text-muted)]" role="status">
|
||||
<span className={`h-1.5 w-1.5 ${isDirty ? 'bg-[var(--warning)]' : 'bg-[var(--accent)]'}`} />
|
||||
{loading ? 'Loading' : isDirty ? 'Unsaved' : 'Saved'}
|
||||
</div>
|
||||
<Button type="button" size="xs" disabled={!isDirty || saving} onClick={discardChanges}>Discard</Button>
|
||||
<Button type="submit" variant="primary" size="xs" icon="Save" loading={saving} disabled={loading || !isDirty}>Save</Button>
|
||||
</footer>
|
||||
</form>
|
||||
</div>
|
||||
</section>
|
||||
);
|
||||
}
|
||||
@@ -4,4 +4,5 @@ export * from "./ClientsTable";
|
||||
export * from "./DataBrowser";
|
||||
export * from "./ExportWorkspace";
|
||||
export * from "./NewClientModal";
|
||||
export * from "./ProfileWorkspace";
|
||||
export * from "./SettingsWorkspace";
|
||||
@@ -15,7 +15,11 @@ export function SettingsTabs({
|
||||
onChange: (value: string) => void;
|
||||
}) {
|
||||
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) => (
|
||||
<button
|
||||
key={item.id}
|
||||
@@ -24,7 +28,11 @@ export function SettingsTabs({
|
||||
role="tab"
|
||||
aria-selected={value === 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)}
|
||||
>
|
||||
{item.label}
|
||||
@@ -59,7 +67,7 @@ export function SettingsField({
|
||||
children: React.ReactNode;
|
||||
}) {
|
||||
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="text-[11.5px] leading-snug text-[var(--text)]">{label}</div>
|
||||
</div>
|
||||
|
||||
@@ -46,9 +46,12 @@ export async function createAdminSessionToken(
|
||||
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(".");
|
||||
if (!payload || !signature || extra) return false;
|
||||
if (!payload || !signature || extra) return null;
|
||||
|
||||
try {
|
||||
const valid = await crypto.subtle.verify(
|
||||
@@ -57,21 +60,29 @@ export async function verifyAdminSessionToken(token: string, secret: string) {
|
||||
decodeBase64Url(signature),
|
||||
encoder.encode(payload),
|
||||
);
|
||||
if (!valid) return false;
|
||||
if (!valid) return null;
|
||||
|
||||
const session = JSON.parse(
|
||||
new TextDecoder().decode(decodeBase64Url(payload)),
|
||||
) as AdminSessionPayload;
|
||||
return (
|
||||
if (
|
||||
typeof session.email === "string" &&
|
||||
typeof session.expiresAt === "number" &&
|
||||
session.expiresAt > Date.now()
|
||||
);
|
||||
) {
|
||||
return session;
|
||||
}
|
||||
return null;
|
||||
} catch {
|
||||
return false;
|
||||
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) {
|
||||
const forwardedProto = request.headers
|
||||
.get("x-forwarded-proto")
|
||||
|
||||
@@ -468,3 +468,83 @@ export async function verifyAdminCredentials(email: string, password: string) {
|
||||
const actualHash = await derivePasswordHash(password, inMem.passwordSalt);
|
||||
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