GET /api/v1/store and /api/v1/people for the native app
Task 2 of the native slice 2 part 1 plan. The two reads beside /api/v1/home, from storeContent and peopleContent behind the member gate: the store's rows in catalogue order with their state and error, and everyone here with their role (owner, member or invited; no joined). 503 unavailable when a read fails; 401 unauthenticated without a member's session. DELETE /api/v1/people/<id> stays unrouted. docs/api/base-native-v1.md gains "Store and People". Gate: go test -p 4 ./internal/webtest -run 'TestAPIStore|TestAPIPeople|TestAPITeam': ok. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Summary
Task 2: the Store and People JSON reads, documented
5 files changed,
+362
−2
docs/api/base-native-v1.md+55 −1internal/web/api_team.go+81 −0internal/web/app.go+2 −0internal/webtest/api_team_test.go+216 −0internal/webtest/oficina_harness_test.go+8 −1
diff --git a/docs/api/base-native-v1.md b/docs/api/base-native-v1.md| index ddc1135..a9c822a 100644 |
| --- a/docs/api/base-native-v1.md |
| +++ b/docs/api/base-native-v1.md |
| @@ -2,7 +2,7 @@ |
| What Base's Mac and iPhone app may rely on. Everything here is pinned by |
| tests in `internal/webtest` (`native_test.go`, `api_test.go`, |
| -`ask_native_contract_test.go`, `ask_oficina_native_test.go`). The Ask |
| +`ask_native_contract_test.go`, `ask_oficina_native_test.go`, `api_team_test.go`). The Ask |
| routes are the same ones the web's `ask.js` uses, so a change that breaks |
| this document breaks the web too. |
| @@ -81,6 +81,60 @@ this document breaks the web too. |
| `currentColor`. Own pages' `url`s are Base's web pages. |
| - Optional keys are absent, never `null` or `""`. |
| +## Store and People |
| + |
| +What the Store and People pages show, from the same builders, behind the |
| +same member gate: any member's session, the native one or the web's |
| +cookie. Every answer is JSON and `no-store`. A refusal is |
| +`{"code": "…"}`. Without a session, or for someone who is no longer a |
| +member, every route answers `401 {"code":"unauthenticated"}`, as above. |
| +An app that hears `404` from a read is talking to an older Base, and opens |
| +the web page instead. |
| + |
| +### `GET /api/v1/store` |
| + |
| +```json |
| +{ |
| + "owner": true, |
| + "rows": [ |
| + {"id": "welcome", "name": "Welcome", "summary": "…", "tint": "amber", "icon_svg": "<svg …>", "state": "installed", "error": ""}, |
| + {"id": "scratchpad", "name": "Scratchpad", "summary": "…", "tint": "rose", "icon_svg": "<svg …>", "state": "installing", "error": ""}, |
| + {"id": "contra", "name": "Contra", "summary": "…", "tint": "teal", "icon_svg": "<svg …>", "state": "failed", "error": "The app did not start answering"} |
| + ] |
| +} |
| +``` |
| + |
| +- `rows` is the whole catalogue, in its order. `state` is `""` (not |
| + installed), `installing`, `installed` or `failed`. `error` is a failed |
| + install's reason, and may be `""` (show "The install didn't finish."). |
| +- `owner` is whether this member may install and uninstall. Every member |
| + sees the same rows. |
| +- `icon_svg` is line art drawn in `currentColor` on `tint`, as in |
| + `/api/v1/home`. |
| +- `503 {"code":"unavailable"}`: Base couldn't read its installs. |
| + |
| +### `GET /api/v1/people` |
| + |
| +```json |
| +{ |
| + "owner": true, |
| + "people": [ |
| + {"id": "…", "initial": "O", "name": "", "email": "owner@acme.test", "role": "owner"}, |
| + {"id": "…", "initial": "A", "name": "Ana Ruiz", "email": "ana@acme.test", "role": "member"}, |
| + {"id": "…", "initial": "B", "name": "", "email": "bob@acme.test", "role": "invited"} |
| + ] |
| +} |
| +``` |
| + |
| +- `people` is everyone here, in the order they were invited, as the page |
| + lists them. |
| +- `role` is `owner`, `member`, or `invited` (hasn't signed in yet). |
| +- `name` is `""` for someone who has given none: show `email` then. |
| + `initial` is the first letter of the name, or else of the address. |
| +- `owner` is whether this member may invite. |
| +- `503 {"code":"unavailable"}`: Base couldn't read its members. |
| +- Nothing removes a member: `DELETE /api/v1/people/{id}` isn't a route. |
| + |
| ## Ask Base |
| No Ask route answers `401` while Base's session is good: Equipo refusing |
diff --git a/internal/web/api_team.go b/internal/web/api_team.go| new file mode 100644 |
| index 0000000..e0ecb94 |
| --- /dev/null |
| +++ b/internal/web/api_team.go |
| @@ -0,0 +1,81 @@ |
| +package web |
| + |
| +import ( |
| + "net/http" |
| +) |
| + |
| +// Store and People for the native app (docs/api/base-native-v1.md "Store" |
| +// and "People"): what the pages of the same names show, from the same |
| +// builders, behind the same member gate and owner checks. |
| + |
| +type apiStoreRow struct { |
| + ID string `json:"id"` |
| + Name string `json:"name"` |
| + Summary string `json:"summary"` |
| + Tint string `json:"tint"` |
| + IconSVG string `json:"icon_svg"` |
| + // State is "", "installing", "installed" or "failed"; Error is a |
| + // failed install's reason, and may be "". |
| + State string `json:"state"` |
| + Error string `json:"error"` |
| +} |
| + |
| +type apiStore struct { |
| + Owner bool `json:"owner"` |
| + Rows []apiStoreRow `json:"rows"` |
| +} |
| + |
| +func storeJSON(c storeContent) apiStore { |
| + out := apiStore{Owner: c.IsOwner, Rows: []apiStoreRow{}} |
| + for _, r := range c.Rows { |
| + out.Rows = append(out.Rows, apiStoreRow{ID: r.ID, Name: r.Name, Summary: r.Summary, Tint: r.Tint, IconSVG: r.Icon, State: r.State, Error: r.Error}) |
| + } |
| + return out |
| +} |
| + |
| +type apiPerson struct { |
| + ID string `json:"id"` |
| + Initial string `json:"initial"` |
| + // Name is "" for someone who has given none; show Email then. |
| + Name string `json:"name"` |
| + Email string `json:"email"` |
| + // Role is "owner", "member" or "invited" (not yet signed in). |
| + Role string `json:"role"` |
| +} |
| + |
| +type apiPeople struct { |
| + Owner bool `json:"owner"` |
| + People []apiPerson `json:"people"` |
| +} |
| + |
| +func personJSON(p personRow) apiPerson { |
| + return apiPerson{ID: p.ID, Initial: p.Initial, Name: p.Name, Email: p.Email, Role: p.Role} |
| +} |
| + |
| +// apiStoreRead is GET /api/v1/store. |
| +func (a *app) apiStoreRead(w http.ResponseWriter, r *http.Request) { |
| + me, _ := CurrentMember(r) |
| + c, err := a.storeContent(r.Context(), me) |
| + if err != nil { |
| + a.logger.Error("api store", "err", err) |
| + writeJSON(w, http.StatusServiceUnavailable, apiError{Code: "unavailable"}) |
| + return |
| + } |
| + writeJSON(w, http.StatusOK, storeJSON(c)) |
| +} |
| + |
| +// apiPeopleRead is GET /api/v1/people. |
| +func (a *app) apiPeopleRead(w http.ResponseWriter, r *http.Request) { |
| + me, _ := CurrentMember(r) |
| + c, err := a.peopleContent(r.Context(), me) |
| + if err != nil { |
| + a.logger.Error("api people", "err", err) |
| + writeJSON(w, http.StatusServiceUnavailable, apiError{Code: "unavailable"}) |
| + return |
| + } |
| + out := apiPeople{Owner: c.IsOwner, People: []apiPerson{}} |
| + for _, p := range c.People { |
| + out.People = append(out.People, personJSON(p)) |
| + } |
| + writeJSON(w, http.StatusOK, out) |
| +} |
diff --git a/internal/web/app.go b/internal/web/app.go| index b37a994..505341c 100644 |
| --- a/internal/web/app.go |
| +++ b/internal/web/app.go |
| @@ -208,6 +208,8 @@ func App(d *db.DB, cfg config.Config, mailer mail.Sender, inst Installer, logger |
| r.Post("/settings/appearance", a.settingsAppearance) |
| r.Get("/api/v1/me", a.apiMeRead) |
| r.Get("/api/v1/home", a.apiHomeRead) |
| + r.Get("/api/v1/store", a.apiStoreRead) |
| + r.Get("/api/v1/people", a.apiPeopleRead) |
| r.With(ownSignInOnly).Post(registerBeginPath, a.pk.RegisterBegin) |
| r.With(ownSignInOnly).Post(registerFinishPath, a.pk.RegisterFinish) |
| r.Method(http.MethodGet, "/authorize", authorize) |
diff --git a/internal/webtest/api_team_test.go b/internal/webtest/api_team_test.go| new file mode 100644 |
| index 0000000..acc10bd |
| --- /dev/null |
| +++ b/internal/webtest/api_team_test.go |
| @@ -0,0 +1,216 @@ |
| +package webtest |
| + |
| +import ( |
| + "context" |
| + "encoding/json" |
| + "net/http" |
| + "reflect" |
| + "strings" |
| + "testing" |
| + |
| + "amadan.net/oficina/base/internal/catalog" |
| + "amadan.net/oficina/base/internal/store" |
| +) |
| + |
| +// Store and People for the native app (docs/api/base-native-v1.md "Store" |
| +// and "People"): the pages' own builders and owner checks, as JSON. |
| + |
| +type apiStoreRowShape struct { |
| + ID string `json:"id"` |
| + Name string `json:"name"` |
| + Summary string `json:"summary"` |
| + Tint string `json:"tint"` |
| + IconSVG string `json:"icon_svg"` |
| + State string `json:"state"` |
| + Error string `json:"error"` |
| +} |
| + |
| +type apiStoreShape struct { |
| + Owner bool `json:"owner"` |
| + Rows []apiStoreRowShape `json:"rows"` |
| +} |
| + |
| +type apiPersonShape struct { |
| + ID string `json:"id"` |
| + Initial string `json:"initial"` |
| + Name string `json:"name"` |
| + Email string `json:"email"` |
| + Role string `json:"role"` |
| +} |
| + |
| +type apiPeopleShape struct { |
| + Owner bool `json:"owner"` |
| + People []apiPersonShape `json:"people"` |
| +} |
| + |
| +// jsonAnswer checks an answer's status, that it is JSON and never cached, |
| +// and decodes it. |
| +func jsonAnswer[T any](t *testing.T, where string, r Resp, code int) T { |
| + t.Helper() |
| + if r.Code != code || r.Header.Get("Content-Type") != "application/json" || r.Header.Get("Cache-Control") != "no-store" { |
| + t.Fatalf("%s: %d %q %q, want %d JSON no-store: %s", where, r.Code, r.Header.Get("Content-Type"), r.Header.Get("Cache-Control"), code, r.Body) |
| + } |
| + return decode[T](t, r) |
| +} |
| + |
| +// refusedWith checks a JSON refusal's status and code. |
| +func refusedWith(t *testing.T, where string, r Resp, code int, want string) { |
| + t.Helper() |
| + got := jsonAnswer[map[string]any](t, where, r, code) |
| + if !reflect.DeepEqual(got, map[string]any{"code": want}) { |
| + t.Errorf("%s: %s, want {\"code\":%q}", where, r.Body, want) |
| + } |
| +} |
| + |
| +// maria is a member who isn't the owner, signed in on the native app. |
| +func (a *testApp) maria() *testApp { |
| + a.t.Helper() |
| + if _, _, err := store.Invite(context.Background(), a.DB, "maria@acme.test"); err != nil { |
| + a.t.Fatal(err) |
| + } |
| + a.newBrowser().link("maria@acme.test", "subject-maria") |
| + return a.nativeSignIn("subject-maria") |
| +} |
| + |
| +func TestAPIStore(t *testing.T) { |
| + a := newHomeApp(t) |
| + a.link(ownerAddress, "subject-owner") |
| + a.setInstall("welcome", "installed", "") |
| + a.setInstall("scratchpad", "installing", "") |
| + a.setInstall("contra", "failed", "The app did not start answering") |
| + app := a.nativeSignIn("subject-owner") |
| + |
| + r := app.nativeGet("/api/v1/store") |
| + var raw map[string]json.RawMessage |
| + if err := json.Unmarshal([]byte(r.Body), &raw); err != nil || len(raw) != 2 { |
| + t.Fatalf("store's keys: %v %s", err, r.Body) |
| + } |
| + s := jsonAnswer[apiStoreShape](t, "store", r, 200) |
| + if !s.Owner { |
| + t.Error("the owner reads as not the owner") |
| + } |
| + all := catalog.All() |
| + if len(s.Rows) != len(all) { |
| + t.Fatalf("%d rows for %d catalogue entries", len(s.Rows), len(all)) |
| + } |
| + for i, e := range all { |
| + row := s.Rows[i] |
| + if row.ID != e.ID || row.Name != e.Name || row.Summary != e.Summary || row.Tint != e.Tint || row.IconSVG != e.Icon || !strings.HasPrefix(row.IconSVG, "<svg") { |
| + t.Errorf("row %d: %+v, want the catalogue's %q in its order", i, row, e.ID) |
| + } |
| + } |
| + states := map[string]string{} |
| + for _, row := range s.Rows { |
| + states[row.ID] = row.State + "|" + row.Error |
| + } |
| + if want := map[string]string{"welcome": "installed|", "scratchpad": "installing|", "contra": "failed|The app did not start answering"}; !reflect.DeepEqual(states, want) { |
| + t.Errorf("states: %v, want %v", states, want) |
| + } |
| + |
| + // A member who isn't the owner sees the same rows. |
| + m := jsonAnswer[apiStoreShape](t, "member's store", a.maria().nativeGet("/api/v1/store"), 200) |
| + if m.Owner || !reflect.DeepEqual(m.Rows, s.Rows) { |
| + t.Errorf("member's store: owner %v, rows differ: %v", m.Owner, !reflect.DeepEqual(m.Rows, s.Rows)) |
| + } |
| + |
| + // The installs unreadable. |
| + if _, err := a.DB.Exec(`DROP TABLE installs`); err != nil { |
| + t.Fatal(err) |
| + } |
| + refusedWith(t, "installs unreadable", app.nativeGet("/api/v1/store"), http.StatusServiceUnavailable, "unavailable") |
| +} |
| + |
| +func TestAPIPeople(t *testing.T) { |
| + a := newHomeApp(t) |
| + a.link(ownerAddress, "subject-owner") |
| + ana, _, err := store.Invite(t.Context(), a.DB, "ana@acme.test") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := a.DB.Exec(`UPDATE members SET name = 'Ana Ruiz' WHERE id = ?`, ana.ID); err != nil { |
| + t.Fatal(err) |
| + } |
| + a.newBrowser().link("ana@acme.test", "subject-ana") |
| + invited, _, err := store.Invite(t.Context(), a.DB, "bob@acme.test") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + |
| + r := a.nativeSignIn("subject-owner").nativeGet("/api/v1/people") |
| + var raw map[string]json.RawMessage |
| + if err := json.Unmarshal([]byte(r.Body), &raw); err != nil || len(raw) != 2 { |
| + t.Fatalf("people's keys: %v %s", err, r.Body) |
| + } |
| + p := jsonAnswer[apiPeopleShape](t, "people", r, 200) |
| + want := apiPeopleShape{Owner: true, People: []apiPersonShape{ |
| + {ID: a.ownerID(), Initial: "O", Name: "", Email: ownerAddress, Role: "owner"}, |
| + {ID: ana.ID, Initial: "A", Name: "Ana Ruiz", Email: "ana@acme.test", Role: "member"}, |
| + {ID: invited.ID, Initial: "B", Name: "", Email: "bob@acme.test", Role: "invited"}, |
| + }} |
| + if !reflect.DeepEqual(p, want) { |
| + t.Fatalf("people:\n got %+v\nwant %+v", p, want) |
| + } |
| + // Each row has exactly these keys: no joined. |
| + var rows struct { |
| + People []map[string]any `json:"people"` |
| + } |
| + _ = json.Unmarshal([]byte(r.Body), &rows) |
| + if len(rows.People[0]) != 5 { |
| + t.Errorf("a person's keys: %v", rows.People[0]) |
| + } |
| + |
| + // Ana, a member, and the owner's own browser session on the web, get |
| + // the same people. |
| + if got := jsonAnswer[apiPeopleShape](t, "ana's people", a.nativeSignIn("subject-ana").nativeGet("/api/v1/people"), 200); got.Owner || !reflect.DeepEqual(got.People, want.People) { |
| + t.Errorf("ana's people: %+v", got) |
| + } |
| + if got := jsonAnswer[apiPeopleShape](t, "web session's people", a.get("/api/v1/people"), 200); !reflect.DeepEqual(got, want) { |
| + t.Errorf("web session's people: %+v", got) |
| + } |
| +} |
| + |
| +func TestAPITeamRefusesWithoutSession(t *testing.T) { |
| + a := newHomeApp(t) |
| + a.link(ownerAddress, "subject-owner") |
| + maria := a.maria() |
| + none := a.newBrowser() |
| + for _, p := range []string{"/api/v1/store", "/api/v1/people"} { |
| + r := none.nativeGet(p) |
| + refusedWith(t, "no session, "+p, r, http.StatusUnauthorized, "unauthenticated") |
| + if r.Location() != "" { |
| + t.Errorf("no session, %s: redirected to %q", p, r.Location()) |
| + } |
| + } |
| + |
| + // Maria, removed, is nobody. |
| + m, _, err := store.MemberByEmail(t.Context(), a.DB, "maria@acme.test") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if err := store.RemoveMember(t.Context(), a.DB, m.ID); err != nil { |
| + t.Fatal(err) |
| + } |
| + for _, p := range []string{"/api/v1/store", "/api/v1/people"} { |
| + refusedWith(t, "removed, "+p, maria.nativeGet(p), http.StatusUnauthorized, "unauthenticated") |
| + } |
| +} |
| + |
| +// Nothing removes a member (spec 7.4): there is no route to. |
| +func TestAPIPeopleHasNoRemove(t *testing.T) { |
| + a := newHomeApp(t) |
| + a.link(ownerAddress, "subject-owner") |
| + ana, _, err := store.Invite(t.Context(), a.DB, "ana@acme.test") |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + app := a.nativeSignIn("subject-owner") |
| + req, _ := http.NewRequest(http.MethodDelete, a.base+"/api/v1/people/"+ana.ID, nil) |
| + req.Header.Set("Origin", homeOrigin) |
| + req.Header.Set("Accept", "application/json") |
| + if r := app.do(req); r.Code != http.StatusNotFound && r.Code != http.StatusMethodNotAllowed { |
| + t.Errorf("DELETE /api/v1/people/<id>: %d %s", r.Code, r.Body) |
| + } |
| + if _, ok, err := store.MemberByEmail(t.Context(), a.DB, "ana@acme.test"); err != nil || !ok { |
| + t.Errorf("ana is gone: %v %v", ok, err) |
| + } |
| +} |
diff --git a/internal/webtest/oficina_harness_test.go b/internal/webtest/oficina_harness_test.go| index 32daf42..2cba342 100644 |
| --- a/internal/webtest/oficina_harness_test.go |
| +++ b/internal/webtest/oficina_harness_test.go |
| @@ -57,6 +57,13 @@ func newHomeApp(t *testing.T) *testApp { return newHomeAppWith(t, nil) } |
| // newHomeAppWith is newHomeApp with a last say over the configuration. |
| func newHomeAppWith(t *testing.T, tweak func(*config.Config)) *testApp { |
| + t.Helper() |
| + return newHomeAppInstalling(t, noInstaller{}, tweak) |
| +} |
| + |
| +// newHomeAppInstalling is newHomeAppWith with the Installer of the |
| +// caller's choice. |
| +func newHomeAppInstalling(t *testing.T, inst web.Installer, tweak func(*config.Config)) *testApp { |
| t.Helper() |
| logger := slog.New(slog.NewTextHandler(io.Discard, nil)) |
| d, err := db.Open(homeSchema.Path(t), logger) |
| @@ -90,7 +97,7 @@ func newHomeAppWith(t *testing.T, tweak func(*config.Config)) *testApp { |
| tweak(&cfg) |
| } |
| mailer := &capturingMailer{} |
| - h, err := web.App(d, cfg, mailer, noInstaller{}, logger) |
| + h, err := web.App(d, cfg, mailer, inst, logger) |
| if err != nil { |
| t.Fatalf("web.App: %v", err) |
| } |