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>
121 lines
3.5 KiB
JavaScript
121 lines
3.5 KiB
JavaScript
import { ref, computed } from "vue";
|
|
|
|
// The panel authenticates exactly like any other DriverVault client: it posts to
|
|
// /api/auth/login and keeps the PocketBase token the API Server relays back. The
|
|
// panel never talks to PocketBase directly — it doesn't even know its address.
|
|
const TOKEN_KEY = "dh-panel-token";
|
|
|
|
function storedToken() {
|
|
try {
|
|
return localStorage.getItem(TOKEN_KEY) || "";
|
|
} catch {
|
|
return ""; // private mode
|
|
}
|
|
}
|
|
|
|
export const token = ref(storedToken());
|
|
export const me = ref(null);
|
|
|
|
export const isSuperadmin = computed(() => me.value?.role === "superadmin");
|
|
export const isManager = computed(
|
|
() => me.value?.role === "admin" || me.value?.role === "superadmin",
|
|
);
|
|
|
|
function setToken(value) {
|
|
token.value = value;
|
|
try {
|
|
if (value) localStorage.setItem(TOKEN_KEY, value);
|
|
else localStorage.removeItem(TOKEN_KEY);
|
|
} catch {
|
|
/* private mode — the session just won't survive a reload */
|
|
}
|
|
}
|
|
|
|
/** ApiError carries the HTTP status so callers can branch on 401/403/503. */
|
|
export class ApiError extends Error {
|
|
constructor(message, status, body) {
|
|
super(message);
|
|
this.status = status;
|
|
this.body = body;
|
|
}
|
|
}
|
|
|
|
// messageFrom digs a human-readable message out of the several error shapes in
|
|
// play: this server's {error}, and PocketBase's {message, data:{field:{message}}}
|
|
// which the user/org endpoints relay verbatim.
|
|
function messageFrom(body, status) {
|
|
if (!body || typeof body !== "object") return `HTTP ${status}`;
|
|
if (body.error) return body.error;
|
|
const fieldErrors = Object.entries(body.data || {})
|
|
.map(([field, e]) => `${field}: ${e?.message || e}`)
|
|
.filter(Boolean);
|
|
if (fieldErrors.length) return fieldErrors.join("; ");
|
|
return body.message || `HTTP ${status}`;
|
|
}
|
|
|
|
/**
|
|
* request calls the API Server, attaching the panel's token. A 401 clears the
|
|
* session so the shell falls back to the login screen.
|
|
*/
|
|
export async function request(path, { method = "GET", body, auth = true } = {}) {
|
|
const headers = {};
|
|
if (body !== undefined) headers["Content-Type"] = "application/json";
|
|
if (auth && token.value) headers.Authorization = token.value;
|
|
|
|
const resp = await fetch(path, {
|
|
method,
|
|
headers,
|
|
body: body === undefined ? undefined : JSON.stringify(body),
|
|
});
|
|
|
|
const text = await resp.text();
|
|
let parsed = null;
|
|
try {
|
|
parsed = text ? JSON.parse(text) : null;
|
|
} catch {
|
|
parsed = null; // non-JSON body (shouldn't happen, but don't explode on it)
|
|
}
|
|
|
|
if (!resp.ok) {
|
|
if (resp.status === 401 && auth) logout();
|
|
throw new ApiError(messageFrom(parsed, resp.status), resp.status, parsed);
|
|
}
|
|
return parsed;
|
|
}
|
|
|
|
/** login exchanges credentials for a PocketBase token via the API Server. */
|
|
export async function login(email, password) {
|
|
const out = await request("/api/auth/login", {
|
|
method: "POST",
|
|
body: { email, password },
|
|
auth: false,
|
|
});
|
|
setToken(out.token);
|
|
await loadMe();
|
|
return me.value;
|
|
}
|
|
|
|
/** loadMe resolves the current identity, including role + organization. */
|
|
export async function loadMe() {
|
|
me.value = await request("/api/identity");
|
|
return me.value;
|
|
}
|
|
|
|
/** logout drops the local session. PocketBase tokens are stateless, so there is
|
|
* nothing to revoke server-side. */
|
|
export function logout() {
|
|
setToken("");
|
|
me.value = null;
|
|
}
|
|
|
|
/** restore re-validates a token kept from a previous visit. */
|
|
export async function restore() {
|
|
if (!token.value) return null;
|
|
try {
|
|
return await loadMe();
|
|
} catch {
|
|
logout(); // expired, revoked, or the server now points at another PocketBase
|
|
return null;
|
|
}
|
|
}
|