Files
ulweb/web/pages/settings/api-keys.tsx
ulhub eae4075265 Build core domain: orgs, users, jobs, locate points, auth, live map
Replaces the device-events demo with the actual product:

- Prisma + PostGIS data layer (postgis/postgis:17-3.5). Lat/lng decimals
  are the source of truth; a generated geometry(Point,4326) column with
  a GIST index backs bbox queries. Migrations apply on container boot.
- JWT auth (bcryptjs + httpOnly cookie) with public registration that
  creates an org; per-org roles (ORG_ADMIN/MEMBER/VIEWER) enforced by
  guards on all /orgs/:orgId routes.
- Scoped API keys (X-API-Key, sha256-hashed, shown once) for
  programmatic access, manageable by org admins.
- REST API: jobs/tickets CRUD with filters, points query (time range,
  recordedAt cursor, bbox), members, devices, api-keys.
- MQTT ingest: devices publish to devices/{username}/points and /jobs;
  unknown tickets auto-create stub jobs (source=DEVICE); every message
  is raw-logged to device_events; acks on devices/{username}/jobs/ack.
  Broker gets a dedicated backend user; testuser is now a plain device.
- Realtime: plain-WS gateway at /api/ws (socket.io removed) with
  cookie auth and per-job channels feeding the map live.
- Next.js frontend: login/register, jobs list with filters, job detail
  with live Google map (APWA utility colors, polylines per run) behind
  a provider-neutral JobMap abstraction for a future Esri swap, and
  settings pages for members/devices/api-keys.
- Seed: Umagul org, admin user, testuser device, demo job with RTK
  points. Sample publisher updated to the new topic contract.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
2026-07-14 12:43:25 +00:00

150 lines
4.9 KiB
TypeScript

import { FormEvent, useCallback, useEffect, useState } from 'react';
import Layout from '../../components/Layout';
import { api } from '../../lib/api';
import { useRequireAuth } from '../../lib/auth-context';
interface ApiKeyRow {
id: string;
name: string;
keyPrefix: string;
scopes: string[];
expiresAt: string | null;
lastUsedAt: string | null;
revokedAt: string | null;
createdAt: string;
}
const ALL_SCOPES = ['jobs:read', 'jobs:write', 'points:read', 'points:write', 'devices:read'];
export default function ApiKeysPage() {
const { user, activeOrg, loading } = useRequireAuth();
const orgId = activeOrg?.org.id ?? null;
const isAdmin = activeOrg?.role === 'ORG_ADMIN';
const [keys, setKeys] = useState<ApiKeyRow[]>([]);
const [name, setName] = useState('');
const [scopes, setScopes] = useState<string[]>(['jobs:read', 'points:read']);
const [createdKey, setCreatedKey] = useState<string | null>(null);
const [error, setError] = useState<string | null>(null);
const reload = useCallback(() => {
if (!orgId || !isAdmin) {
return;
}
api
.get<ApiKeyRow[]>(`/api/orgs/${orgId}/api-keys`)
.then((rows) => {
setKeys(rows);
setError(null);
})
.catch((err) => setError(err.message));
}, [orgId, isAdmin]);
useEffect(reload, [reload]);
const toggleScope = (scope: string) =>
setScopes((s) => (s.includes(scope) ? s.filter((x) => x !== scope) : [...s, scope]));
const createKey = async (e: FormEvent) => {
e.preventDefault();
try {
const created = await api.post<ApiKeyRow & { key: string }>(`/api/orgs/${orgId}/api-keys`, { name, scopes });
setCreatedKey(created.key);
setName('');
reload();
} catch (err: any) {
setError(err.message);
}
};
const revoke = async (keyId: string) => {
try {
await api.delete(`/api/orgs/${orgId}/api-keys/${keyId}`);
reload();
} catch (err: any) {
setError(err.message);
}
};
if (loading || !user) {
return null;
}
if (!isAdmin) {
return (
<Layout title="API Keys">
<h1>API Keys</h1>
<p>Only organization admins can manage API keys.</p>
</Layout>
);
}
return (
<Layout title="API Keys">
<h1>API Keys</h1>
<p style={{ color: '#666' }}>
Send keys in the <code>X-API-Key</code> header. Access is limited to this organization and the selected scopes.
</p>
{error && <p style={{ color: '#c62828' }}>{error}</p>}
{createdKey && (
<div style={{ background: '#e8f5e9', border: '1px solid #388e3c', borderRadius: 6, padding: '1rem', margin: '1rem 0' }}>
<strong>Copy this key now it will not be shown again:</strong>
<div style={{ display: 'flex', gap: '0.5rem', alignItems: 'center', marginTop: '0.5rem' }}>
<code style={{ wordBreak: 'break-all' }}>{createdKey}</code>
<button onClick={() => navigator.clipboard.writeText(createdKey)}>Copy</button>
<button onClick={() => setCreatedKey(null)}>Dismiss</button>
</div>
</div>
)}
<form onSubmit={createKey} style={{ display: 'flex', gap: '0.75rem', alignItems: 'center', flexWrap: 'wrap', marginBottom: '1.5rem' }}>
<input
placeholder="key name (e.g. GIS export)"
value={name}
onChange={(e) => setName(e.target.value)}
required
style={{ padding: '0.4rem', width: 220 }}
/>
{ALL_SCOPES.map((scope) => (
<label key={scope} style={{ whiteSpace: 'nowrap' }}>
<input type="checkbox" checked={scopes.includes(scope)} onChange={() => toggleScope(scope)} /> {scope}
</label>
))}
<button type="submit" disabled={scopes.length === 0}>
Create key
</button>
</form>
<table style={{ width: '100%', borderCollapse: 'collapse' }}>
<thead>
<tr style={{ textAlign: 'left', borderBottom: '2px solid #ddd' }}>
<th style={{ padding: '0.5rem' }}>Name</th>
<th>Prefix</th>
<th>Scopes</th>
<th>Last used</th>
<th>Status</th>
<th />
</tr>
</thead>
<tbody>
{keys.map((k) => (
<tr key={k.id} style={{ borderBottom: '1px solid #eee' }}>
<td style={{ padding: '0.5rem' }}>{k.name}</td>
<td>
<code>{k.keyPrefix}</code>
</td>
<td>{k.scopes.join(', ')}</td>
<td>{k.lastUsedAt ? new Date(k.lastUsedAt).toLocaleString() : 'never'}</td>
<td style={{ color: k.revokedAt ? '#c62828' : '#388e3c' }}>{k.revokedAt ? 'revoked' : 'active'}</td>
<td style={{ textAlign: 'right' }}>
{!k.revokedAt && <button onClick={() => revoke(k.id)}>Revoke</button>}
</td>
</tr>
))}
</tbody>
</table>
</Layout>
);
}