Rebuild API Server on the PilotVault structure

Mirror PilotVault's API Server layout and add the superadmin console,
plugin system, runtime PocketBase settings, and user/organization
management. The car domain (cars, service records, parts, sharing) is
carried over unchanged apart from the auth switch.

Layout: main.go -> cmd/server/main.go; module carcontrol/api ->
drivervault/apiserver. internal/api is split by concern (auth, users,
orgs, settings, plugins, status, health, respond).

Auth: replace the server-minted HS256 JWT and the sessions collection
with a PocketBase token proxy. /api/auth/login relays PocketBase's
{token, record}, and every protected request re-resolves that token
against PocketBase, so a role change or deletion takes effect at once
instead of waiting out a token. AUTH_SECRET is obsolete and internal/auth
is gone. Per-device session listing/revocation goes with it: PocketBase
tokens are stateless. Changing a password rotates the user's token key,
which invalidates every token already issued.

Roles: add superadmin alongside user/admin, plus an organizations
collection and users.organization. Admins are scoped to their own
organization; superadmins span all of them. Guards prevent changing your
own role, deleting your own account, an admin touching a superadmin, and
deleting an organization that still has members.

Plugins: new internal/plugins package with one contract over two kinds --
builtin (compiled in) and external (any HTTP service, registered at
runtime with no rebuild). State persists to plugins.json; secrets are
masked on read and preserved when saved back at the mask.

PocketBase settings: /api/admin/pb-config applies a new connection at
runtime and persists it to .env. It deliberately does not require a
working service account, so a wrong or unreachable connection can still
be fixed from the panel.

Panel: rebuilt as the superadmin console -- login gate, status, users,
organizations, PocketBase, plugins, and the endpoint reference.

Clients: update the Web App and Phone App for the PocketBase token shape,
the move of user management to /api/users ({users}/{user} envelopes, with
password resets folded into PATCH), and the removal of sessions. Both now
mirror the server's real guards rather than the old last-admin rule, and
parse PocketBase's field-level error shape.

Config: modern POCKETBASE_*/API_ADDR names with legacy PB_*/PORT
fallbacks, so existing .env files keep working. Also fixes /api/status
probing the Web App on 8090 instead of DriverVault's 5173.

