diff --git a/app/api/auth/profile/route.ts b/app/api/auth/profile/route.ts new file mode 100644 index 0000000..ef36524 --- /dev/null +++ b/app/api/auth/profile/route.ts @@ -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 }, + ); + } +} diff --git a/app/vcon/clients/page.tsx b/app/vcon/clients/page.tsx index 6f680bf..9413dca 100644 --- a/app/vcon/clients/page.tsx +++ b/app/vcon/clients/page.tsx @@ -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([]); + const [clients, setClients] = useState(() => getCached('vcon:clients', [])); const [search, setSearch] = useState(''); const [statusFilter, setStatusFilter] = useState('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]); diff --git a/app/vcon/profile/page.tsx b/app/vcon/profile/page.tsx new file mode 100644 index 0000000..38eccf5 --- /dev/null +++ b/app/vcon/profile/page.tsx @@ -0,0 +1,5 @@ +import { ProfileWorkspace } from '@/components/sections/ProfileWorkspace'; + +export default function ProfilePage() { + return ; +} diff --git a/app/vcon/sdk/page.tsx b/app/vcon/sdk/page.tsx index a10cc06..3bfde04 100644 --- a/app/vcon/sdk/page.tsx +++ b/app/vcon/sdk/page.tsx @@ -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([]); - const [selectedClientId, setSelectedClientId] = useState(''); + const [clients, setClients] = useState(() => getCached('vcon:clients', [])); + const [selectedClientId, setSelectedClientId] = useState(() => { + const cached = getCached('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 ( -
+
- - pip install ./sdk-python -
); } diff --git a/app/vcon/simulator/page.tsx b/app/vcon/simulator/page.tsx index c66146d..9924de9 100644 --- a/app/vcon/simulator/page.tsx +++ b/app/vcon/simulator/page.tsx @@ -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([]); - const [selectedClient, setSelectedClient] = useState(''); + const [clients, setClients] = useState(() => getCached('vcon:clients', [])); + const [selectedClient, setSelectedClient] = useState(() => { + const cached = getCached('vcon:clients', []); + return cached[0]?.clientId ?? ''; + }); const [payloadText, setPayloadText] = useState( 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() { } /> -
+
setEmail(event.target.value)} + required + /> + + + + + + + + + setCurrentPassword(event.target.value)} + required + /> + + + setNewPassword(event.target.value)} + /> + + + setConfirmPassword(event.target.value)} + /> + + + +
+ + {loading ? 'Loading profile...' : 'Confirm current password to update credentials'} + +
+ + +
+
+ +
+ ); +} diff --git a/components/sections/SettingsWorkspace.tsx b/components/sections/SettingsWorkspace.tsx index 548fc92..cc1b1c0 100644 --- a/components/sections/SettingsWorkspace.tsx +++ b/components/sections/SettingsWorkspace.tsx @@ -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(DEFAULT_SETTINGS); - const [savedSettings, setSavedSettings] = useState(DEFAULT_SETTINGS); + const [settings, setSettings] = useState(() => getCached('vcon:settings', DEFAULT_SETTINGS)); + const [savedSettings, setSavedSettings] = useState(() => getCached('vcon:settings', DEFAULT_SETTINGS)); const [activeTab, setActiveTab] = useState('general'); const [jwtSecret, setJwtSecret] = useState(''); - const [storagePath, setStoragePath] = useState(''); + const [storagePath, setStoragePath] = useState(() => getCached('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('vcon:server-port', 4000)); + const [loading, setLoading] = useState(() => !getCached('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 ( -
+
- setActiveTab(tab as TabId)} /> +
+ setActiveTab(tab as TabId)} /> -
-
- <> + +
+ <> {activeTab === 'general' && ( <> @@ -231,18 +234,19 @@ export function SettingsWorkspace() { )} - -
- -
-
- - {loading ? 'Loading' : isDirty ? 'Unsaved' : 'Saved'} +
- - -
- + +
+
+ + {loading ? 'Loading' : isDirty ? 'Unsaved' : 'Saved'} +
+ + +
+ +
); } diff --git a/components/sections/index.ts b/components/sections/index.ts index 86d8450..6da27dc 100644 --- a/components/sections/index.ts +++ b/components/sections/index.ts @@ -4,4 +4,5 @@ export * from "./ClientsTable"; export * from "./DataBrowser"; export * from "./ExportWorkspace"; export * from "./NewClientModal"; +export * from "./ProfileWorkspace"; export * from "./SettingsWorkspace"; diff --git a/components/ui/SettingsLayout.tsx b/components/ui/SettingsLayout.tsx index ae750df..95f53f8 100644 --- a/components/ui/SettingsLayout.tsx +++ b/components/ui/SettingsLayout.tsx @@ -15,7 +15,11 @@ export function SettingsTabs({ onChange: (value: string) => void; }) { return ( -
+
{items.map((item) => (