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:
1 parent
7d55f0a4cd
commit
ae6ed4ac1e
56 files changed
+4474
-1475
No files matched your search
+39
-21
@@ -75,16 +75,39 @@ class ApiClient {
|
||||
|
||||
final data = jsonDecode(res.body);
|
||||
if (res.statusCode < 200 || res.statusCode >= 300) {
|
||||
final msg = data is Map && data["error"] != null ? data["error"].toString() : res.reasonPhrase;
|
||||
throw ApiException(res.statusCode, msg ?? "Request failed");
|
||||
throw ApiException(res.statusCode, _errorMessage(data, res.reasonPhrase));
|
||||
}
|
||||
return data;
|
||||
}
|
||||
|
||||
/// Digs a human-readable message out of the error shapes in play: this
|
||||
/// server's {error}, and PocketBase's {message, data:{field:{message}}} —
|
||||
/// which the user endpoints relay verbatim, so a duplicate email arrives as a
|
||||
/// per-field error rather than a flat string.
|
||||
String _errorMessage(dynamic data, String? fallback) {
|
||||
if (data is! Map) return fallback ?? "Request failed";
|
||||
if (data["error"] != null) return data["error"].toString();
|
||||
|
||||
final fields = data["data"];
|
||||
if (fields is Map && fields.isNotEmpty) {
|
||||
final parts = fields.entries.map((e) {
|
||||
final v = e.value;
|
||||
final msg = v is Map && v["message"] != null ? v["message"] : v;
|
||||
return "${e.key}: $msg";
|
||||
});
|
||||
return parts.join("; ");
|
||||
}
|
||||
if (data["message"] != null) return data["message"].toString();
|
||||
return fallback ?? "Request failed";
|
||||
}
|
||||
|
||||
// --- auth ---
|
||||
/// The API Server proxies login to PocketBase and relays its response
|
||||
/// verbatim, so the user arrives under `record` (PocketBase's name) and the
|
||||
/// token is PocketBase's own — the server no longer mints its own JWT.
|
||||
Future<(String, AuthUser)> login(String email, String password) async {
|
||||
final data = await _send("POST", "/auth/login", body: {"email": email, "password": password});
|
||||
return (data["token"] as String, AuthUser.fromJson(Map<String, dynamic>.from(data["user"])));
|
||||
return (data["token"] as String, AuthUser.fromJson(Map<String, dynamic>.from(data["record"])));
|
||||
}
|
||||
|
||||
// --- cars ---
|
||||
@@ -125,31 +148,35 @@ class ApiClient {
|
||||
Future<void> removeCarShare(String carId, String userId) =>
|
||||
_send("DELETE", "/cars/$carId/shares/$userId");
|
||||
|
||||
// --- admin: user management (admin role only) ---
|
||||
// --- user management (admin or superadmin) ---
|
||||
// Admins are scoped by the server to their own organization; superadmins see
|
||||
// everyone. Responses are enveloped ({users}/{user}).
|
||||
Future<List<AdminUser>> listUsers() async {
|
||||
final data = await _send("GET", "/admin/users") as List;
|
||||
return data.map((e) => AdminUser.fromJson(Map<String, dynamic>.from(e))).toList();
|
||||
final data = await _send("GET", "/users");
|
||||
final items = (data["users"] ?? []) as List;
|
||||
return items.map((e) => AdminUser.fromJson(Map<String, dynamic>.from(e))).toList();
|
||||
}
|
||||
|
||||
Future<AdminUser> createUser(
|
||||
{required String email, required String password, String? name, String role = "user"}) async {
|
||||
final data = await _send("POST", "/admin/users",
|
||||
final data = await _send("POST", "/users",
|
||||
body: {"email": email, "password": password, "name": name ?? "", "role": role});
|
||||
return AdminUser.fromJson(Map<String, dynamic>.from(data));
|
||||
return AdminUser.fromJson(Map<String, dynamic>.from(data["user"]));
|
||||
}
|
||||
|
||||
Future<AdminUser> updateUser(String id, {String? name, String? role}) async {
|
||||
final body = <String, dynamic>{};
|
||||
if (name != null) body["name"] = name;
|
||||
if (role != null) body["role"] = role;
|
||||
final data = await _send("PATCH", "/admin/users/$id", body: body);
|
||||
return AdminUser.fromJson(Map<String, dynamic>.from(data));
|
||||
final data = await _send("PATCH", "/users/$id", body: body);
|
||||
return AdminUser.fromJson(Map<String, dynamic>.from(data["user"]));
|
||||
}
|
||||
|
||||
/// Password resets are a field on the user PATCH now, not a separate endpoint.
|
||||
Future<void> setUserPassword(String id, String newPassword) =>
|
||||
_send("POST", "/admin/users/$id/password", body: {"newPassword": newPassword});
|
||||
_send("PATCH", "/users/$id", body: {"password": newPassword});
|
||||
|
||||
Future<void> deleteUser(String id) => _send("DELETE", "/admin/users/$id");
|
||||
Future<void> deleteUser(String id) => _send("DELETE", "/users/$id");
|
||||
|
||||
// --- service records ---
|
||||
Future<List<ServiceRecord>> listCarServices(String carId) async {
|
||||
@@ -233,15 +260,6 @@ class ApiClient {
|
||||
|
||||
Future<void> deleteAvatar() => _send("DELETE", "/me/avatar");
|
||||
|
||||
// --- settings: sessions ---
|
||||
Future<List<Session>> listSessions() async {
|
||||
final data = await _send("GET", "/sessions") as List;
|
||||
return data.map((e) => Session.fromJson(Map<String, dynamic>.from(e))).toList();
|
||||
}
|
||||
|
||||
Future<void> revokeSession(String id) => _send("DELETE", "/sessions/$id");
|
||||
Future<void> revokeOtherSessions() => _send("DELETE", "/sessions");
|
||||
|
||||
// --- settings: account deletion ---
|
||||
Future<DateTime?> requestAccountDeletion(String confirmEmail) async {
|
||||
final data = await _send("POST", "/me/delete", body: {"confirmEmail": confirmEmail});
|
||||
|
||||
Reference in new issue
Block a user