fix(admin): key tunnels by user_id, server-side initial list load, full-scan user search

This commit is contained in:
Gerhard Scheikl
2026-05-31 11:46:14 +02:00
parent fb4880a1d9
commit b6c4d94990
19 changed files with 1676 additions and 840 deletions
+163
View File
@@ -0,0 +1,163 @@
'use client';
import { useCallback, useEffect, useRef, useState } from 'react';
import { formatDate } from '@/lib/format';
import type { AuditItem } from '@/lib/admin/list';
const PER_PAGE = 50;
export function AuditTable({
initialEntries,
initialTotal,
}: {
initialEntries: AuditItem[];
initialTotal: number;
}) {
const [entries, setEntries] = useState<AuditItem[]>(initialEntries);
const [total, setTotal] = useState(initialTotal);
const [page, setPage] = useState(1);
const [action, setAction] = useState('');
const [targetType, setTargetType] = useState('');
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const load = useCallback(async () => {
setLoading(true);
setError(null);
try {
const params = new URLSearchParams({
page: String(page),
perPage: String(PER_PAGE),
});
if (action.trim()) params.set('action', action.trim());
if (targetType.trim()) params.set('target_type', targetType.trim());
const res = await fetch(`/api/admin/audit?${params.toString()}`, {
credentials: 'same-origin',
});
if (!res.ok) {
const b = (await res.json().catch(() => ({}))) as { error?: string };
throw new Error(b.error ?? `Request failed (${res.status})`);
}
const data = (await res.json()) as {
entries: AuditItem[];
total: number;
};
setEntries(data.entries);
setTotal(data.total);
} catch (e) {
setError((e as Error).message);
} finally {
setLoading(false);
}
}, [page, action, targetType]);
// First page is server-rendered; skip the on-mount fetch to avoid racing the
// SSR session-cookie refresh (which intermittently 401'd).
const didMount = useRef(false);
useEffect(() => {
if (!didMount.current) {
didMount.current = true;
return;
}
const t = setTimeout(load, 250);
return () => clearTimeout(t);
}, [load]);
const totalPages = Math.max(1, Math.ceil(total / PER_PAGE));
return (
<div>
<h1>Audit log</h1>
<div className="row" style={{ marginBottom: '1rem', flexWrap: 'wrap' }}>
<input
type="text"
placeholder="Filter action (e.g. tunnel.delete)"
value={action}
onChange={(e) => {
setPage(1);
setAction(e.target.value);
}}
style={{ maxWidth: 240 }}
/>
<input
type="text"
placeholder="Filter target_type (user/tunnel…)"
value={targetType}
onChange={(e) => {
setPage(1);
setTargetType(e.target.value);
}}
style={{ maxWidth: 240 }}
/>
<button className="secondary btn-sm" type="button" onClick={load}>
Refresh
</button>
</div>
{error && <p className="error">{error}</p>}
{loading ? (
<p className="muted">Loading</p>
) : entries.length === 0 ? (
<p className="muted">No audit entries.</p>
) : (
<div className="admin-table-wrap">
<table className="admin-table">
<thead>
<tr>
<th>When</th>
<th>Actor</th>
<th>Action</th>
<th>Target</th>
<th>Details</th>
</tr>
</thead>
<tbody>
{entries.map((e) => (
<tr key={e.id}>
<td>{formatDate(e.created_at)}</td>
<td style={{ wordBreak: 'break-all' }}>
{e.actor_email ?? e.actor_id ?? '—'}
</td>
<td>{e.action}</td>
<td style={{ wordBreak: 'break-all' }}>
{e.target_type ? `${e.target_type}:` : ''}
{e.target_id ?? ''}
</td>
<td>
<code className="muted">
{JSON.stringify(e.details ?? {})}
</code>
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
<div className="row" style={{ marginTop: '1rem' }}>
<button
className="secondary btn-sm"
type="button"
disabled={page <= 1}
onClick={() => setPage((p) => Math.max(1, p - 1))}
>
Prev
</button>
<span className="muted">
Page {page} of {totalPages} ({total} total)
</span>
<button
className="secondary btn-sm"
type="button"
disabled={page >= totalPages}
onClick={() => setPage((p) => p + 1)}
>
Next
</button>
</div>
</div>
);
}
+13 -152
View File
@@ -1,158 +1,19 @@
'use client';
import { getAuditList } from '@/lib/admin/list';
import { AuditTable } from './audit-table';
import { useCallback, useEffect, useState } from 'react';
import { formatDate } from '@/lib/format';
type AuditEntry = {
id: number;
actor_id: string | null;
actor_email: string | null;
action: string;
target_type: string | null;
target_id: string | null;
details: Record<string, unknown>;
created_at: string;
};
export const dynamic = 'force-dynamic';
const PER_PAGE = 50;
export default function AdminAuditPage() {
const [entries, setEntries] = useState<AuditEntry[]>([]);
const [total, setTotal] = useState(0);
const [page, setPage] = useState(1);
const [action, setAction] = useState('');
const [targetType, setTargetType] = useState('');
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
export default async function AdminAuditPage() {
// Initial load on the server (admin session already validated by the layout)
// so the first paint never races the client session-cookie refresh.
const { entries, total } = await getAuditList({
page: 1,
perPage: PER_PAGE,
action: '',
targetType: '',
});
const load = useCallback(async () => {
setLoading(true);
setError(null);
try {
const params = new URLSearchParams({
page: String(page),
perPage: String(PER_PAGE),
});
if (action.trim()) params.set('action', action.trim());
if (targetType.trim()) params.set('target_type', targetType.trim());
const res = await fetch(`/api/admin/audit?${params.toString()}`);
if (!res.ok) {
const b = (await res.json().catch(() => ({}))) as { error?: string };
throw new Error(b.error ?? `Request failed (${res.status})`);
}
const data = (await res.json()) as {
entries: AuditEntry[];
total: number;
};
setEntries(data.entries);
setTotal(data.total);
} catch (e) {
setError((e as Error).message);
} finally {
setLoading(false);
}
}, [page, action, targetType]);
useEffect(() => {
const t = setTimeout(load, 250);
return () => clearTimeout(t);
}, [load]);
const totalPages = Math.max(1, Math.ceil(total / PER_PAGE));
return (
<div>
<h1>Audit log</h1>
<div className="row" style={{ marginBottom: '1rem', flexWrap: 'wrap' }}>
<input
type="text"
placeholder="Filter action (e.g. tunnel.delete)"
value={action}
onChange={(e) => {
setPage(1);
setAction(e.target.value);
}}
style={{ maxWidth: 240 }}
/>
<input
type="text"
placeholder="Filter target_type (user/tunnel…)"
value={targetType}
onChange={(e) => {
setPage(1);
setTargetType(e.target.value);
}}
style={{ maxWidth: 240 }}
/>
<button className="secondary btn-sm" type="button" onClick={load}>
Refresh
</button>
</div>
{error && <p className="error">{error}</p>}
{loading ? (
<p className="muted">Loading</p>
) : entries.length === 0 ? (
<p className="muted">No audit entries.</p>
) : (
<div className="admin-table-wrap">
<table className="admin-table">
<thead>
<tr>
<th>When</th>
<th>Actor</th>
<th>Action</th>
<th>Target</th>
<th>Details</th>
</tr>
</thead>
<tbody>
{entries.map((e) => (
<tr key={e.id}>
<td>{formatDate(e.created_at)}</td>
<td style={{ wordBreak: 'break-all' }}>
{e.actor_email ?? e.actor_id ?? '—'}
</td>
<td>{e.action}</td>
<td style={{ wordBreak: 'break-all' }}>
{e.target_type ? `${e.target_type}:` : ''}
{e.target_id ?? ''}
</td>
<td>
<code className="muted">
{JSON.stringify(e.details ?? {})}
</code>
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
<div className="row" style={{ marginTop: '1rem' }}>
<button
className="secondary btn-sm"
type="button"
disabled={page <= 1}
onClick={() => setPage((p) => Math.max(1, p - 1))}
>
Prev
</button>
<span className="muted">
Page {page} of {totalPages} ({total} total)
</span>
<button
className="secondary btn-sm"
type="button"
disabled={page >= totalPages}
onClick={() => setPage((p) => p + 1)}
>
Next
</button>
</div>
</div>
);
return <AuditTable initialEntries={entries} initialTotal={total} />;
}
+3 -3
View File
@@ -6,7 +6,7 @@ import { formatBytes, formatDate } from '@/lib/format';
export const dynamic = 'force-dynamic';
type OverQuotaRow = {
id: string;
user_id: string;
subdomain: string;
bytes_used: number;
quota_bytes: number;
@@ -26,7 +26,7 @@ export default async function AdminOverviewPage() {
// Over-quota tunnels (compute in memory).
const { data: tunnelsData } = await admin
.from('tunnels')
.select('id, subdomain, bytes_used, quota_bytes');
.select('user_id, subdomain, bytes_used, quota_bytes');
const overQuota = ((tunnelsData ?? []) as OverQuotaRow[])
.filter((t) => t.quota_bytes > 0 && t.bytes_used >= t.quota_bytes)
.slice(0, 5);
@@ -100,7 +100,7 @@ export default async function AdminOverviewPage() {
</thead>
<tbody>
{overQuota.map((t) => (
<tr key={t.id}>
<tr key={t.user_id}>
<td>{t.subdomain}</td>
<td>
{formatBytes(t.bytes_used)} / {formatBytes(t.quota_bytes)}
+12 -339
View File
@@ -1,346 +1,19 @@
'use client';
import { getTunnelsList } from '@/lib/admin/list';
import { TunnelsTable } from './tunnels-table';
import { useCallback, useEffect, useState } from 'react';
import { formatBytes, formatDate } from '@/lib/format';
type Tunnel = {
id: string;
user_id: string;
owner_email: string | null;
subdomain: string;
is_active: boolean;
bytes_used: number;
quota_bytes: number;
usage_pct: number;
last_seen_at: string | null;
created_at: string;
};
export const dynamic = 'force-dynamic';
const PER_PAGE = 25;
export default function AdminTunnelsPage() {
const [tunnels, setTunnels] = useState<Tunnel[]>([]);
const [total, setTotal] = useState(0);
const [page, setPage] = useState(1);
const [search, setSearch] = useState('');
const [status, setStatus] = useState('');
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [notice, setNotice] = useState<string | null>(null);
const [busyId, setBusyId] = useState<string | null>(null);
const load = useCallback(async () => {
setLoading(true);
setError(null);
try {
const params = new URLSearchParams({
page: String(page),
perPage: String(PER_PAGE),
});
if (search.trim()) params.set('search', search.trim());
if (status) params.set('status', status);
const res = await fetch(`/api/admin/tunnels?${params.toString()}`);
if (!res.ok) {
const b = (await res.json().catch(() => ({}))) as { error?: string };
throw new Error(b.error ?? `Request failed (${res.status})`);
}
const data = (await res.json()) as { tunnels: Tunnel[]; total: number };
setTunnels(data.tunnels);
setTotal(data.total);
} catch (e) {
setError((e as Error).message);
} finally {
setLoading(false);
}
}, [page, search, status]);
useEffect(() => {
const t = setTimeout(load, 250);
return () => clearTimeout(t);
}, [load]);
async function act(
id: string,
label: string,
url: string,
init: RequestInit,
confirmMsg?: string,
): Promise<unknown | null> {
if (confirmMsg && !window.confirm(confirmMsg)) return null;
setBusyId(id);
setError(null);
setNotice(null);
try {
const res = await fetch(url, init);
const body = (await res.json().catch(() => ({}))) as {
error?: string;
[k: string]: unknown;
};
if (!res.ok) throw new Error(body.error ?? `Request failed (${res.status})`);
setNotice(`${label} succeeded`);
await load();
return body;
} catch (e) {
setError((e as Error).message);
return null;
} finally {
setBusyId(null);
}
}
const jsonInit = (body: unknown): RequestInit => ({
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
export default async function AdminTunnelsPage() {
// Initial load on the server (admin session already validated by the layout)
// so the first paint never races the client session-cookie refresh.
const { tunnels, total } = await getTunnelsList({
page: 1,
perPage: PER_PAGE,
search: '',
status: null,
});
async function onToggleActive(t: Tunnel) {
await act(
t.id,
t.is_active ? 'Deactivate' : 'Activate',
`/api/admin/tunnels/${t.id}/active`,
jsonInit({ is_active: !t.is_active }),
);
}
async function onRegenerate(t: Tunnel) {
const body = (await act(
t.id,
'Regenerate token',
`/api/admin/tunnels/${t.id}/regenerate-token`,
{ method: 'POST' },
`Regenerate the token for ${t.subdomain}? The old token stops working.`,
)) as { token?: string } | null;
if (body?.token) {
window.prompt('New token (copy it now):', body.token);
}
}
async function onResetUsage(t: Tunnel) {
await act(
t.id,
'Reset usage',
`/api/admin/tunnels/${t.id}/reset-usage`,
{ method: 'POST' },
`Reset bandwidth usage for ${t.subdomain} to zero?`,
);
}
async function onSetQuota(t: Tunnel) {
const input = window.prompt(
`New quota in GiB for ${t.subdomain}:`,
String(Math.round(t.quota_bytes / 1024 ** 3)),
);
if (input === null) return;
const gib = Number(input);
if (!Number.isFinite(gib) || gib <= 0) {
setError('Quota must be a positive number of GiB');
return;
}
await act(
t.id,
'Set quota',
`/api/admin/tunnels/${t.id}/quota`,
jsonInit({ quota_bytes: Math.round(gib * 1024 ** 3) }),
);
}
async function onReassign(t: Tunnel) {
const input = window.prompt(
`New subdomain for ${t.owner_email ?? t.subdomain}:`,
t.subdomain,
);
if (input === null) return;
await act(
t.id,
'Reassign',
`/api/admin/tunnels/${t.id}/reassign`,
jsonInit({ subdomain: input.trim().toLowerCase() }),
);
}
async function onDelete(t: Tunnel) {
await act(
t.id,
'Delete tunnel',
`/api/admin/tunnels/${t.id}`,
{ method: 'DELETE' },
`Delete the tunnel ${t.subdomain}? This frees the subdomain.`,
);
}
const totalPages = Math.max(1, Math.ceil(total / PER_PAGE));
return (
<div>
<h1>Tunnels</h1>
<div className="row" style={{ marginBottom: '1rem', flexWrap: 'wrap' }}>
<input
type="text"
placeholder="Search subdomain…"
value={search}
onChange={(e) => {
setPage(1);
setSearch(e.target.value);
}}
style={{ maxWidth: 260 }}
/>
<select
value={status}
onChange={(e) => {
setPage(1);
setStatus(e.target.value);
}}
style={{
padding: '0.6rem 0.75rem',
background: 'var(--bg)',
color: 'var(--fg)',
border: '1px solid var(--border)',
borderRadius: 6,
}}
>
<option value="">All statuses</option>
<option value="active">Active</option>
<option value="inactive">Inactive</option>
<option value="over_quota">Over quota</option>
</select>
<button className="secondary btn-sm" type="button" onClick={load}>
Refresh
</button>
</div>
{error && <p className="error">{error}</p>}
{notice && <p className="success">{notice}</p>}
{loading ? (
<p className="muted">Loading</p>
) : tunnels.length === 0 ? (
<p className="muted">No tunnels found.</p>
) : (
<div className="admin-table-wrap">
<table className="admin-table">
<thead>
<tr>
<th>Subdomain</th>
<th>Owner</th>
<th>Status</th>
<th>Usage</th>
<th>Last seen</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
{tunnels.map((t) => (
<tr key={t.id}>
<td>{t.subdomain}</td>
<td style={{ wordBreak: 'break-all' }}>
{t.owner_email ?? '—'}
</td>
<td>
{t.is_active ? (
<span className="badge badge-ok">active</span>
) : (
<span className="badge">inactive</span>
)}
</td>
<td style={{ minWidth: 140 }}>
<div>
{formatBytes(t.bytes_used)} / {formatBytes(t.quota_bytes)}
</div>
<div className="progress" style={{ marginTop: 4 }}>
<div
style={{
width: `${Math.min(100, t.usage_pct).toFixed(1)}%`,
background:
t.usage_pct >= 100
? 'var(--danger)'
: 'var(--accent)',
}}
/>
</div>
</td>
<td>{formatDate(t.last_seen_at)}</td>
<td>
<div className="row" style={{ flexWrap: 'wrap', gap: 4 }}>
<button
type="button"
className="secondary btn-sm"
disabled={busyId === t.id}
onClick={() => onToggleActive(t)}
>
{t.is_active ? 'Deactivate' : 'Activate'}
</button>
<button
type="button"
className="secondary btn-sm"
disabled={busyId === t.id}
onClick={() => onSetQuota(t)}
>
Quota
</button>
<button
type="button"
className="secondary btn-sm"
disabled={busyId === t.id}
onClick={() => onResetUsage(t)}
>
Reset
</button>
<button
type="button"
className="secondary btn-sm"
disabled={busyId === t.id}
onClick={() => onReassign(t)}
>
Reassign
</button>
<button
type="button"
className="secondary btn-sm"
disabled={busyId === t.id}
onClick={() => onRegenerate(t)}
>
Token
</button>
<button
type="button"
className="btn-danger btn-sm"
disabled={busyId === t.id}
onClick={() => onDelete(t)}
>
Delete
</button>
</div>
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
<div className="row" style={{ marginTop: '1rem' }}>
<button
className="secondary btn-sm"
type="button"
disabled={page <= 1}
onClick={() => setPage((p) => Math.max(1, p - 1))}
>
Prev
</button>
<span className="muted">
Page {page} of {totalPages} ({total} total)
</span>
<button
className="secondary btn-sm"
type="button"
disabled={page >= totalPages}
onClick={() => setPage((p) => p + 1)}
>
Next
</button>
</div>
</div>
);
return <TunnelsTable initialTunnels={tunnels} initialTotal={total} />;
}
+349
View File
@@ -0,0 +1,349 @@
'use client';
import { useCallback, useEffect, useRef, useState } from 'react';
import { formatBytes, formatDate } from '@/lib/format';
import type { TunnelItem } from '@/lib/admin/list';
const PER_PAGE = 25;
export function TunnelsTable({
initialTunnels,
initialTotal,
}: {
initialTunnels: TunnelItem[];
initialTotal: number;
}) {
const [tunnels, setTunnels] = useState<TunnelItem[]>(initialTunnels);
const [total, setTotal] = useState(initialTotal);
const [page, setPage] = useState(1);
const [search, setSearch] = useState('');
const [status, setStatus] = useState('');
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const [notice, setNotice] = useState<string | null>(null);
const [busyId, setBusyId] = useState<string | null>(null);
const load = useCallback(async () => {
setLoading(true);
setError(null);
try {
const params = new URLSearchParams({
page: String(page),
perPage: String(PER_PAGE),
});
if (search.trim()) params.set('search', search.trim());
if (status) params.set('status', status);
const res = await fetch(`/api/admin/tunnels?${params.toString()}`, {
credentials: 'same-origin',
});
if (!res.ok) {
const b = (await res.json().catch(() => ({}))) as { error?: string };
throw new Error(b.error ?? `Request failed (${res.status})`);
}
const data = (await res.json()) as { tunnels: TunnelItem[]; total: number };
setTunnels(data.tunnels);
setTotal(data.total);
} catch (e) {
setError((e as Error).message);
} finally {
setLoading(false);
}
}, [page, search, status]);
// First page is server-rendered; skip the on-mount fetch to avoid racing the
// SSR session-cookie refresh (which intermittently 401'd).
const didMount = useRef(false);
useEffect(() => {
if (!didMount.current) {
didMount.current = true;
return;
}
const t = setTimeout(load, 250);
return () => clearTimeout(t);
}, [load]);
async function act(
id: string,
label: string,
url: string,
init: RequestInit,
confirmMsg?: string,
): Promise<unknown | null> {
if (confirmMsg && !window.confirm(confirmMsg)) return null;
setBusyId(id);
setError(null);
setNotice(null);
try {
const res = await fetch(url, { credentials: 'same-origin', ...init });
const body = (await res.json().catch(() => ({}))) as {
error?: string;
[k: string]: unknown;
};
if (!res.ok) throw new Error(body.error ?? `Request failed (${res.status})`);
setNotice(`${label} succeeded`);
await load();
return body;
} catch (e) {
setError((e as Error).message);
return null;
} finally {
setBusyId(null);
}
}
const jsonInit = (body: unknown): RequestInit => ({
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
});
async function onToggleActive(t: TunnelItem) {
await act(
t.user_id,
t.is_active ? 'Deactivate' : 'Activate',
`/api/admin/tunnels/${t.user_id}/active`,
jsonInit({ is_active: !t.is_active }),
);
}
async function onRegenerate(t: TunnelItem) {
const body = (await act(
t.user_id,
'Regenerate token',
`/api/admin/tunnels/${t.user_id}/regenerate-token`,
{ method: 'POST' },
`Regenerate the token for ${t.subdomain}? The old token stops working.`,
)) as { token?: string } | null;
if (body?.token) {
window.prompt('New token (copy it now):', body.token);
}
}
async function onResetUsage(t: TunnelItem) {
await act(
t.user_id,
'Reset usage',
`/api/admin/tunnels/${t.user_id}/reset-usage`,
{ method: 'POST' },
`Reset bandwidth usage for ${t.subdomain} to zero?`,
);
}
async function onSetQuota(t: TunnelItem) {
const input = window.prompt(
`New quota in GiB for ${t.subdomain}:`,
String(Math.round(t.quota_bytes / 1024 ** 3)),
);
if (input === null) return;
const gib = Number(input);
if (!Number.isFinite(gib) || gib <= 0) {
setError('Quota must be a positive number of GiB');
return;
}
await act(
t.user_id,
'Set quota',
`/api/admin/tunnels/${t.user_id}/quota`,
jsonInit({ quota_bytes: Math.round(gib * 1024 ** 3) }),
);
}
async function onReassign(t: TunnelItem) {
const input = window.prompt(
`New subdomain for ${t.owner_email ?? t.subdomain}:`,
t.subdomain,
);
if (input === null) return;
await act(
t.user_id,
'Reassign',
`/api/admin/tunnels/${t.user_id}/reassign`,
jsonInit({ subdomain: input.trim().toLowerCase() }),
);
}
async function onDelete(t: TunnelItem) {
await act(
t.user_id,
'Delete tunnel',
`/api/admin/tunnels/${t.user_id}`,
{ method: 'DELETE' },
`Delete the tunnel ${t.subdomain}? This frees the subdomain.`,
);
}
const totalPages = Math.max(1, Math.ceil(total / PER_PAGE));
return (
<div>
<h1>Tunnels</h1>
<div className="row" style={{ marginBottom: '1rem', flexWrap: 'wrap' }}>
<input
type="text"
placeholder="Search subdomain…"
value={search}
onChange={(e) => {
setPage(1);
setSearch(e.target.value);
}}
style={{ maxWidth: 260 }}
/>
<select
value={status}
onChange={(e) => {
setPage(1);
setStatus(e.target.value);
}}
style={{
padding: '0.6rem 0.75rem',
background: 'var(--bg)',
color: 'var(--fg)',
border: '1px solid var(--border)',
borderRadius: 6,
}}
>
<option value="">All statuses</option>
<option value="active">Active</option>
<option value="inactive">Inactive</option>
<option value="over_quota">Over quota</option>
</select>
<button className="secondary btn-sm" type="button" onClick={load}>
Refresh
</button>
</div>
{error && <p className="error">{error}</p>}
{notice && <p className="success">{notice}</p>}
{loading ? (
<p className="muted">Loading</p>
) : tunnels.length === 0 ? (
<p className="muted">No tunnels found.</p>
) : (
<div className="admin-table-wrap">
<table className="admin-table">
<thead>
<tr>
<th>Subdomain</th>
<th>Owner</th>
<th>Status</th>
<th>Usage</th>
<th>Last seen</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
{tunnels.map((t) => (
<tr key={t.user_id}>
<td>{t.subdomain}</td>
<td style={{ wordBreak: 'break-all' }}>
{t.owner_email ?? '—'}
</td>
<td>
{t.is_active ? (
<span className="badge badge-ok">active</span>
) : (
<span className="badge">inactive</span>
)}
</td>
<td style={{ minWidth: 140 }}>
<div>
{formatBytes(t.bytes_used)} / {formatBytes(t.quota_bytes)}
</div>
<div className="progress" style={{ marginTop: 4 }}>
<div
style={{
width: `${Math.min(100, t.usage_pct).toFixed(1)}%`,
background:
t.usage_pct >= 100
? 'var(--danger)'
: 'var(--accent)',
}}
/>
</div>
</td>
<td>{formatDate(t.last_seen_at)}</td>
<td>
<div className="row" style={{ flexWrap: 'wrap', gap: 4 }}>
<button
type="button"
className="secondary btn-sm"
disabled={busyId === t.user_id}
onClick={() => onToggleActive(t)}
>
{t.is_active ? 'Deactivate' : 'Activate'}
</button>
<button
type="button"
className="secondary btn-sm"
disabled={busyId === t.user_id}
onClick={() => onSetQuota(t)}
>
Quota
</button>
<button
type="button"
className="secondary btn-sm"
disabled={busyId === t.user_id}
onClick={() => onResetUsage(t)}
>
Reset
</button>
<button
type="button"
className="secondary btn-sm"
disabled={busyId === t.user_id}
onClick={() => onReassign(t)}
>
Reassign
</button>
<button
type="button"
className="secondary btn-sm"
disabled={busyId === t.user_id}
onClick={() => onRegenerate(t)}
>
Token
</button>
<button
type="button"
className="btn-danger btn-sm"
disabled={busyId === t.user_id}
onClick={() => onDelete(t)}
>
Delete
</button>
</div>
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
<div className="row" style={{ marginTop: '1rem' }}>
<button
className="secondary btn-sm"
type="button"
disabled={page <= 1}
onClick={() => setPage((p) => Math.max(1, p - 1))}
>
Prev
</button>
<span className="muted">
Page {page} of {totalPages} ({total} total)
</span>
<button
className="secondary btn-sm"
type="button"
disabled={page >= totalPages}
onClick={() => setPage((p) => p + 1)}
>
Next
</button>
</div>
</div>
);
}
+1 -2
View File
@@ -9,7 +9,6 @@ import { UserActions } from './user-actions';
export const dynamic = 'force-dynamic';
type TunnelRow = {
id: string;
subdomain: string;
is_active: boolean;
bytes_used: number;
@@ -54,7 +53,7 @@ export default async function AdminUserDetailPage({
const { data: tunnel } = await admin
.from('tunnels')
.select(
'id, subdomain, is_active, bytes_used, quota_bytes, last_seen_at, created_at',
'subdomain, is_active, bytes_used, quota_bytes, last_seen_at, created_at',
)
.eq('user_id', params.id)
.maybeSingle<TunnelRow>();
+14 -165
View File
@@ -1,170 +1,19 @@
'use client';
import { getUsersList } from '@/lib/admin/list';
import { UsersTable } from './users-table';
import { useCallback, useEffect, useState } from 'react';
import Link from 'next/link';
import { formatBytes, formatDate } from '@/lib/format';
type AdminUser = {
id: string;
email: string | null;
role: string;
banned_until: string | null;
email_confirmed_at: string | null;
created_at: string;
last_sign_in_at: string | null;
tunnel: {
subdomain: string;
is_active: boolean;
bytes_used: number;
quota_bytes: number;
} | null;
};
export const dynamic = 'force-dynamic';
const PER_PAGE = 25;
function isBanned(u: AdminUser): boolean {
return !!u.banned_until && new Date(u.banned_until).getTime() > Date.now();
}
export default function AdminUsersPage() {
const [users, setUsers] = useState<AdminUser[]>([]);
const [total, setTotal] = useState(0);
const [page, setPage] = useState(1);
const [search, setSearch] = useState('');
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const load = useCallback(async () => {
setLoading(true);
setError(null);
try {
const params = new URLSearchParams({
page: String(page),
perPage: String(PER_PAGE),
});
if (search.trim()) params.set('search', search.trim());
const res = await fetch(`/api/admin/users?${params.toString()}`);
if (!res.ok) {
const b = (await res.json().catch(() => ({}))) as { error?: string };
throw new Error(b.error ?? `Request failed (${res.status})`);
}
const data = (await res.json()) as { users: AdminUser[]; total: number };
setUsers(data.users);
setTotal(data.total);
} catch (e) {
setError((e as Error).message);
} finally {
setLoading(false);
}
}, [page, search]);
useEffect(() => {
const t = setTimeout(load, 250);
return () => clearTimeout(t);
}, [load]);
const totalPages = Math.max(1, Math.ceil(total / PER_PAGE));
return (
<div>
<h1>Users</h1>
<div className="row" style={{ marginBottom: '1rem' }}>
<input
type="text"
placeholder="Search by email…"
value={search}
onChange={(e) => {
setPage(1);
setSearch(e.target.value);
}}
style={{ maxWidth: 320 }}
/>
<button className="secondary btn-sm" onClick={load} type="button">
Refresh
</button>
</div>
{error && <p className="error">{error}</p>}
{loading ? (
<p className="muted">Loading</p>
) : users.length === 0 ? (
<p className="muted">No users found.</p>
) : (
<div className="admin-table-wrap">
<table className="admin-table">
<thead>
<tr>
<th>Email</th>
<th>Role</th>
<th>Status</th>
<th>Tunnel</th>
<th>Usage</th>
<th>Created</th>
</tr>
</thead>
<tbody>
{users.map((u) => (
<tr key={u.id}>
<td>
<Link href={`/admin/users/${u.id}`}>
{u.email ?? u.id}
</Link>
</td>
<td>
{u.role === 'admin' ? (
<span className="badge badge-admin">admin</span>
) : (
<span className="badge">user</span>
)}
</td>
<td>
{isBanned(u) ? (
<span className="badge badge-banned">banned</span>
) : u.email_confirmed_at ? (
<span className="badge badge-ok">confirmed</span>
) : (
<span className="badge">unconfirmed</span>
)}
</td>
<td>{u.tunnel ? u.tunnel.subdomain : '—'}</td>
<td>
{u.tunnel
? `${formatBytes(u.tunnel.bytes_used)} / ${formatBytes(
u.tunnel.quota_bytes,
)}`
: '—'}
</td>
<td>{formatDate(u.created_at)}</td>
</tr>
))}
</tbody>
</table>
</div>
)}
<div className="row" style={{ marginTop: '1rem' }}>
<button
className="secondary btn-sm"
type="button"
disabled={page <= 1}
onClick={() => setPage((p) => Math.max(1, p - 1))}
>
Prev
</button>
<span className="muted">
Page {page} of {totalPages} ({total} total)
</span>
<button
className="secondary btn-sm"
type="button"
disabled={page >= totalPages}
onClick={() => setPage((p) => p + 1)}
>
Next
</button>
</div>
</div>
);
export default async function AdminUsersPage() {
// Initial load runs on the server (the admin session is already validated by
// the admin layout's requireAdmin()), so the first paint never races the
// client session-cookie refresh.
const { users, total } = await getUsersList({
page: 1,
perPage: PER_PAGE,
search: '',
});
return <UsersTable initialUsers={users} initialTotal={total} />;
}
+174
View File
@@ -0,0 +1,174 @@
'use client';
import { useCallback, useEffect, useRef, useState } from 'react';
import Link from 'next/link';
import { formatBytes, formatDate } from '@/lib/format';
import type { AdminUserItem } from '@/lib/admin/list';
const PER_PAGE = 25;
function isBanned(u: AdminUserItem): boolean {
return !!u.banned_until && new Date(u.banned_until).getTime() > Date.now();
}
export function UsersTable({
initialUsers,
initialTotal,
}: {
initialUsers: AdminUserItem[];
initialTotal: number;
}) {
const [users, setUsers] = useState<AdminUserItem[]>(initialUsers);
const [total, setTotal] = useState(initialTotal);
const [page, setPage] = useState(1);
const [search, setSearch] = useState('');
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const load = useCallback(async () => {
setLoading(true);
setError(null);
try {
const params = new URLSearchParams({
page: String(page),
perPage: String(PER_PAGE),
});
if (search.trim()) params.set('search', search.trim());
const res = await fetch(`/api/admin/users?${params.toString()}`, {
credentials: 'same-origin',
});
if (!res.ok) {
const b = (await res.json().catch(() => ({}))) as { error?: string };
throw new Error(b.error ?? `Request failed (${res.status})`);
}
const data = (await res.json()) as {
users: AdminUserItem[];
total: number;
};
setUsers(data.users);
setTotal(data.total);
} catch (e) {
setError((e as Error).message);
} finally {
setLoading(false);
}
}, [page, search]);
// The first page is rendered from server-supplied data (see the parent server
// component), so skip the initial on-mount fetch — that on-mount request used
// to race the SSR session-cookie refresh and intermittently 401.
const didMount = useRef(false);
useEffect(() => {
if (!didMount.current) {
didMount.current = true;
return;
}
const t = setTimeout(load, 250);
return () => clearTimeout(t);
}, [load]);
const totalPages = Math.max(1, Math.ceil(total / PER_PAGE));
return (
<div>
<h1>Users</h1>
<div className="row" style={{ marginBottom: '1rem' }}>
<input
type="text"
placeholder="Search by email…"
value={search}
onChange={(e) => {
setPage(1);
setSearch(e.target.value);
}}
style={{ maxWidth: 320 }}
/>
<button className="secondary btn-sm" onClick={load} type="button">
Refresh
</button>
</div>
{error && <p className="error">{error}</p>}
{loading ? (
<p className="muted">Loading</p>
) : users.length === 0 ? (
<p className="muted">No users found.</p>
) : (
<div className="admin-table-wrap">
<table className="admin-table">
<thead>
<tr>
<th>Email</th>
<th>Role</th>
<th>Status</th>
<th>Tunnel</th>
<th>Usage</th>
<th>Created</th>
</tr>
</thead>
<tbody>
{users.map((u) => (
<tr key={u.id}>
<td>
<Link href={`/admin/users/${u.id}`}>
{u.email ?? u.id}
</Link>
</td>
<td>
{u.role === 'admin' ? (
<span className="badge badge-admin">admin</span>
) : (
<span className="badge">user</span>
)}
</td>
<td>
{isBanned(u) ? (
<span className="badge badge-banned">banned</span>
) : u.email_confirmed_at ? (
<span className="badge badge-ok">confirmed</span>
) : (
<span className="badge">unconfirmed</span>
)}
</td>
<td>{u.tunnel ? u.tunnel.subdomain : '—'}</td>
<td>
{u.tunnel
? `${formatBytes(u.tunnel.bytes_used)} / ${formatBytes(
u.tunnel.quota_bytes,
)}`
: '—'}
</td>
<td>{formatDate(u.created_at)}</td>
</tr>
))}
</tbody>
</table>
</div>
)}
<div className="row" style={{ marginTop: '1rem' }}>
<button
className="secondary btn-sm"
type="button"
disabled={page <= 1}
onClick={() => setPage((p) => Math.max(1, p - 1))}
>
Prev
</button>
<span className="muted">
Page {page} of {totalPages} ({total} total)
</span>
<button
className="secondary btn-sm"
type="button"
disabled={page >= totalPages}
onClick={() => setPage((p) => p + 1)}
>
Next
</button>
</div>
</div>
);
}