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>
236 lines
6.4 KiB
Go
236 lines
6.4 KiB
Go
package api
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"fmt"
|
|
"net/http"
|
|
"net/url"
|
|
|
|
"drivervault/apiserver/internal/models"
|
|
)
|
|
|
|
// Access levels a user can have on a car. accessNone means no access at all.
|
|
const (
|
|
accessNone = ""
|
|
accessRead = "read"
|
|
accessWrite = "write"
|
|
accessOwner = "owner"
|
|
)
|
|
|
|
// carAccessLevel reports the requesting user's permission on a car: "owner" if
|
|
// they own it, otherwise the permission from any car_shares grant ("read"/
|
|
// "write"), otherwise "" (no access). It also returns the car record so callers
|
|
// that already need it avoid a second fetch.
|
|
func (s *Server) carAccessLevel(ctx context.Context, userID, carID string) (string, *carRecord, error) {
|
|
var rec carRecord
|
|
if err := s.pb.GetOne(ctx, colCars, carID, &rec); err != nil {
|
|
return accessNone, nil, err
|
|
}
|
|
if rec.Owner == userID {
|
|
return accessOwner, &rec, nil
|
|
}
|
|
perm, err := s.sharePermission(ctx, carID, userID)
|
|
if err != nil {
|
|
return accessNone, &rec, err
|
|
}
|
|
return perm, &rec, nil
|
|
}
|
|
|
|
// sharePermission returns the permission ("read"/"write") granted to userID on
|
|
// carID via car_shares, or "" if there is no grant.
|
|
func (s *Server) sharePermission(ctx context.Context, carID, userID string) (string, error) {
|
|
res, err := s.pb.List(ctx, colShares, url.Values{
|
|
"filter": {fmt.Sprintf("car='%s' && user='%s'", carID, userID)},
|
|
"perPage": {"1"},
|
|
})
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
var recs []shareRecord
|
|
if err := json.Unmarshal(res.Items, &recs); err != nil || len(recs) == 0 {
|
|
return "", err
|
|
}
|
|
return recs[0].Permission, nil
|
|
}
|
|
|
|
func canWrite(level string) bool { return level == accessOwner || level == accessWrite }
|
|
|
|
// requireCarAccess enforces that the current user's access to carID meets the
|
|
// minimum `need` (accessRead = any access, accessWrite = write or owner,
|
|
// accessOwner = owner only). On failure it writes the HTTP response and returns
|
|
// false, so callers can `if !s.requireCarAccess(...) { return }`.
|
|
func (s *Server) requireCarAccess(w http.ResponseWriter, r *http.Request, carID, need string) bool {
|
|
if carID == "" {
|
|
writeError(w, http.StatusBadRequest, "car is required")
|
|
return false
|
|
}
|
|
level, _, err := s.carAccessLevel(r.Context(), s.currentUserID(r), carID)
|
|
if err != nil {
|
|
writePBError(w, err)
|
|
return false
|
|
}
|
|
var ok bool
|
|
switch need {
|
|
case accessWrite:
|
|
ok = canWrite(level)
|
|
case accessOwner:
|
|
ok = level == accessOwner
|
|
default: // accessRead / any
|
|
ok = level != accessNone
|
|
}
|
|
if !ok {
|
|
writeError(w, http.StatusForbidden, "you do not have access to this car")
|
|
return false
|
|
}
|
|
return true
|
|
}
|
|
|
|
func (s *Server) listCars(w http.ResponseWriter, r *http.Request) {
|
|
me := s.currentUserID(r)
|
|
|
|
// Cars the user owns.
|
|
ownedRes, err := s.pb.List(r.Context(), colCars, url.Values{
|
|
"filter": {fmt.Sprintf("owner='%s'", me)},
|
|
"sort": {"name"},
|
|
"perPage": {"200"},
|
|
})
|
|
if err != nil {
|
|
writePBError(w, err)
|
|
return
|
|
}
|
|
var owned []carRecord
|
|
if err := json.Unmarshal(ownedRes.Items, &owned); err != nil {
|
|
writeError(w, http.StatusInternalServerError, err.Error())
|
|
return
|
|
}
|
|
|
|
out := make([]models.Car, 0, len(owned))
|
|
for _, rec := range owned {
|
|
m := rec.toModel()
|
|
m.Access = accessOwner
|
|
out = append(out, m)
|
|
}
|
|
|
|
// Cars shared with the user (each grant → fetch the car, annotate access).
|
|
sharesRes, err := s.pb.List(r.Context(), colShares, url.Values{
|
|
"filter": {fmt.Sprintf("user='%s'", me)},
|
|
"perPage": {"200"},
|
|
})
|
|
if err != nil {
|
|
writePBError(w, err)
|
|
return
|
|
}
|
|
var shares []shareRecord
|
|
if err := json.Unmarshal(sharesRes.Items, &shares); err != nil {
|
|
writeError(w, http.StatusInternalServerError, err.Error())
|
|
return
|
|
}
|
|
for _, sh := range shares {
|
|
var rec carRecord
|
|
if err := s.pb.GetOne(r.Context(), colCars, sh.Car, &rec); err != nil {
|
|
continue // grant points at a deleted car; skip defensively
|
|
}
|
|
m := rec.toModel()
|
|
m.Access = sh.Permission
|
|
out = append(out, m)
|
|
}
|
|
|
|
writeJSON(w, http.StatusOK, out)
|
|
}
|
|
|
|
func (s *Server) getCar(w http.ResponseWriter, r *http.Request) {
|
|
level, rec, err := s.carAccessLevel(r.Context(), s.currentUserID(r), r.PathValue("id"))
|
|
if err != nil {
|
|
writePBError(w, err)
|
|
return
|
|
}
|
|
if level == accessNone {
|
|
writeError(w, http.StatusForbidden, "you do not have access to this car")
|
|
return
|
|
}
|
|
m := rec.toModel()
|
|
m.Access = level
|
|
writeJSON(w, http.StatusOK, m)
|
|
}
|
|
|
|
func (s *Server) createCar(w http.ResponseWriter, r *http.Request) {
|
|
var in models.Car
|
|
if err := decodeJSON(r, &in); err != nil {
|
|
writeError(w, http.StatusBadRequest, err.Error())
|
|
return
|
|
}
|
|
if in.Name == "" {
|
|
writeError(w, http.StatusBadRequest, "name is required")
|
|
return
|
|
}
|
|
applyCarDefaults(&in)
|
|
|
|
// Owner is always the authenticated user; ignore any client-supplied owner.
|
|
payload := carPayload(in)
|
|
payload["owner"] = s.currentUserID(r)
|
|
|
|
var rec carRecord
|
|
if err := s.pb.Create(r.Context(), colCars, payload, &rec); err != nil {
|
|
writePBError(w, err)
|
|
return
|
|
}
|
|
m := rec.toModel()
|
|
m.Access = accessOwner
|
|
writeJSON(w, http.StatusCreated, m)
|
|
}
|
|
|
|
func (s *Server) updateCar(w http.ResponseWriter, r *http.Request) {
|
|
var in models.Car
|
|
if err := decodeJSON(r, &in); err != nil {
|
|
writeError(w, http.StatusBadRequest, err.Error())
|
|
return
|
|
}
|
|
level, _, err := s.carAccessLevel(r.Context(), s.currentUserID(r), r.PathValue("id"))
|
|
if err != nil {
|
|
writePBError(w, err)
|
|
return
|
|
}
|
|
if !canWrite(level) {
|
|
writeError(w, http.StatusForbidden, "you cannot edit this car")
|
|
return
|
|
}
|
|
// carPayload deliberately omits owner, so a PATCH never reassigns ownership.
|
|
var rec carRecord
|
|
if err := s.pb.Update(r.Context(), colCars, r.PathValue("id"), carPayload(in), &rec); err != nil {
|
|
writePBError(w, err)
|
|
return
|
|
}
|
|
m := rec.toModel()
|
|
m.Access = level
|
|
writeJSON(w, http.StatusOK, m)
|
|
}
|
|
|
|
func (s *Server) deleteCar(w http.ResponseWriter, r *http.Request) {
|
|
level, _, err := s.carAccessLevel(r.Context(), s.currentUserID(r), r.PathValue("id"))
|
|
if err != nil {
|
|
writePBError(w, err)
|
|
return
|
|
}
|
|
if level != accessOwner {
|
|
writeError(w, http.StatusForbidden, "only the owner can delete this car")
|
|
return
|
|
}
|
|
if err := s.pb.Delete(r.Context(), colCars, r.PathValue("id")); err != nil {
|
|
writePBError(w, err)
|
|
return
|
|
}
|
|
w.WriteHeader(http.StatusNoContent)
|
|
}
|
|
|
|
// applyCarDefaults fills the spreadsheet's default maintenance intervals when
|
|
// the client didn't specify them.
|
|
func applyCarDefaults(c *models.Car) {
|
|
if c.ServiceIntervalDays <= 0 {
|
|
c.ServiceIntervalDays = 365
|
|
}
|
|
if c.ServiceIntervalKm <= 0 {
|
|
c.ServiceIntervalKm = 15000
|
|
}
|
|
}
|