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>
This commit is contained in:
149
web/pages/settings/api-keys.tsx
Normal file
149
web/pages/settings/api-keys.tsx
Normal file
@@ -0,0 +1,149 @@
|
||||
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>
|
||||
);
|
||||
}
|
||||
150
web/pages/settings/devices.tsx
Normal file
150
web/pages/settings/devices.tsx
Normal file
@@ -0,0 +1,150 @@
|
||||
import { FormEvent, useCallback, useEffect, useState } from 'react';
|
||||
import Layout from '../../components/Layout';
|
||||
import { api } from '../../lib/api';
|
||||
import { useRequireAuth } from '../../lib/auth-context';
|
||||
|
||||
interface DeviceRow {
|
||||
id: string;
|
||||
name: string;
|
||||
serialNumber: string | null;
|
||||
mqttUsername: string;
|
||||
isActive: boolean;
|
||||
lastSeenAt: string | null;
|
||||
}
|
||||
|
||||
export default function DevicesPage() {
|
||||
const { user, activeOrg, loading } = useRequireAuth();
|
||||
const orgId = activeOrg?.org.id ?? null;
|
||||
const isAdmin = activeOrg?.role === 'ORG_ADMIN';
|
||||
|
||||
const [devices, setDevices] = useState<DeviceRow[]>([]);
|
||||
const [form, setForm] = useState({ name: '', mqttUsername: '', serialNumber: '' });
|
||||
const [notice, setNotice] = useState<string | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const reload = useCallback(() => {
|
||||
if (!orgId) {
|
||||
return;
|
||||
}
|
||||
api
|
||||
.get<DeviceRow[]>(`/api/orgs/${orgId}/devices`)
|
||||
.then((rows) => {
|
||||
setDevices(rows);
|
||||
setError(null);
|
||||
})
|
||||
.catch((err) => setError(err.message));
|
||||
}, [orgId]);
|
||||
|
||||
useEffect(reload, [reload]);
|
||||
|
||||
const addDevice = async (e: FormEvent) => {
|
||||
e.preventDefault();
|
||||
try {
|
||||
const created = await api.post<DeviceRow & { provisioning: { pointsTopic: string } }>(
|
||||
`/api/orgs/${orgId}/devices`,
|
||||
{
|
||||
name: form.name,
|
||||
mqttUsername: form.mqttUsername,
|
||||
serialNumber: form.serialNumber || undefined,
|
||||
},
|
||||
);
|
||||
setNotice(`Device created. It should publish points to ${created.provisioning.pointsTopic}`);
|
||||
setForm({ name: '', mqttUsername: '', serialNumber: '' });
|
||||
reload();
|
||||
} catch (err: any) {
|
||||
setError(err.message);
|
||||
}
|
||||
};
|
||||
|
||||
const toggleActive = async (device: DeviceRow) => {
|
||||
try {
|
||||
await api.patch(`/api/orgs/${orgId}/devices/${device.id}`, { isActive: !device.isActive });
|
||||
reload();
|
||||
} catch (err: any) {
|
||||
setError(err.message);
|
||||
}
|
||||
};
|
||||
|
||||
const remove = async (deviceId: string) => {
|
||||
try {
|
||||
await api.delete(`/api/orgs/${orgId}/devices/${deviceId}`);
|
||||
reload();
|
||||
} catch (err: any) {
|
||||
setError(err.message);
|
||||
}
|
||||
};
|
||||
|
||||
if (loading || !user) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<Layout title="Devices">
|
||||
<h1>Devices</h1>
|
||||
<p style={{ color: '#666' }}>
|
||||
Field devices publish to <code>devices/<mqtt username>/points</code>. Broker credentials are provisioned
|
||||
separately for now.
|
||||
</p>
|
||||
{error && <p style={{ color: '#c62828' }}>{error}</p>}
|
||||
{notice && <p style={{ color: '#388e3c' }}>{notice}</p>}
|
||||
|
||||
{isAdmin && (
|
||||
<form onSubmit={addDevice} style={{ display: 'flex', gap: '0.5rem', marginBottom: '1.5rem', flexWrap: 'wrap' }}>
|
||||
<input
|
||||
placeholder="name"
|
||||
value={form.name}
|
||||
onChange={(e) => setForm((f) => ({ ...f, name: e.target.value }))}
|
||||
required
|
||||
style={{ padding: '0.4rem' }}
|
||||
/>
|
||||
<input
|
||||
placeholder="mqtt username"
|
||||
value={form.mqttUsername}
|
||||
onChange={(e) => setForm((f) => ({ ...f, mqttUsername: e.target.value }))}
|
||||
required
|
||||
style={{ padding: '0.4rem' }}
|
||||
/>
|
||||
<input
|
||||
placeholder="serial number (optional)"
|
||||
value={form.serialNumber}
|
||||
onChange={(e) => setForm((f) => ({ ...f, serialNumber: e.target.value }))}
|
||||
style={{ padding: '0.4rem' }}
|
||||
/>
|
||||
<button type="submit">Add device</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>MQTT username</th>
|
||||
<th>Serial</th>
|
||||
<th>Status</th>
|
||||
<th>Last seen</th>
|
||||
{isAdmin && <th />}
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{devices.map((d) => (
|
||||
<tr key={d.id} style={{ borderBottom: '1px solid #eee' }}>
|
||||
<td style={{ padding: '0.5rem' }}>{d.name}</td>
|
||||
<td>
|
||||
<code>{d.mqttUsername}</code>
|
||||
</td>
|
||||
<td>{d.serialNumber ?? '—'}</td>
|
||||
<td style={{ color: d.isActive ? '#388e3c' : '#9e9e9e' }}>{d.isActive ? 'active' : 'disabled'}</td>
|
||||
<td>{d.lastSeenAt ? new Date(d.lastSeenAt).toLocaleString() : 'never'}</td>
|
||||
{isAdmin && (
|
||||
<td style={{ textAlign: 'right', whiteSpace: 'nowrap' }}>
|
||||
<button onClick={() => toggleActive(d)}>{d.isActive ? 'Disable' : 'Enable'}</button>{' '}
|
||||
<button onClick={() => remove(d.id)}>Delete</button>
|
||||
</td>
|
||||
)}
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</Layout>
|
||||
);
|
||||
}
|
||||
138
web/pages/settings/members.tsx
Normal file
138
web/pages/settings/members.tsx
Normal file
@@ -0,0 +1,138 @@
|
||||
import { FormEvent, useCallback, useEffect, useState } from 'react';
|
||||
import Layout from '../../components/Layout';
|
||||
import { api } from '../../lib/api';
|
||||
import { useRequireAuth } from '../../lib/auth-context';
|
||||
|
||||
interface MemberRow {
|
||||
role: string;
|
||||
createdAt: string;
|
||||
user: { id: string; email: string; name: string };
|
||||
}
|
||||
|
||||
const ROLES = ['ORG_ADMIN', 'MEMBER', 'VIEWER'];
|
||||
|
||||
export default function MembersPage() {
|
||||
const { user, activeOrg, loading } = useRequireAuth();
|
||||
const orgId = activeOrg?.org.id ?? null;
|
||||
const isAdmin = activeOrg?.role === 'ORG_ADMIN';
|
||||
|
||||
const [members, setMembers] = useState<MemberRow[]>([]);
|
||||
const [email, setEmail] = useState('');
|
||||
const [role, setRole] = useState('MEMBER');
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const reload = useCallback(() => {
|
||||
if (!orgId) {
|
||||
return;
|
||||
}
|
||||
api
|
||||
.get<MemberRow[]>(`/api/orgs/${orgId}/members`)
|
||||
.then((rows) => {
|
||||
setMembers(rows);
|
||||
setError(null);
|
||||
})
|
||||
.catch((err) => setError(err.message));
|
||||
}, [orgId]);
|
||||
|
||||
useEffect(reload, [reload]);
|
||||
|
||||
const addMember = async (e: FormEvent) => {
|
||||
e.preventDefault();
|
||||
try {
|
||||
await api.post(`/api/orgs/${orgId}/members`, { email, role });
|
||||
setEmail('');
|
||||
reload();
|
||||
} catch (err: any) {
|
||||
setError(err.message);
|
||||
}
|
||||
};
|
||||
|
||||
const changeRole = async (userId: string, newRole: string) => {
|
||||
try {
|
||||
await api.patch(`/api/orgs/${orgId}/members/${userId}`, { role: newRole });
|
||||
reload();
|
||||
} catch (err: any) {
|
||||
setError(err.message);
|
||||
}
|
||||
};
|
||||
|
||||
const remove = async (userId: string) => {
|
||||
try {
|
||||
await api.delete(`/api/orgs/${orgId}/members/${userId}`);
|
||||
reload();
|
||||
} catch (err: any) {
|
||||
setError(err.message);
|
||||
}
|
||||
};
|
||||
|
||||
if (loading || !user) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<Layout title="Members">
|
||||
<h1>Members</h1>
|
||||
{error && <p style={{ color: '#c62828' }}>{error}</p>}
|
||||
|
||||
{isAdmin && (
|
||||
<form onSubmit={addMember} style={{ display: 'flex', gap: '0.5rem', marginBottom: '1.5rem' }}>
|
||||
<input
|
||||
type="email"
|
||||
placeholder="registered user's email"
|
||||
value={email}
|
||||
onChange={(e) => setEmail(e.target.value)}
|
||||
required
|
||||
style={{ padding: '0.4rem', width: 280 }}
|
||||
/>
|
||||
<select value={role} onChange={(e) => setRole(e.target.value)}>
|
||||
{ROLES.map((r) => (
|
||||
<option key={r} value={r}>
|
||||
{r}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
<button type="submit">Add member</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>Email</th>
|
||||
<th>Role</th>
|
||||
<th>Since</th>
|
||||
{isAdmin && <th />}
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{members.map((m) => (
|
||||
<tr key={m.user.id} style={{ borderBottom: '1px solid #eee' }}>
|
||||
<td style={{ padding: '0.5rem' }}>{m.user.name}</td>
|
||||
<td>{m.user.email}</td>
|
||||
<td>
|
||||
{isAdmin && m.user.id !== user.id ? (
|
||||
<select value={m.role} onChange={(e) => changeRole(m.user.id, e.target.value)}>
|
||||
{ROLES.map((r) => (
|
||||
<option key={r} value={r}>
|
||||
{r}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
) : (
|
||||
m.role
|
||||
)}
|
||||
</td>
|
||||
<td>{new Date(m.createdAt).toLocaleDateString()}</td>
|
||||
{isAdmin && (
|
||||
<td style={{ textAlign: 'right' }}>
|
||||
{m.user.id !== user.id && <button onClick={() => remove(m.user.id)}>Remove</button>}
|
||||
</td>
|
||||
)}
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</Layout>
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user