Run scripts/setup-pocketbase.mjs to add the organizations collection and
grow users.role; every client must log in once more.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
tajniak81
2026-07-16 22:29:45 +02:00
co-authored by Claude Opus 4.8
parent 7d55f0a4cd
commit ae6ed4ac1e
56 changed files with 4474 additions and 1475 deletions
@@ -0,0 +1,83 @@
<script setup>
import { ref, computed } from "vue";
import { login } from "../api";
const emit = defineEmits(["authenticated"]);
const email = ref("");
const password = ref("");
const error = ref("");
const busy = ref(false);
const canSubmit = computed(() => email.value.trim() !== "" && password.value !== "" && !busy.value);
async function submit() {
if (!canSubmit.value) return;
error.value = "";
busy.value = true;
try {
const who = await login(email.value.trim(), password.value);
// Any DriverVault account can authenticate; the console itself is only
// useful to a manager, and the server enforces that on every call anyway.
emit("authenticated", who);
} catch (e) {
// 400/404 from PocketBase both mean "bad credentials" — don't leak which.
error.value =
e.status === 400 || e.status === 404
? "Invalid email or password."
: e.message || "Could not sign in.";
password.value = "";
} finally {
busy.value = false;
}
}
</script>
<template>
<div class="mx-auto flex w-full max-w-sm flex-col gap-5 pt-24">
<div class="dh-card p-6">
<h1 class="text-lg font-bold tracking-[-0.02em] text-strong">Sign in</h1>
<p class="mt-1 mb-5 text-sm text-body">
Superadmin console for the DriverVault API Server.
</p>
<form class="flex flex-col gap-4" @submit.prevent="submit">
<div>
<label class="dh-label" for="login-email">Email</label>
<input
id="login-email"
v-model="email"
class="dh-input"
type="email"
autocomplete="username"
autofocus
placeholder="you@example.com"
/>
</div>
<div>
<label class="dh-label" for="login-password">Password</label>
<input
id="login-password"
v-model="password"
class="dh-input"
type="password"
autocomplete="current-password"
placeholder="••••••••"
/>
</div>
<p v-if="error" class="rounded-control bg-danger-soft px-3 py-2 text-xs text-danger">
{{ error }}
</p>
<button class="dh-btn w-full" type="submit" :disabled="!canSubmit">
{{ busy ? "Signing in…" : "Sign in" }}
</button>
</form>
</div>
<p class="eyebrow text-center">
Authenticates against PocketBase through this server
</p>
</div>
</template>
@@ -0,0 +1,127 @@
<script setup>
import { ref, onMounted } from "vue";
import { isSuperadmin, request } from "../api";
// Listing is manager-scoped (an admin sees only their own org); creating,
// renaming and deleting are superadmin-only, matching the server's gates.
const orgs = ref([]);
const error = ref("");
const busy = ref(false);
const editing = ref(null); // org id, or "new"
const draftName = ref("");
async function load() {
try {
const out = await request("/api/orgs");
orgs.value = out.organizations || [];
error.value = "";
} catch (e) {
error.value = e.message;
}
}
onMounted(load);
function startNew() {
editing.value = "new";
draftName.value = "";
}
function startEdit(o) {
editing.value = o.id;
draftName.value = o.name;
}
function cancel() {
editing.value = null;
error.value = "";
}
async function save() {
busy.value = true;
error.value = "";
try {
if (editing.value === "new") {
await request("/api/orgs", { method: "POST", body: { name: draftName.value } });
} else {
await request(`/api/orgs/${editing.value}`, {
method: "PATCH",
body: { name: draftName.value },
});
}
editing.value = null;
await load();
} catch (e) {
error.value = e.message;
} finally {
busy.value = false;
}
}
async function remove(o) {
if (!confirm(`Delete the organization "${o.name}"?`)) return;
busy.value = true;
error.value = "";
try {
await request(`/api/orgs/${o.id}`, { method: "DELETE" });
await load();
} catch (e) {
// The server refuses (409) while the org still has members.
error.value = e.message;
} finally {
busy.value = false;
}
}
</script>
<template>
<div class="dh-card overflow-hidden">
<div class="flex items-center justify-between border-b border-subtle px-5 py-4">
<div>
<div class="text-base font-bold tracking-[-0.02em] text-strong">Organizations</div>
<p class="mt-0.5 text-xs text-muted">Tenants users belong to</p>
</div>
<button v-if="isSuperadmin" class="dh-btn" @click="startNew">New organization</button>
</div>
<p v-if="error" class="border-b border-subtle px-5 py-3 text-xs text-danger">{{ error }}</p>
<div v-if="editing" class="border-b border-subtle bg-sunken px-5 py-4">
<label class="dh-label">Name</label>
<input v-model="draftName" class="dh-input" placeholder="Acme Fleet" @keyup.enter="save" />
<div class="mt-3 flex items-center gap-2">
<button class="dh-btn" :disabled="busy || !draftName.trim()" @click="save">
{{ editing === "new" ? "Create" : "Save" }}
</button>
<button class="dh-btn-ghost" :disabled="busy" @click="cancel">Cancel</button>
</div>
</div>
<p v-if="!orgs.length" class="px-5 py-6 text-center text-sm text-muted">
No organizations yet.
</p>
<table v-else class="w-full text-left text-sm">
<thead>
<tr class="[&>th]:eyebrow [&>th]:px-5 [&>th]:py-2.5 [&>th]:font-medium">
<th>Name</th>
<th>ID</th>
<th></th>
</tr>
</thead>
<tbody>
<tr v-for="o in orgs" :key="o.id" class="border-t border-subtle transition-colors hover:bg-sunken">
<td class="px-5 py-2.5 font-medium text-strong">{{ o.name }}</td>
<td class="data px-5 py-2.5 text-xs text-muted">{{ o.id }}</td>
<td class="px-5 py-2.5 text-right whitespace-nowrap">
<template v-if="isSuperadmin">
<button class="dh-btn-ghost" @click="startEdit(o)">Rename</button>
<button class="dh-btn-danger ml-1.5" :disabled="busy" @click="remove(o)">
Delete
</button>
</template>
</td>
</tr>
</tbody>
</table>
</div>
</template>
@@ -0,0 +1,242 @@
<script setup>
import { ref, onMounted, reactive } from "vue";
import { request } from "../api";
// Superadmin-only. Each plugin advertises its own config fields (Descriptor.
// ConfigFields), so the form below is generated rather than hard-coded — that's
// what lets an external plugin be added without touching this panel.
const plugins = ref([]);
const error = ref("");
const busy = ref(false);
const open = ref(null); // name of the expanded plugin
const drafts = reactive({}); // name -> { key: value }
const rowNotice = reactive({}); // name -> string
const showRegister = ref(false);
const reg = ref({ name: "", baseURL: "", provider: "" });
async function load() {
try {
const out = await request("/api/admin/plugins");
plugins.value = out.plugins || [];
error.value = "";
} catch (e) {
error.value = e.message;
}
}
onMounted(load);
function expand(p) {
if (open.value === p.name) {
open.value = null;
return;
}
// Seed the draft from the (secret-masked) stored config plus field defaults.
const d = {};
for (const f of p.configFields || []) d[f.key] = p.config?.[f.key] ?? "";
drafts[p.name] = d;
open.value = p.name;
}
async function save(p, enabled) {
busy.value = true;
rowNotice[p.name] = "";
try {
const out = await request(`/api/admin/plugins/${encodeURIComponent(p.name)}`, {
method: "PUT",
body: { enabled, config: drafts[p.name] ?? {} },
});
// A save can succeed while Init fails (e.g. bad credentials) — the server
// returns the saved plugin plus a warning.
rowNotice[p.name] = out.warning || "Saved.";
await load();
} catch (e) {
rowNotice[p.name] = e.message;
} finally {
busy.value = false;
}
}
async function health(p) {
busy.value = true;
rowNotice[p.name] = "Checking…";
try {
const out = await request(`/api/admin/plugins/${encodeURIComponent(p.name)}/health`, {
method: "POST",
});
rowNotice[p.name] = `${out.health.status}${out.health.detail ? " — " + out.health.detail : ""}`;
await load();
} catch (e) {
rowNotice[p.name] = e.message;
} finally {
busy.value = false;
}
}
async function remove(p) {
if (!confirm(`Remove the external plugin "${p.name}"? Its saved config is deleted.`)) return;
busy.value = true;
try {
await request(`/api/admin/plugins/${encodeURIComponent(p.name)}`, { method: "DELETE" });
if (open.value === p.name) open.value = null;
await load();
} catch (e) {
rowNotice[p.name] = e.message;
} finally {
busy.value = false;
}
}
async function registerExternal() {
busy.value = true;
error.value = "";
try {
await request("/api/admin/plugins", { method: "POST", body: reg.value });
reg.value = { name: "", baseURL: "", provider: "" };
showRegister.value = false;
await load();
} catch (e) {
error.value = e.message;
} finally {
busy.value = false;
}
}
const healthClass = (s) =>
s === "ok"
? "bg-success-soft text-success"
: s === "degraded"
? "bg-warning-soft text-warning"
: "bg-danger-soft text-danger";
</script>
<template>
<div class="dh-card overflow-hidden">
<div class="flex items-center justify-between border-b border-subtle px-5 py-4">
<div>
<div class="text-base font-bold tracking-[-0.02em] text-strong">Plugins</div>
<p class="mt-0.5 text-xs text-muted">Third-party service integrations</p>
</div>
<button class="dh-btn-ghost" @click="showRegister = !showRegister">
{{ showRegister ? "Cancel" : "Register external" }}
</button>
</div>
<!-- Register an external (remote HTTP) plugin the no-rebuild path. -->
<div v-if="showRegister" class="border-b border-subtle bg-sunken px-5 py-4">
<div class="grid gap-3 sm:grid-cols-3">
<div>
<label class="dh-label">Name</label>
<input v-model="reg.name" class="dh-input" placeholder="acme-parts" />
</div>
<div>
<label class="dh-label">Base URL</label>
<input v-model="reg.baseURL" class="dh-input" placeholder="http://127.0.0.1:9100" />
</div>
<div>
<label class="dh-label">Provider</label>
<input v-model="reg.provider" class="dh-input" placeholder="ACME Corp" />
</div>
</div>
<button
class="dh-btn mt-3"
:disabled="busy || !reg.name || !reg.baseURL"
@click="registerExternal"
>
Register
</button>
</div>
<p v-if="error" class="border-b border-subtle px-5 py-3 text-xs text-danger">{{ error }}</p>
<p v-if="!plugins.length" class="px-5 py-6 text-center text-sm text-muted">
No plugins yet. Register an external one above, or compile a built-in connector.
</p>
<div v-for="p in plugins" :key="p.name" class="border-t border-subtle first:border-t-0">
<!-- Summary row -->
<div class="flex items-center gap-3 px-5 py-3">
<button class="flex flex-1 items-center gap-3 text-left" @click="expand(p)">
<span class="font-semibold text-strong">{{ p.name }}</span>
<span class="dh-pill bg-sunken text-muted">{{ p.kind || "builtin" }}</span>
<span v-if="p.provider" class="text-xs text-muted">{{ p.provider }}</span>
<span v-if="p.health" class="dh-pill" :class="healthClass(p.health.status)">
<span class="h-1.5 w-1.5 rounded-full bg-current"></span>{{ p.health.status }}
</span>
</button>
<span class="dh-pill" :class="p.enabled ? 'bg-success-soft text-success' : 'bg-sunken text-muted'">
{{ p.enabled ? "enabled" : "disabled" }}
</span>
<button class="dh-btn-ghost" :disabled="busy" @click="health(p)">Health</button>
<button
class="dh-btn-ghost"
:disabled="busy"
@click="expand(p)"
>
{{ open === p.name ? "Close" : "Configure" }}
</button>
</div>
<!-- Expanded config: generated from the plugin's declared fields. -->
<div v-if="open === p.name" class="bg-sunken px-5 py-4">
<div v-if="p.baseURL" class="data mb-3 text-xs text-muted">{{ p.baseURL }}</div>
<div v-if="(p.configFields || []).length" class="grid gap-3 sm:grid-cols-2">
<div v-for="f in p.configFields" :key="f.key">
<label class="dh-label">
{{ f.label || f.key }}<span v-if="f.required" class="text-danger"> *</span>
</label>
<select v-if="f.type === 'select'" v-model="drafts[p.name][f.key]" class="dh-select">
<option v-for="o in f.options || []" :key="o.value" :value="o.value">
{{ o.label || o.value }}
</option>
</select>
<input
v-else
v-model="drafts[p.name][f.key]"
class="dh-input"
:type="f.type === 'password' ? 'password' : f.type === 'number' ? 'number' : 'text'"
:placeholder="f.default || ''"
autocomplete="off"
/>
<p v-if="f.help" class="mt-1 text-xs text-muted">{{ f.help }}</p>
</div>
</div>
<p v-else class="text-xs text-muted">This plugin takes no configuration.</p>
<div v-if="(p.capabilities || []).length" class="mt-4">
<div class="eyebrow mb-1.5">Capabilities</div>
<ul class="data flex flex-col gap-1 text-xs text-muted">
<li v-for="c in p.capabilities" :key="c.id">
<span class="text-strong">{{ c.id }}</span>
<span v-if="c.method || c.endpoint"> — {{ c.method }} {{ c.endpoint }}</span>
<span v-if="c.description"> · {{ c.description }}</span>
</li>
</ul>
</div>
<p v-if="rowNotice[p.name]" class="data mt-3 text-xs text-body">{{ rowNotice[p.name] }}</p>
<div class="mt-4 flex items-center gap-2">
<button class="dh-btn" :disabled="busy" @click="save(p, true)">
{{ p.enabled ? "Save" : "Save &amp; enable" }}
</button>
<button v-if="p.enabled" class="dh-btn-ghost" :disabled="busy" @click="save(p, false)">
Disable
</button>
<span class="flex-1"></span>
<button
v-if="p.kind === 'external'"
class="dh-btn-danger"
:disabled="busy"
@click="remove(p)"
>
Remove
</button>
</div>
<p v-if="p.kind !== 'external'" class="eyebrow mt-2">
Built-in plugins can be disabled but not removed
</p>
</div>
</div>
</div>
</template>
@@ -0,0 +1,126 @@
<script setup>
import { ref, onMounted } from "vue";
import { request } from "../api";
// Superadmin-only: retarget the PocketBase this server talks to. The change is
// applied at runtime AND persisted to the server's .env, so it survives a
// restart. A blank password means "keep the stored one".
const cfg = ref(null);
const form = ref({ url: "", adminEmail: "", adminPassword: "" });
const probe = ref(null);
const error = ref("");
const notice = ref("");
const busy = ref(false);
async function load() {
try {
cfg.value = await request("/api/admin/pb-config");
form.value = {
url: cfg.value.url,
adminEmail: cfg.value.adminEmail,
adminPassword: "",
};
probe.value = cfg.value.probe;
} catch (e) {
error.value = e.message;
}
}
onMounted(load);
async function test() {
error.value = "";
notice.value = "";
busy.value = true;
try {
probe.value = await request("/api/admin/pb-config/test", {
method: "POST",
body: form.value,
});
notice.value = probe.value.superuser
? "Connection OK — superuser authenticated."
: probe.value.reachable
? "PocketBase is reachable, but the service account did not authenticate."
: "PocketBase is not reachable at that address.";
} catch (e) {
error.value = e.message;
} finally {
busy.value = false;
}
}
async function save() {
error.value = "";
notice.value = "";
busy.value = true;
try {
const out = await request("/api/admin/pb-config", { method: "PUT", body: form.value });
cfg.value = out.config;
probe.value = out.config.probe;
form.value.adminPassword = "";
notice.value = out.warning || "Saved. The server is now using this PocketBase.";
} catch (e) {
error.value = e.message;
} finally {
busy.value = false;
}
}
</script>
<template>
<div class="dh-card overflow-hidden">
<div class="flex items-center justify-between border-b border-subtle px-5 py-4">
<div>
<div class="text-base font-bold tracking-[-0.02em] text-strong">PocketBase</div>
<p class="mt-0.5 text-xs text-muted">Database connection used by every endpoint</p>
</div>
<span
v-if="probe"
class="dh-pill"
:class="probe.superuser
? 'bg-success-soft text-success'
: probe.reachable
? 'bg-warning-soft text-warning'
: 'bg-danger-soft text-danger'"
>
<span class="h-1.5 w-1.5 rounded-full bg-current"></span>
{{ probe.superuser ? "connected" : probe.reachable ? "no superuser" : "unreachable" }}
</span>
</div>
<div class="flex flex-col gap-4 px-5 py-4">
<div>
<label class="dh-label" for="pb-url">Base URL</label>
<input id="pb-url" v-model="form.url" class="dh-input" placeholder="http://10.2.1.10:8027" />
</div>
<div class="grid gap-4 sm:grid-cols-2">
<div>
<label class="dh-label" for="pb-email">Superuser email</label>
<input id="pb-email" v-model="form.adminEmail" class="dh-input" autocomplete="off" />
</div>
<div>
<label class="dh-label" for="pb-password">Superuser password</label>
<input
id="pb-password"
v-model="form.adminPassword"
class="dh-input"
type="password"
autocomplete="new-password"
:placeholder="cfg?.adminConfigured ? 'unchanged' : 'not set'"
/>
</div>
</div>
<p v-if="probe?.detail" class="data text-xs text-muted">{{ probe.detail }}</p>
<p v-if="notice" class="rounded-control bg-info-soft px-3 py-2 text-xs text-info">{{ notice }}</p>
<p v-if="error" class="rounded-control bg-danger-soft px-3 py-2 text-xs text-danger">{{ error }}</p>
<div class="flex items-center gap-2">
<button class="dh-btn" :disabled="busy" @click="save">Save &amp; apply</button>
<button class="dh-btn-ghost" :disabled="busy" @click="test">Test connection</button>
<span class="flex-1"></span>
<span class="eyebrow">persisted to .env</span>
</div>
</div>
</div>
</template>
@@ -0,0 +1,65 @@
<script setup>
import { ref, onMounted, onUnmounted } from "vue";
import { request } from "../api";
// /api/status probes PocketBase and the Web App server-side, so the browser
// never has to reach either directly.
const status = ref(null);
const error = ref("");
let timer = null;
async function check() {
try {
status.value = await request("/api/status", { auth: false });
error.value = "";
} catch (e) {
status.value = null;
error.value = e.message || "unreachable";
}
}
onMounted(() => {
check();
timer = setInterval(check, 10000);
});
onUnmounted(() => clearInterval(timer));
const pillFor = (s) =>
s === "ok" ? "bg-success-soft text-success" : "bg-danger-soft text-danger";
</script>
<template>
<div class="dh-card overflow-hidden">
<div class="flex items-center justify-between border-b border-subtle px-5 py-4">
<div class="text-base font-bold tracking-[-0.02em] text-strong">Status</div>
<span v-if="error" class="dh-pill bg-danger-soft text-danger">
<span class="h-1.5 w-1.5 rounded-full bg-current"></span>unreachable
</span>
</div>
<div v-if="error" class="px-5 py-4 text-sm text-danger">{{ error }}</div>
<table v-else-if="status" class="w-full text-left text-sm">
<tbody>
<tr v-for="row in [
{ key: 'apiServer', label: 'API Server', h: status.apiServer },
{ key: 'pocketBase', label: 'PocketBase', h: status.pocketBase },
{ key: 'webApp', label: 'Web App', h: status.webApp },
]" :key="row.key" class="border-t border-subtle first:border-t-0">
<td class="px-5 py-3 font-medium text-strong">{{ row.label }}</td>
<td class="data px-5 py-3 text-xs text-muted">{{ row.h.url || "this process" }}</td>
<td class="data px-5 py-3 text-right text-xs text-muted">
{{ row.h.latencyMs != null ? row.h.latencyMs + "ms" : "—" }}
</td>
<td class="px-5 py-3 text-right">
<span class="dh-pill" :class="pillFor(row.h.status)">
<span class="h-1.5 w-1.5 rounded-full bg-current"></span>{{ row.h.status }}
</span>
</td>
</tr>
</tbody>
</table>
<div v-else class="px-5 py-4 text-sm text-muted">Checking</div>
</div>
</template>
@@ -0,0 +1,198 @@
<script setup>
import { ref, onMounted, computed } from "vue";
import { request, me, isSuperadmin } from "../api";
// Manager-only. A superadmin sees and edits everyone; an admin is scoped by the
// server to their own organization. The UI mirrors those limits, but the server
// is what enforces them.
const users = ref([]);
const orgs = ref([]);
const error = ref("");
const busy = ref(false);
const editing = ref(null); // user id being edited, or "new"
const draft = ref({});
const roles = computed(() =>
isSuperadmin.value ? ["user", "admin", "superadmin"] : ["user", "admin"],
);
async function load() {
try {
const [u, o] = await Promise.all([request("/api/users"), request("/api/orgs")]);
users.value = u.users || [];
orgs.value = o.organizations || [];
error.value = "";
} catch (e) {
error.value = e.message;
}
}
onMounted(load);
function startNew() {
editing.value = "new";
draft.value = {
email: "",
name: "",
password: "",
role: "user",
organization: isSuperadmin.value ? "" : me.value?.organization || "",
};
}
function startEdit(u) {
editing.value = u.id;
draft.value = {
email: u.email,
name: u.name || "",
password: "",
role: u.role,
organization: u.organization || "",
};
}
function cancel() {
editing.value = null;
error.value = "";
}
async function save() {
busy.value = true;
error.value = "";
try {
if (editing.value === "new") {
await request("/api/users", { method: "POST", body: draft.value });
} else {
// Only send a password when one was typed — blank means "leave it".
const body = { ...draft.value };
if (!body.password) delete body.password;
await request(`/api/users/${editing.value}`, { method: "PATCH", body });
}
editing.value = null;
await load();
} catch (e) {
error.value = e.message;
} finally {
busy.value = false;
}
}
async function remove(u) {
if (!confirm(`Delete ${u.email}? This cannot be undone.`)) return;
busy.value = true;
error.value = "";
try {
await request(`/api/users/${u.id}`, { method: "DELETE" });
await load();
} catch (e) {
error.value = e.message;
} finally {
busy.value = false;
}
}
const roleClass = (r) =>
r === "superadmin"
? "bg-info-soft text-info"
: r === "admin"
? "bg-warning-soft text-warning"
: "bg-sunken text-muted";
</script>
<template>
<div class="dh-card overflow-hidden">
<div class="flex items-center justify-between border-b border-subtle px-5 py-4">
<div>
<div class="text-base font-bold tracking-[-0.02em] text-strong">Users</div>
<p class="mt-0.5 text-xs text-muted">
{{ isSuperadmin ? "All organizations" : "Your organization" }}
</p>
</div>
<button class="dh-btn" @click="startNew">New user</button>
</div>
<p v-if="error" class="border-b border-subtle px-5 py-3 text-xs text-danger">{{ error }}</p>
<!-- Create / edit form -->
<div v-if="editing" class="border-b border-subtle bg-sunken px-5 py-4">
<div class="grid gap-3 sm:grid-cols-2">
<div>
<label class="dh-label">Email</label>
<input v-model="draft.email" class="dh-input" type="email" autocomplete="off" />
</div>
<div>
<label class="dh-label">Name</label>
<input v-model="draft.name" class="dh-input" autocomplete="off" />
</div>
<div>
<label class="dh-label">
Password{{ editing === "new" ? "" : " (blank = unchanged)" }}
</label>
<input
v-model="draft.password"
class="dh-input"
type="password"
autocomplete="new-password"
placeholder="min 8 characters"
/>
</div>
<div>
<label class="dh-label">Role</label>
<select v-model="draft.role" class="dh-select">
<option v-for="r in roles" :key="r" :value="r">{{ r }}</option>
</select>
</div>
<div v-if="isSuperadmin">
<label class="dh-label">Organization</label>
<select v-model="draft.organization" class="dh-select">
<option value=""> none </option>
<option v-for="o in orgs" :key="o.id" :value="o.id">{{ o.name }}</option>
</select>
</div>
</div>
<div class="mt-3 flex items-center gap-2">
<button class="dh-btn" :disabled="busy" @click="save">
{{ editing === "new" ? "Create" : "Save" }}
</button>
<button class="dh-btn-ghost" :disabled="busy" @click="cancel">Cancel</button>
</div>
</div>
<p v-if="!users.length" class="px-5 py-6 text-center text-sm text-muted">No users.</p>
<table v-else class="w-full text-left text-sm">
<thead>
<tr class="[&>th]:eyebrow [&>th]:px-5 [&>th]:py-2.5 [&>th]:font-medium">
<th>Email</th>
<th>Name</th>
<th>Organization</th>
<th>Role</th>
<th></th>
</tr>
</thead>
<tbody>
<tr v-for="u in users" :key="u.id" class="border-t border-subtle transition-colors hover:bg-sunken">
<td class="data px-5 py-2.5 text-xs text-strong">
{{ u.email }}
<span v-if="u.id === me?.id" class="eyebrow ml-1">you</span>
</td>
<td class="px-5 py-2.5 text-body">{{ u.name || "—" }}</td>
<td class="px-5 py-2.5 text-body">{{ u.organizationName || "—" }}</td>
<td class="px-5 py-2.5">
<span class="dh-pill" :class="roleClass(u.role)">{{ u.role }}</span>
</td>
<td class="px-5 py-2.5 text-right whitespace-nowrap">
<button class="dh-btn-ghost" @click="startEdit(u)">Edit</button>
<button
v-if="u.id !== me?.id"
class="dh-btn-danger ml-1.5"
:disabled="busy"
@click="remove(u)"
>
Delete
</button>
</td>
</tr>
</tbody>
</table>
</div>
</template>