Files
DriverVault/API Server/internal/api/shares.go
T
tajniak81andClaude Opus 4.8 ae6ed4ac1e 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>
2026-07-16 22:29:45 +02:00

203 lines
5.6 KiB
Go

package api
import (
"encoding/json"
"fmt"
"net/http"
"net/url"
"strings"
)
// shareRecord is the PocketBase-facing shape of a car_shares row: a grant that
// lets `user` access `car` at `permission` ("read"/"write").
type shareRecord struct {
ID string `json:"id"`
Car string `json:"car"`
User string `json:"user"`
Permission string `json:"permission"`
Created string `json:"created"`
}
// shareView is the API shape returned to clients: the grantee's public identity
// plus their permission on the car.
type shareView struct {
User userInfo `json:"user"`
Permission string `json:"permission"`
}
// requireCarOwner ensures the current user owns the car in the {id} path param.
// Sharing management is owner-only. Returns the car id on success, else writes
// the response and returns "".
func (s *Server) requireCarOwner(w http.ResponseWriter, r *http.Request) string {
carID := r.PathValue("id")
level, _, err := s.carAccessLevel(r.Context(), s.currentUserID(r), carID)
if err != nil {
writePBError(w, err)
return ""
}
if level != accessOwner {
writeError(w, http.StatusForbidden, "only the owner can manage sharing")
return ""
}
return carID
}
// handleListShares serves GET /api/cars/{id}/shares (owner only).
func (s *Server) handleListShares(w http.ResponseWriter, r *http.Request) {
carID := s.requireCarOwner(w, r)
if carID == "" {
return
}
res, err := s.pb.List(r.Context(), colShares, url.Values{
"filter": {fmt.Sprintf("car='%s'", carID)},
"perPage": {"200"},
})
if err != nil {
writePBError(w, err)
return
}
var recs []shareRecord
if err := json.Unmarshal(res.Items, &recs); err != nil {
writeError(w, http.StatusInternalServerError, err.Error())
return
}
out := make([]shareView, 0, len(recs))
for _, rec := range recs {
u, err := s.fetchUser(r, rec.User)
if err != nil {
continue // grantee user was deleted; skip defensively
}
out = append(out, shareView{
User: userInfo{ID: u.ID, Email: u.Email, Name: u.Name},
Permission: rec.Permission,
})
}
writeJSON(w, http.StatusOK, out)
}
type shareRequest struct {
Email string `json:"email"`
Permission string `json:"permission"`
}
// handleUpsertShare serves POST /api/cars/{id}/shares (owner only). It grants
// or updates a share for the user identified by email. Body: {email,
// permission}. Idempotent: an existing grant for that user is updated.
func (s *Server) handleUpsertShare(w http.ResponseWriter, r *http.Request) {
carID := s.requireCarOwner(w, r)
if carID == "" {
return
}
var in shareRequest
if err := decodeJSON(r, &in); err != nil {
writeError(w, http.StatusBadRequest, err.Error())
return
}
in.Email = strings.TrimSpace(strings.ToLower(in.Email))
if in.Email == "" {
writeError(w, http.StatusBadRequest, "email is required")
return
}
if in.Permission != accessRead && in.Permission != accessWrite {
writeError(w, http.StatusBadRequest, "permission must be 'read' or 'write'")
return
}
target, err := s.findUserByEmail(r, in.Email)
if err != nil {
writePBError(w, err)
return
}
if target == nil {
writeError(w, http.StatusNotFound, "no user with that email")
return
}
if target.ID == s.currentUserID(r) {
writeError(w, http.StatusBadRequest, "you already own this car")
return
}
// Upsert: update the existing grant's permission, else create a new one.
existing, err := s.findShare(r, carID, target.ID)
if err != nil {
writePBError(w, err)
return
}
payload := map[string]any{"car": carID, "user": target.ID, "permission": in.Permission}
if existing != nil {
if err := s.pb.Update(r.Context(), colShares, existing.ID, payload, nil); err != nil {
writePBError(w, err)
return
}
} else if err := s.pb.Create(r.Context(), colShares, payload, nil); err != nil {
writePBError(w, err)
return
}
writeJSON(w, http.StatusOK, shareView{
User: userInfo{ID: target.ID, Email: target.Email, Name: target.Name},
Permission: in.Permission,
})
}
// handleDeleteShare serves DELETE /api/cars/{id}/shares/{userId} (owner only).
func (s *Server) handleDeleteShare(w http.ResponseWriter, r *http.Request) {
carID := s.requireCarOwner(w, r)
if carID == "" {
return
}
existing, err := s.findShare(r, carID, r.PathValue("userId"))
if err != nil {
writePBError(w, err)
return
}
if existing == nil {
w.WriteHeader(http.StatusNoContent) // already not shared — idempotent
return
}
if err := s.pb.Delete(r.Context(), colShares, existing.ID); err != nil {
writePBError(w, err)
return
}
w.WriteHeader(http.StatusNoContent)
}
// findShare returns the car_shares grant for (carID, userID), or nil if none.
func (s *Server) findShare(r *http.Request, carID, userID string) (*shareRecord, error) {
res, err := s.pb.List(r.Context(), colShares, url.Values{
"filter": {fmt.Sprintf("car='%s' && user='%s'", carID, userID)},
"perPage": {"1"},
})
if err != nil {
return nil, err
}
var recs []shareRecord
if err := json.Unmarshal(res.Items, &recs); err != nil {
return nil, err
}
if len(recs) == 0 {
return nil, nil
}
return &recs[0], nil
}
// findUserByEmail looks up a user in the auth collection by email, returning nil
// if none matches.
func (s *Server) findUserByEmail(r *http.Request, email string) (*userRecord, error) {
res, err := s.pb.List(r.Context(), s.usersCollection(), url.Values{
"filter": {fmt.Sprintf("email='%s'", strings.ReplaceAll(email, "'", ""))},
"perPage": {"1"},
})
if err != nil {
return nil, err
}
var recs []userRecord
if err := json.Unmarshal(res.Items, &recs); err != nil {
return nil, err
}
if len(recs) == 0 {
return nil, nil
}
return &recs[0], nil
}