Phase 13, part 1: a Postgres schema per team
On the multi-tenant edition each team's data is in its own schema; the tables every team shares (people, sessions, memberships, keys, locks, and a new teams table) stay in the main one. A team's connection pool searches its own schema first, so the app's SQL runs unchanged and can't reach another team's tables. Each request is served by a copy of the Server for the viewer's team, with that team's database, secrets and caches; agents work on their own team's. The local and server editions are unchanged. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -54,6 +54,9 @@ merged** (2026-11-25): a new `compose.server.yaml` and `install-server.sh`.
|
||||
tools over MCP, approvals, limits and visibility, and the JSON API. Schema
|
||||
39.
|
||||
|
||||
**Phase 13 (multi-tenant) is under way** on branch `phase13`, with a
|
||||
Postgres schema per team (decided 2026-11-26); part 1 is built.
|
||||
|
||||
**Phase 12 (signing in with the Core, OIDC) is set aside for now**
|
||||
(2026-11-26): before it starts, the user will share the Federated Core's
|
||||
`idproviders.yml`, which shows how the Core sets up Authelia and its
|
||||
@@ -2769,6 +2772,44 @@ Core's admin tooling does it.
|
||||
Many teams sign in at one address, each working on its own domains. This
|
||||
builds on Phases 9–12. A commit after each part.
|
||||
|
||||
**Decided 2026-11-26: a Postgres schema per team**, instead of the
|
||||
`team_id` column on every table and row-level security that parts 1 and 2
|
||||
describe below. Those would have meant changing about 611 queries in 88
|
||||
files and every unique key. With a schema per team, the app's SQL runs
|
||||
unchanged: a team's connection pool has the team's schema first on its
|
||||
search_path, then the main schema, so its queries find the team's tables
|
||||
and can't reach another team's without naming them. Parts 1 and 2 below
|
||||
are built that way; their aims (every query scoped, and a second guard)
|
||||
stand.
|
||||
|
||||
**Part 1 built 2026-11-26** on branch `phase13`.
|
||||
- Schema 40 (the platform's): `teams` (name, its one website domain,
|
||||
active, suspended or deleting) and `sessions.team_id`, the team a session
|
||||
works in.
|
||||
- The shared tables (`db.PlatformTables`: people, memberships, sessions,
|
||||
links, throttle, agent keys, instances, locks, teams) are in the main
|
||||
schema; every other table is a team's. Migrations say which they are
|
||||
(`Platform: true` for the shared ones; a migration is one or the other).
|
||||
- `db.Teams`: `Create` makes `team_<id>` and migrates it with the team's
|
||||
migrations only; `Open` keeps one small pool per team (4 connections,
|
||||
idle ones closed after a minute), migrating it forward the first time;
|
||||
`Drop` removes the schema. Tests on Postgres name teams' schemas after
|
||||
their own and drop them with it.
|
||||
- The web server: each route is registered as a method expression and run
|
||||
on the Server for the request's team (`forTeam`): a copy with the team's
|
||||
database, secrets (the `secrets` table is a team's, so each team's keys
|
||||
are its own) and caches (Reddit's and Google's tokens are per team now).
|
||||
What every copy shares (templates, the jobs runner, the copies
|
||||
themselves) moved into a shared `state`. MCP: an agent's key finds its
|
||||
team, and its tools, `profile_get` and the Market's included, work on
|
||||
that team's database.
|
||||
- The local and server editions are unchanged: one team, team 1, is the
|
||||
whole database. The multi-tenant edition still doesn't start: signing up
|
||||
and choosing a team come in part 3.
|
||||
- Checked on Postgres: two teams, each with a profile, a Market entry and a
|
||||
key, see only their own, through the pages, Search, MCP and secrets; the
|
||||
main schema holds none of it.
|
||||
|
||||
1. **Teams everywhere.**
|
||||
- Every table that holds a company's data gets `team_id`, and its
|
||||
unique keys include it. The settings table's key becomes
|
||||
|
||||
@@ -35,12 +35,17 @@ type DB struct {
|
||||
SQL *sql.DB
|
||||
Dialect Dialect
|
||||
|
||||
// Team is the team whose schema this is (Teams.Open); 0 for the main
|
||||
// database.
|
||||
Team int64
|
||||
|
||||
// MigratedFrom is the schema version the database was at when opened,
|
||||
// if Open migrated it (0 if it was new or already current), for the
|
||||
// log.
|
||||
MigratedFrom int
|
||||
|
||||
closeHook func() error // tests on Postgres: drop the test's schema
|
||||
url string // Postgres: where it was opened, for teams' schemas
|
||||
}
|
||||
|
||||
func (d *DB) query(q string) string {
|
||||
|
||||
@@ -17,8 +17,18 @@ type Migration struct {
|
||||
Note string // what it does, for the record (Postgres' schema_migrations)
|
||||
SQLite string
|
||||
Postgres string // empty: PostgresSQL(SQLite)
|
||||
// Platform marks a migration that only touches the tables every team
|
||||
// shares (people, sessions, keys, locks): on the multi-tenant edition
|
||||
// it runs in the main schema, never in a team's (see Teams). A
|
||||
// migration is one or the other, never both.
|
||||
Platform bool
|
||||
}
|
||||
|
||||
// PlatformTables are the tables every team shares on the multi-tenant
|
||||
// edition, in the main schema; every other table is a team's, in its own
|
||||
// schema.
|
||||
var PlatformTables = []string{"instances", "locks", "users", "memberships", "sessions", "links", "throttle", "agent_keys", "teams"}
|
||||
|
||||
// both are the migrations after schema 29, on both databases: schema 30
|
||||
// is both[0]. (migrations, before them, are SQLite's own; Postgres starts
|
||||
// from postgres.sql, which is schema 29 as a whole.)
|
||||
@@ -37,7 +47,8 @@ CREATE TABLE secrets (
|
||||
},
|
||||
// 31
|
||||
{
|
||||
Note: "copies of the app, and the locks that let only one of them do a job",
|
||||
Note: "copies of the app, and the locks that let only one of them do a job",
|
||||
Platform: true,
|
||||
SQLite: `
|
||||
CREATE TABLE instances (
|
||||
id TEXT PRIMARY KEY, -- a copy of the app, while it runs
|
||||
@@ -56,7 +67,8 @@ CREATE TABLE locks (
|
||||
},
|
||||
// 32
|
||||
{
|
||||
Note: "users, their memberships of the team, and their sign-in sessions (server and multi-tenant editions)",
|
||||
Note: "users, their memberships of the team, and their sign-in sessions (server and multi-tenant editions)",
|
||||
Platform: true,
|
||||
SQLite: `
|
||||
CREATE TABLE users (
|
||||
id INTEGER PRIMARY KEY,
|
||||
@@ -94,7 +106,8 @@ CREATE INDEX sessions_user ON sessions(user_id);
|
||||
},
|
||||
// 33
|
||||
{
|
||||
Note: "one-time links: setting up the first owner, password resets, invitations",
|
||||
Note: "one-time links: setting up the first owner, password resets, invitations",
|
||||
Platform: true,
|
||||
SQLite: `
|
||||
CREATE TABLE links (
|
||||
id TEXT PRIMARY KEY, -- the SHA-256 of the link's random token
|
||||
@@ -108,7 +121,8 @@ CREATE INDEX links_user ON links(user_id, purpose);
|
||||
},
|
||||
// 34
|
||||
{
|
||||
Note: "signing in: failed attempts and locks, two-factor sign-in, and limits on tries",
|
||||
Note: "signing in: failed attempts and locks, two-factor sign-in, and limits on tries",
|
||||
Platform: true,
|
||||
SQLite: `
|
||||
ALTER TABLE users ADD COLUMN failed_signins INTEGER NOT NULL DEFAULT 0; -- in a row, since the last sign-in
|
||||
ALTER TABLE users ADD COLUMN locked_at TEXT NOT NULL DEFAULT ''; -- locked after too many; '' when not
|
||||
@@ -169,7 +183,8 @@ ALTER TABLE outreach ADD COLUMN created_by INTEGER NOT NULL DEFAULT 0;
|
||||
},
|
||||
// 37
|
||||
{
|
||||
Note: "agents' keys, and a description for each agent",
|
||||
Note: "agents' keys, and a description for each agent",
|
||||
Platform: true,
|
||||
SQLite: `
|
||||
CREATE TABLE agent_keys (
|
||||
id INTEGER PRIMARY KEY,
|
||||
@@ -240,6 +255,22 @@ CREATE TABLE agent_calls (
|
||||
ms INTEGER NOT NULL DEFAULT 0
|
||||
);
|
||||
CREATE INDEX agent_calls_agent ON agent_calls(agent_id, at);
|
||||
`,
|
||||
},
|
||||
// 40
|
||||
{
|
||||
Note: "teams, and which team each sign-in session works in (multi-tenant edition)",
|
||||
Platform: true,
|
||||
SQLite: `
|
||||
CREATE TABLE teams (
|
||||
id INTEGER PRIMARY KEY,
|
||||
name TEXT NOT NULL,
|
||||
domain TEXT NOT NULL DEFAULT '', -- the one website domain it works on, such as example.com
|
||||
status TEXT NOT NULL DEFAULT 'active', -- active, suspended or deleting
|
||||
created_at TEXT NOT NULL,
|
||||
delete_at TEXT NOT NULL DEFAULT '' -- deleting: when its data goes for good
|
||||
);
|
||||
ALTER TABLE sessions ADD COLUMN team_id INTEGER NOT NULL DEFAULT 1;
|
||||
`,
|
||||
},
|
||||
}
|
||||
|
||||
+34
-7
@@ -37,7 +37,7 @@ func OpenPostgres(url string) (*DB, error) {
|
||||
sqldb.Close()
|
||||
return nil, fmt.Errorf("opening Postgres: %w", err)
|
||||
}
|
||||
d := &DB{SQL: sqldb, Dialect: Postgres}
|
||||
d := &DB{SQL: sqldb, Dialect: Postgres, url: url}
|
||||
if err := d.migratePostgres(); err != nil {
|
||||
sqldb.Close()
|
||||
return nil, err
|
||||
@@ -53,7 +53,12 @@ var AppVersion = "dev"
|
||||
// transaction: a failure leaves the database as it was. One copy of the
|
||||
// app at a time does it (an advisory lock), so several can start
|
||||
// together. Each step is recorded in schema_migrations.
|
||||
func (d *DB) migratePostgres() error {
|
||||
func (d *DB) migratePostgres() error { return d.migrateSchema(false) }
|
||||
|
||||
// migrateSchema migrates the schema the connection's search_path names
|
||||
// first: the main one, or (team) a team's, which skips the platform's
|
||||
// migrations and never has the platform's tables.
|
||||
func (d *DB) migrateSchema(team bool) error {
|
||||
if err := checkMigrations(); err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -62,7 +67,7 @@ func (d *DB) migratePostgres() error {
|
||||
return err
|
||||
}
|
||||
defer tx.Rollback()
|
||||
if _, err := tx.Exec(`SELECT pg_advisory_xact_lock(4708421)`); err != nil { // any fixed number: "the schema"
|
||||
if _, err := tx.Exec(`SELECT pg_advisory_xact_lock(4708421, hashtext(current_schema()))`); err != nil { // any fixed number: "the schema", then which
|
||||
return err
|
||||
}
|
||||
if _, err := tx.Exec(`CREATE TABLE IF NOT EXISTS schema_migrations (
|
||||
@@ -77,8 +82,10 @@ func (d *DB) migratePostgres() error {
|
||||
_, err := tx.Exec(`INSERT INTO schema_migrations (version, note, app) VALUES ($1, $2, $3)`, version, note, AppVersion)
|
||||
return err
|
||||
}
|
||||
// In this schema itself: a team's search_path falls back to the main
|
||||
// schema, which has its own.
|
||||
var exists bool
|
||||
if err := tx.QueryRow(`SELECT to_regclass('schema_version') IS NOT NULL`).Scan(&exists); err != nil {
|
||||
if err := tx.QueryRow(`SELECT to_regclass(quote_ident(current_schema()) || '.schema_version') IS NOT NULL`).Scan(&exists); err != nil {
|
||||
return err
|
||||
}
|
||||
version := pgBaseline
|
||||
@@ -109,8 +116,13 @@ func (d *DB) migratePostgres() error {
|
||||
}
|
||||
for i := version; i < Schema(); i++ {
|
||||
m, q := postgresStep(i)
|
||||
if _, err := tx.Exec(q); err != nil {
|
||||
return fmt.Errorf("migration %d (%s): %w", i+1, m.Note, err)
|
||||
if team && m.Platform {
|
||||
q = "" // the platform's tables aren't in a team's schema
|
||||
}
|
||||
if q != "" {
|
||||
if _, err := tx.Exec(q); err != nil {
|
||||
return fmt.Errorf("migration %d (%s): %w", i+1, m.Note, err)
|
||||
}
|
||||
}
|
||||
if _, err := tx.Exec(`UPDATE schema_version SET version = $1`, i+1); err != nil {
|
||||
return err
|
||||
@@ -174,7 +186,22 @@ func openTestSchema(base string) (*DB, error) {
|
||||
d.SQL.SetMaxOpenConns(4)
|
||||
d.closeHook = func() error {
|
||||
defer admin.Close()
|
||||
_, err := admin.Exec(`DROP SCHEMA ` + schema + ` CASCADE`)
|
||||
// Its teams' schemas too (Teams names them after it).
|
||||
rows, err := admin.Query(`SELECT nspname FROM pg_namespace WHERE nspname LIKE $1`, schema+`\_team\_%`)
|
||||
if err == nil {
|
||||
var teams []string
|
||||
for rows.Next() {
|
||||
var n string
|
||||
if rows.Scan(&n) == nil {
|
||||
teams = append(teams, n)
|
||||
}
|
||||
}
|
||||
rows.Close()
|
||||
for _, n := range teams {
|
||||
admin.Exec(`DROP SCHEMA ` + n + ` CASCADE`)
|
||||
}
|
||||
}
|
||||
_, err = admin.Exec(`DROP SCHEMA ` + schema + ` CASCADE`)
|
||||
return err
|
||||
}
|
||||
return d, nil
|
||||
|
||||
@@ -0,0 +1,135 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Teams keeps each team's data in a Postgres schema of its own (the
|
||||
// multi-tenant edition). The main schema has what every team shares (see
|
||||
// PlatformTables); a team's schema has the rest, made by the same
|
||||
// migrations. A team's DB is a connection pool whose search_path is its
|
||||
// schema, then the main one: the app's SQL runs unchanged, finds the
|
||||
// team's tables, and the shared ones behind them, and can't reach another
|
||||
// team's tables without naming them.
|
||||
type Teams struct {
|
||||
platform *DB
|
||||
base string // the main database's address
|
||||
main string // the main schema
|
||||
prefix string // teams' schemas are <prefix><id>
|
||||
|
||||
mu sync.Mutex
|
||||
open map[int64]*DB
|
||||
}
|
||||
|
||||
// Teams opens the teams of a Postgres database.
|
||||
func (d *DB) Teams() (*Teams, error) {
|
||||
if d.Dialect != Postgres || d.url == "" {
|
||||
return nil, errors.New("teams need Postgres")
|
||||
}
|
||||
var main string
|
||||
if err := d.SQL.QueryRow(`SELECT current_schema()`).Scan(&main); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
prefix := "team_"
|
||||
if main != "public" {
|
||||
prefix = main + "_team_" // tests: each in its own schema, its teams named after it
|
||||
}
|
||||
return &Teams{platform: d, base: d.url, main: main, prefix: prefix, open: map[int64]*DB{}}, nil
|
||||
}
|
||||
|
||||
// Schema is a team's schema's name.
|
||||
func (t *Teams) Schema(id int64) string { return t.prefix + strconv.FormatInt(id, 10) }
|
||||
|
||||
// connect opens a pool with a search_path.
|
||||
func (t *Teams) connect(path string) (*sql.DB, error) {
|
||||
u, err := url.Parse(t.base)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
q := u.Query()
|
||||
q.Set("search_path", path)
|
||||
u.RawQuery = q.Encode()
|
||||
return sql.Open("pgx", u.String())
|
||||
}
|
||||
|
||||
// Create makes a team's schema, with its tables at the current schema
|
||||
// version. Making one that exists only migrates it.
|
||||
func (t *Teams) Create(id int64) error {
|
||||
if id <= 0 {
|
||||
return errors.New("no team")
|
||||
}
|
||||
schema := t.Schema(id)
|
||||
if _, err := t.platform.SQL.Exec(`CREATE SCHEMA IF NOT EXISTS ` + schema); err != nil {
|
||||
return err
|
||||
}
|
||||
// Only the team's schema on the path while its tables are made, so
|
||||
// nothing is mistaken for the main schema's.
|
||||
sqldb, err := t.connect(schema)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer sqldb.Close()
|
||||
d := &DB{SQL: sqldb, Dialect: Postgres}
|
||||
return d.migrateSchema(true)
|
||||
}
|
||||
|
||||
// Open is a team's database: one pool per team, kept while the app runs.
|
||||
// It migrates the team's schema to this version the first time.
|
||||
func (t *Teams) Open(id int64) (*DB, error) {
|
||||
t.mu.Lock()
|
||||
defer t.mu.Unlock()
|
||||
if d, ok := t.open[id]; ok {
|
||||
return d, nil
|
||||
}
|
||||
var exists bool
|
||||
if err := t.platform.SQL.QueryRow(`SELECT to_regclass($1) IS NOT NULL`, t.Schema(id)+".schema_version").Scan(&exists); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if !exists {
|
||||
return nil, fmt.Errorf("team %d has no data yet", id)
|
||||
}
|
||||
sqldb, err := t.connect(t.Schema(id) + "," + t.main)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// Small: many teams share the server's connections. An idle team holds
|
||||
// none for long.
|
||||
sqldb.SetMaxOpenConns(4)
|
||||
sqldb.SetMaxIdleConns(1)
|
||||
sqldb.SetConnMaxIdleTime(time.Minute)
|
||||
d := &DB{SQL: sqldb, Dialect: Postgres, Team: id}
|
||||
if err := d.migrateSchema(true); err != nil {
|
||||
sqldb.Close()
|
||||
return nil, fmt.Errorf("team %d: %w", id, err)
|
||||
}
|
||||
t.open[id] = d
|
||||
return d, nil
|
||||
}
|
||||
|
||||
// Drop deletes a team's schema and everything in it.
|
||||
func (t *Teams) Drop(id int64) error {
|
||||
t.mu.Lock()
|
||||
if d, ok := t.open[id]; ok {
|
||||
d.SQL.Close()
|
||||
delete(t.open, id)
|
||||
}
|
||||
t.mu.Unlock()
|
||||
_, err := t.platform.SQL.Exec(`DROP SCHEMA IF EXISTS ` + t.Schema(id) + ` CASCADE`)
|
||||
return err
|
||||
}
|
||||
|
||||
// Close closes every team's pool.
|
||||
func (t *Teams) Close() {
|
||||
t.mu.Lock()
|
||||
defer t.mu.Unlock()
|
||||
for id, d := range t.open {
|
||||
d.SQL.Close()
|
||||
delete(t.open, id)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"path/filepath"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestTeamsSchemas(t *testing.T) {
|
||||
if !OnPostgres() {
|
||||
t.Skip("teams are Postgres's")
|
||||
}
|
||||
d, err := Open(filepath.Join(t.TempDir(), "app.db"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer d.Close()
|
||||
teams, err := d.Teams()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer teams.Close()
|
||||
if _, err := teams.Open(1); err == nil {
|
||||
t.Error("opened a team that wasn't created")
|
||||
}
|
||||
for _, id := range []int64{1, 2} {
|
||||
if err := teams.Create(id); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
a, err := teams.Open(1)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
b, _ := teams.Open(2)
|
||||
if a2, _ := teams.Open(1); a2 != a {
|
||||
t.Error("a second pool")
|
||||
}
|
||||
if v, err := a.SchemaVersion(); err != nil || v != Schema() {
|
||||
t.Errorf("team schema at %d: %v", v, err)
|
||||
}
|
||||
// Each team's own tables.
|
||||
if err := a.PutJSON("company", "Acme"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := b.PutJSON("company", "Bolt"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var got string
|
||||
a.GetJSON("company", &got)
|
||||
if got != "Acme" {
|
||||
t.Errorf("team 1 sees %q", got)
|
||||
}
|
||||
b.GetJSON("company", &got)
|
||||
if got != "Bolt" {
|
||||
t.Errorf("team 2 sees %q", got)
|
||||
}
|
||||
var n int
|
||||
d.QueryRow(`SELECT count(*) FROM settings WHERE key = 'company'`).Scan(&n)
|
||||
if n != 0 {
|
||||
t.Error("a team's setting in the main schema")
|
||||
}
|
||||
// The shared tables: only in the main schema, reached from a team's.
|
||||
for _, tbl := range PlatformTables {
|
||||
var inTeam bool
|
||||
d.QueryRow(`SELECT to_regclass($1) IS NOT NULL`, teams.Schema(1)+"."+tbl).Scan(&inTeam)
|
||||
if inTeam {
|
||||
t.Errorf("%s is in the team's schema", tbl)
|
||||
}
|
||||
}
|
||||
if _, err := d.Exec(`INSERT INTO teams (name, created_at) VALUES ('Acme', 'now')`); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := a.QueryRow(`SELECT count(*) FROM teams`).Scan(&n); err != nil || n != 1 {
|
||||
t.Errorf("the shared teams table from a team: %d %v", n, err)
|
||||
}
|
||||
// Creating again only migrates; dropping removes it all.
|
||||
if err := teams.Create(1); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := teams.Drop(2); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := teams.Open(2); err == nil {
|
||||
t.Error("a dropped team opens")
|
||||
}
|
||||
}
|
||||
@@ -29,6 +29,10 @@ import (
|
||||
type Caller struct {
|
||||
ID int64
|
||||
Name string
|
||||
// Team is the agent's team, and DB its database (multi-tenant); nil:
|
||||
// the one the Handler was given.
|
||||
Team int64
|
||||
DB *db.DB
|
||||
// Can says whether the agent may read (act false) or change things in
|
||||
// a module or scope (market, crm, …).
|
||||
Can func(scope string, act bool) bool
|
||||
@@ -66,7 +70,7 @@ func Handler(d *db.DB, version string, auth Authenticator, more func(*mcp.Server
|
||||
c, _ := r.Context().Value(callerKey{}).(*Caller)
|
||||
sig := signature(c)
|
||||
if c != nil {
|
||||
sig = fmt.Sprintf("%d/%s", c.ID, sig)
|
||||
sig = fmt.Sprintf("%d/%p/%s", c.ID, c.DB, sig)
|
||||
}
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
@@ -74,7 +78,11 @@ func Handler(d *db.DB, version string, auth Authenticator, more func(*mcp.Server
|
||||
return srv
|
||||
}
|
||||
srv := mcp.NewServer(&mcp.Implementation{Name: "supermarket", Version: version}, nil)
|
||||
addTools(srv, d, c)
|
||||
td := d
|
||||
if c != nil && c.DB != nil {
|
||||
td = c.DB
|
||||
}
|
||||
addTools(srv, td, c)
|
||||
if more != nil {
|
||||
more(srv, c)
|
||||
}
|
||||
|
||||
@@ -32,6 +32,7 @@ type Session struct {
|
||||
Expires time.Time
|
||||
IP string
|
||||
UserAgent string
|
||||
Team int64 // the team it works in (multi-tenant: switchable)
|
||||
}
|
||||
|
||||
// ErrNoSession is a cookie that leads nowhere: unknown, ended or expired,
|
||||
@@ -54,6 +55,11 @@ func NewToken() (string, error) {
|
||||
|
||||
// StartSession signs a user in: it returns the token for the cookie.
|
||||
func StartSession(d *db.DB, user int64, ip, userAgent string, now time.Time) (string, *Session, error) {
|
||||
return StartSessionIn(d, user, Team, ip, userAgent, now)
|
||||
}
|
||||
|
||||
// StartSessionIn signs a user in to work in a team.
|
||||
func StartSessionIn(d *db.DB, user, team int64, ip, userAgent string, now time.Time) (string, *Session, error) {
|
||||
token, err := NewToken()
|
||||
if err != nil {
|
||||
return "", nil, err
|
||||
@@ -61,9 +67,9 @@ func StartSession(d *db.DB, user int64, ip, userAgent string, now time.Time) (st
|
||||
if len(userAgent) > 300 {
|
||||
userAgent = userAgent[:300]
|
||||
}
|
||||
s := &Session{ID: hashToken(token), User: user, Created: now, Seen: now, Expires: expiry(now, now), IP: ip, UserAgent: userAgent}
|
||||
_, err = d.Exec(`INSERT INTO sessions (id, user_id, created_at, seen_at, expires_at, ip, user_agent) VALUES (?, ?, ?, ?, ?, ?, ?)`,
|
||||
s.ID, s.User, ts(s.Created), ts(s.Seen), ts(s.Expires), s.IP, s.UserAgent)
|
||||
s := &Session{ID: hashToken(token), User: user, Created: now, Seen: now, Expires: expiry(now, now), IP: ip, UserAgent: userAgent, Team: team}
|
||||
_, err = d.Exec(`INSERT INTO sessions (id, user_id, created_at, seen_at, expires_at, ip, user_agent, team_id) VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
|
||||
s.ID, s.User, ts(s.Created), ts(s.Seen), ts(s.Expires), s.IP, s.UserAgent, s.Team)
|
||||
if err != nil {
|
||||
return "", nil, err
|
||||
}
|
||||
@@ -79,12 +85,12 @@ func expiry(created, seen time.Time) time.Time {
|
||||
return max
|
||||
}
|
||||
|
||||
const sessionCols = `id, user_id, created_at, seen_at, expires_at, ip, user_agent`
|
||||
const sessionCols = `id, user_id, created_at, seen_at, expires_at, ip, user_agent, team_id`
|
||||
|
||||
func scanSession(row interface{ Scan(...any) error }) (*Session, error) {
|
||||
var s Session
|
||||
var created, seen, expires string
|
||||
if err := row.Scan(&s.ID, &s.User, &created, &seen, &expires, &s.IP, &s.UserAgent); err != nil {
|
||||
if err := row.Scan(&s.ID, &s.User, &created, &seen, &expires, &s.IP, &s.UserAgent, &s.Team); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
s.Created, s.Seen, s.Expires = parseTS(created), parseTS(seen), parseTS(expires)
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
package users
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"errors"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"supermarket/internal/db"
|
||||
)
|
||||
|
||||
// Teams (the multi-tenant edition): each is a company, working on one
|
||||
// website domain, with its data in its own schema (db.Teams). On the local
|
||||
// and server editions there's one, Team, and no row for it.
|
||||
|
||||
// Team statuses.
|
||||
const (
|
||||
TeamActive = "active"
|
||||
TeamSuspended = "suspended"
|
||||
TeamDeleting = "deleting"
|
||||
)
|
||||
|
||||
// TeamInfo is a team.
|
||||
type TeamInfo struct {
|
||||
ID int64
|
||||
Name string
|
||||
Domain string
|
||||
Status string
|
||||
Created time.Time
|
||||
DeleteAt time.Time
|
||||
}
|
||||
|
||||
const teamCols = `id, name, domain, status, created_at, delete_at`
|
||||
|
||||
func scanTeam(row interface{ Scan(...any) error }) (*TeamInfo, error) {
|
||||
var t TeamInfo
|
||||
var created, del string
|
||||
if err := row.Scan(&t.ID, &t.Name, &t.Domain, &t.Status, &created, &del); err != nil {
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return nil, ErrNotFound
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
t.Created, t.DeleteAt = parseTS(created), parseTS(del)
|
||||
return &t, nil
|
||||
}
|
||||
|
||||
// CreateTeam adds a team (its schema is the caller's to make).
|
||||
func CreateTeam(d *db.DB, name, domain string, now time.Time) (*TeamInfo, error) {
|
||||
name = strings.TrimSpace(name)
|
||||
if name == "" {
|
||||
return nil, errors.New("give the company's name")
|
||||
}
|
||||
t := &TeamInfo{Name: name, Domain: strings.ToLower(strings.TrimSpace(domain)), Status: TeamActive, Created: now}
|
||||
var err error
|
||||
t.ID, err = d.Insert(`INSERT INTO teams (name, domain, status, created_at) VALUES (?, ?, ?, ?)`, t.Name, t.Domain, t.Status, ts(now))
|
||||
return t, err
|
||||
}
|
||||
|
||||
// GetTeam finds a team.
|
||||
func GetTeam(d *db.DB, id int64) (*TeamInfo, error) {
|
||||
return scanTeam(d.QueryRow(`SELECT `+teamCols+` FROM teams WHERE id = ?`, id))
|
||||
}
|
||||
|
||||
// ListTeams is every team, newest first.
|
||||
func ListTeams(d *db.DB) ([]TeamInfo, error) {
|
||||
return queryTeams(d, `SELECT `+teamCols+` FROM teams ORDER BY id DESC`)
|
||||
}
|
||||
|
||||
// TeamsOf are the teams a user belongs to, by name.
|
||||
func TeamsOf(d *db.DB, user int64) ([]TeamInfo, error) {
|
||||
return queryTeams(d, `SELECT t.id, t.name, t.domain, t.status, t.created_at, t.delete_at FROM teams t
|
||||
JOIN memberships m ON m.team_id = t.id WHERE m.user_id = ? ORDER BY t.name COLLATE NOCASE, t.id`, user)
|
||||
}
|
||||
|
||||
func queryTeams(d *db.DB, q string, args ...any) ([]TeamInfo, error) {
|
||||
rows, err := d.Query(q, args...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
var out []TeamInfo
|
||||
for rows.Next() {
|
||||
t, err := scanTeam(rows)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
out = append(out, *t)
|
||||
}
|
||||
return out, rows.Err()
|
||||
}
|
||||
|
||||
// SetTeamStatus suspends, restores or marks a team for deletion.
|
||||
func SetTeamStatus(d *db.DB, id int64, status string, deleteAt time.Time) error {
|
||||
_, err := d.Exec(`UPDATE teams SET status = ?, delete_at = ? WHERE id = ?`, status, tsOrEmpty(deleteAt), id)
|
||||
return err
|
||||
}
|
||||
|
||||
// SetSessionTeam switches a session to another of its user's teams.
|
||||
func SetSessionTeam(d *db.DB, sessionID string, team int64) error {
|
||||
_, err := d.Exec(`UPDATE sessions SET team_id = ? WHERE id = ?`, team, sessionID)
|
||||
return err
|
||||
}
|
||||
|
||||
// AgentTeam is the team an agent works for: agents belong to one.
|
||||
func AgentTeam(d *db.DB, agent int64) (int64, error) {
|
||||
var t int64
|
||||
err := d.QueryRow(`SELECT team_id FROM memberships WHERE user_id = ? ORDER BY team_id LIMIT 1`, agent).Scan(&t)
|
||||
if errors.Is(err, sql.ErrNoRows) {
|
||||
return 0, ErrNotFound
|
||||
}
|
||||
return t, err
|
||||
}
|
||||
+21
-2
@@ -110,8 +110,27 @@ type routes struct {
|
||||
unmapped []string
|
||||
}
|
||||
|
||||
func (rt *routes) HandleFunc(pattern string, fn http.HandlerFunc) {
|
||||
rt.Handle(pattern, fn)
|
||||
// HandleFunc registers a handler: a method expression such as
|
||||
// (*Server).seoPage, run on the Server for the request's team; or a plain
|
||||
// handler that needs no team.
|
||||
func (rt *routes) HandleFunc(pattern string, fn any) {
|
||||
switch f := fn.(type) {
|
||||
case func(*Server, http.ResponseWriter, *http.Request):
|
||||
rt.Handle(pattern, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
ts, err := rt.s.teamServer(r)
|
||||
if err != nil {
|
||||
rt.s.serverError(w, err)
|
||||
return
|
||||
}
|
||||
f(ts, w, r)
|
||||
}))
|
||||
case func(http.ResponseWriter, *http.Request):
|
||||
rt.Handle(pattern, http.HandlerFunc(f))
|
||||
case http.HandlerFunc:
|
||||
rt.Handle(pattern, f)
|
||||
default:
|
||||
panic(fmt.Sprintf("route %s: a handler of type %T", pattern, fn))
|
||||
}
|
||||
}
|
||||
|
||||
func (rt *routes) Handle(pattern string, h http.Handler) {
|
||||
|
||||
@@ -154,7 +154,7 @@ func (s *Server) activityPage(w http.ResponseWriter, r *http.Request) {
|
||||
d.More = entries[len(entries)-1].ID
|
||||
}
|
||||
d.Entries = entries
|
||||
d.People, _ = users.Members(s.DB, users.Team)
|
||||
d.People, _ = users.Members(s.DB, s.team())
|
||||
s.render(w, r, "activity", page{Title: "Activity", Nav: "settings/activity", Data: d})
|
||||
}
|
||||
|
||||
|
||||
+25
-11
@@ -32,7 +32,7 @@ func (s *Server) AgentAuth(r *http.Request, key string) (*mcpserver.Caller, erro
|
||||
if s.throttled(ipKey, users.MaxFailsPerIP, now) {
|
||||
return nil, users.ErrBadKey
|
||||
}
|
||||
u, _, err := users.Authenticate(s.DB, key, ip, now)
|
||||
u, _, err := users.Authenticate(s.platform(), key, ip, now)
|
||||
if err != nil {
|
||||
if errors.Is(err, users.ErrBadKey) {
|
||||
_ = users.Fail(s.DB, ipKey, users.ThrottleWindow, now)
|
||||
@@ -42,11 +42,21 @@ func (s *Server) AgentAuth(r *http.Request, key string) (*mcpserver.Caller, erro
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
m, err := users.MembershipOf(s.DB, users.Team, u.ID)
|
||||
team := s.team()
|
||||
if s.multi() {
|
||||
if team, err = users.AgentTeam(s.platform(), u.ID); err != nil {
|
||||
return nil, users.ErrBadKey
|
||||
}
|
||||
}
|
||||
ts, err := s.forTeam(team)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
m, err := users.MembershipOf(ts.platform(), team, u.ID)
|
||||
if err != nil {
|
||||
return nil, users.ErrBadKey
|
||||
}
|
||||
lim, err := users.LimitsOf(s.DB, u.ID)
|
||||
lim, err := users.LimitsOf(ts.DB, u.ID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -55,11 +65,15 @@ func (s *Server) AgentAuth(r *http.Request, key string) (*mcpserver.Caller, erro
|
||||
Reason: u.Name + " is paused: an admin can resume it under Settings → Agents."}
|
||||
}
|
||||
id := u.ID
|
||||
return &mcpserver.Caller{ID: u.ID, Name: u.Name, Can: m.Can,
|
||||
Before: func(ctx context.Context, tool string) error { return s.beforeCall(id, tool) },
|
||||
c := &mcpserver.Caller{ID: u.ID, Name: u.Name, Can: m.Can, Team: team,
|
||||
Before: func(ctx context.Context, tool string) error { return ts.beforeCall(id, tool) },
|
||||
After: func(tool string, res *mcp.CallToolResult, err error, took time.Duration) {
|
||||
s.afterCall(id, tool, res, err, took)
|
||||
}}, nil
|
||||
ts.afterCall(id, tool, res, err, took)
|
||||
}}
|
||||
if s.multi() {
|
||||
c.DB = ts.DB
|
||||
}
|
||||
return c, nil
|
||||
}
|
||||
|
||||
// beforeCall keeps an agent within its calls a minute, and stops a paused
|
||||
@@ -139,7 +153,7 @@ func (s *Server) EnsureHermes(token string) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if err := users.Join(s.DB, users.Team, u.ID, users.Member, map[string]users.Access{users.CRMScope: users.Edit, "market": users.View}, now); err != nil {
|
||||
if err := users.Join(s.DB, s.team(), u.ID, users.Member, map[string]users.Access{users.CRMScope: users.Edit, "market": users.View}, now); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, err := users.AddKey(s.DB, u.ID, token, time.Time{}, now); err != nil {
|
||||
@@ -173,7 +187,7 @@ type agentRow struct {
|
||||
}
|
||||
|
||||
func (s *Server) agentRows(now time.Time) ([]agentRow, error) {
|
||||
list, err := users.Members(s.DB, users.Team)
|
||||
list, err := users.Members(s.DB, s.team())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -313,7 +327,7 @@ func (s *Server) agentCreate(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
u, err := users.CreateAgent(s.DB, f.Name, f.Description, now)
|
||||
if err == nil {
|
||||
err = users.Join(s.DB, users.Team, u.ID, users.Member, f.Scopes, now)
|
||||
err = users.Join(s.DB, s.team(), u.ID, users.Member, f.Scopes, now)
|
||||
}
|
||||
var key string
|
||||
if err == nil {
|
||||
@@ -418,7 +432,7 @@ func (s *Server) agentAction(w http.ResponseWriter, r *http.Request) {
|
||||
s.renderAgent(w, r, u, sentence(err.Error())+".", http.StatusUnprocessableEntity)
|
||||
return
|
||||
}
|
||||
if err = users.Join(s.DB, users.Team, u.ID, users.Member, scopes, now); err == nil {
|
||||
if err = users.Join(s.DB, s.team(), u.ID, users.Member, scopes, now); err == nil {
|
||||
s.audit(r, "agent-changed", u.Name, agentAccessText(users.Membership{Role: users.Member, Modules: scopes}))
|
||||
redirect(w, r, back, "saved")
|
||||
return
|
||||
|
||||
@@ -31,6 +31,14 @@ import (
|
||||
|
||||
// AgentTools adds the module tools a caller may use.
|
||||
func (s *Server) AgentTools(srv *mcp.Server, c *mcpserver.Caller) {
|
||||
if c != nil && s.multi() {
|
||||
ts, err := s.forTeam(c.Team)
|
||||
if err != nil {
|
||||
s.Log.Error("mcp: the agent's team", "team", c.Team, "err", err)
|
||||
return
|
||||
}
|
||||
s = ts
|
||||
}
|
||||
may := func(module string, act bool) bool { return c == nil || c.Can(module, act) }
|
||||
if may("content", false) {
|
||||
s.contentReadTools(srv)
|
||||
|
||||
@@ -77,7 +77,7 @@ func (s *Server) agentViewer(id int64) *viewer {
|
||||
if err != nil || u.Status != users.Active {
|
||||
return &viewer{}
|
||||
}
|
||||
m, err := users.MembershipOf(s.DB, users.Team, id)
|
||||
m, err := users.MembershipOf(s.DB, s.team(), id)
|
||||
if err != nil {
|
||||
return &viewer{}
|
||||
}
|
||||
|
||||
+24
-3
@@ -87,7 +87,7 @@ func (s *Server) sessions(next http.Handler) http.Handler {
|
||||
next.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), viewerKey, localOwner)))
|
||||
return
|
||||
}
|
||||
if !publicPath(r.URL.Path) || strings.HasPrefix(r.URL.Path, "/signin") {
|
||||
if !s.multi() && (!publicPath(r.URL.Path) || strings.HasPrefix(r.URL.Path, "/signin")) {
|
||||
if done, err := s.hasOwner(); err != nil {
|
||||
s.serverError(w, err)
|
||||
return
|
||||
@@ -119,11 +119,11 @@ func (s *Server) lookupSession(r *http.Request) (*viewer, error) {
|
||||
if err != nil {
|
||||
return nil, users.ErrNoSession
|
||||
}
|
||||
sess, u, err := users.Lookup(s.DB, c.Value, time.Now())
|
||||
sess, u, err := users.Lookup(s.platform(), c.Value, time.Now())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
m, err := users.MembershipOf(s.DB, users.Team, u.ID)
|
||||
m, err := users.MembershipOf(s.platform(), sess.Team, u.ID)
|
||||
if errors.Is(err, users.ErrNotFound) {
|
||||
return nil, users.ErrNoSession // no longer in the team
|
||||
}
|
||||
@@ -319,3 +319,24 @@ func withCSRF(r *http.Request, exec func(*bytes.Buffer) error) ([]byte, error) {
|
||||
}
|
||||
return rewriteForms(buf.Bytes(), csrfToken(r), r.URL.Path, v), nil
|
||||
}
|
||||
|
||||
// teamServer is the Server for the request's team: the viewer's (the
|
||||
// team their session works in), else this one.
|
||||
func (s *Server) teamServer(r *http.Request) (*Server, error) {
|
||||
if !s.multi() {
|
||||
return s, nil
|
||||
}
|
||||
v := viewerOf(r)
|
||||
if v.Session == nil {
|
||||
return s, nil
|
||||
}
|
||||
return s.forTeam(v.Session.Team)
|
||||
}
|
||||
|
||||
// team is the team this Server works for.
|
||||
func (s *Server) team() int64 {
|
||||
if s.Team == 0 {
|
||||
return users.Team
|
||||
}
|
||||
return s.Team
|
||||
}
|
||||
|
||||
+18
-15
@@ -137,19 +137,20 @@ func (s *Server) redditReader(ctx context.Context) (*reddit.Client, error) {
|
||||
if id == "" || secret == "" {
|
||||
return nil, errors.New("add Reddit's client ID and secret under Settings → Social accounts to read subreddits")
|
||||
}
|
||||
s.mu.Lock()
|
||||
tok, exp := s.redditAppToken, s.redditAppTokenExp
|
||||
s.mu.Unlock()
|
||||
tc := s.cache()
|
||||
tc.mu.Lock()
|
||||
tok, exp := tc.redditAppToken, tc.redditAppTokenExp
|
||||
tc.mu.Unlock()
|
||||
if tok == "" || time.Now().After(exp) {
|
||||
res, err := oauth.RedditAppToken(ctx, id, secret, s.redditUserAgent())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
tok = res.AccessToken
|
||||
s.mu.Lock()
|
||||
tc.mu.Lock()
|
||||
// Reddit's app tokens last an hour; renew a little early.
|
||||
s.redditAppToken, s.redditAppTokenExp = tok, time.Now().Add(50*time.Minute)
|
||||
s.mu.Unlock()
|
||||
tc.redditAppToken, tc.redditAppTokenExp = tok, time.Now().Add(50*time.Minute)
|
||||
tc.mu.Unlock()
|
||||
}
|
||||
return reddit.New(tok, s.redditUserAgent(), nil), nil
|
||||
}
|
||||
@@ -193,9 +194,10 @@ func (s *Server) redditHistory(ctx context.Context) []reddit.Submission {
|
||||
return nil
|
||||
}
|
||||
user, c := a.External, s.redditClient(a)
|
||||
s.mu.Lock()
|
||||
h, at := s.redditHist, s.redditHistAt
|
||||
s.mu.Unlock()
|
||||
tc := s.cache()
|
||||
tc.mu.Lock()
|
||||
h, at := tc.redditHist, tc.redditHistAt
|
||||
tc.mu.Unlock()
|
||||
if h != nil && time.Since(at) < redditHistoryTTL {
|
||||
return h
|
||||
}
|
||||
@@ -207,15 +209,16 @@ func (s *Server) redditHistory(ctx context.Context) []reddit.Submission {
|
||||
if h == nil {
|
||||
h = []reddit.Submission{}
|
||||
}
|
||||
s.mu.Lock()
|
||||
s.redditHist, s.redditHistAt = h, time.Now()
|
||||
s.mu.Unlock()
|
||||
tc.mu.Lock()
|
||||
tc.redditHist, tc.redditHistAt = h, time.Now()
|
||||
tc.mu.Unlock()
|
||||
return h
|
||||
}
|
||||
|
||||
// forgetRedditHistory drops the cached posts after posting.
|
||||
func (s *Server) forgetRedditHistory() {
|
||||
s.mu.Lock()
|
||||
s.redditHist = nil
|
||||
s.mu.Unlock()
|
||||
tc := s.cache()
|
||||
tc.mu.Lock()
|
||||
tc.redditHist = nil
|
||||
tc.mu.Unlock()
|
||||
}
|
||||
|
||||
@@ -108,7 +108,7 @@ func (s *Server) viewerFor(user int64) *viewer {
|
||||
if err != nil || u.Status != users.Active {
|
||||
return &viewer{}
|
||||
}
|
||||
m, err := users.MembershipOf(s.DB, users.Team, u.ID)
|
||||
m, err := users.MembershipOf(s.DB, s.team(), u.ID)
|
||||
if err != nil {
|
||||
return &viewer{}
|
||||
}
|
||||
@@ -334,7 +334,7 @@ func (s *Server) postingPage(w http.ResponseWriter, r *http.Request) {
|
||||
s.serverError(w, err)
|
||||
return
|
||||
}
|
||||
members, err := users.Members(s.DB, users.Team)
|
||||
members, err := users.Members(s.DB, s.team())
|
||||
if err != nil {
|
||||
s.serverError(w, err)
|
||||
return
|
||||
|
||||
+13
-20
@@ -9,7 +9,6 @@ import (
|
||||
"sort"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"supermarket/internal/api/gsc"
|
||||
@@ -31,31 +30,24 @@ var googleFields = []secretField{
|
||||
// gscBase is the Search Console API's address; tests point it elsewhere.
|
||||
var gscBase = ""
|
||||
|
||||
// googleAuth caches the access token, which lasts an hour.
|
||||
type googleAuth struct {
|
||||
mu sync.Mutex
|
||||
token string
|
||||
expires time.Time
|
||||
}
|
||||
|
||||
var gauth googleAuth
|
||||
|
||||
func (s *Server) setGoogleToken(res *oauth.Result) {
|
||||
gauth.mu.Lock()
|
||||
defer gauth.mu.Unlock()
|
||||
gauth.token = res.AccessToken
|
||||
tc := s.cache()
|
||||
tc.mu.Lock()
|
||||
defer tc.mu.Unlock()
|
||||
tc.googleToken = res.AccessToken
|
||||
life := res.ExpiresIn
|
||||
if life <= 0 {
|
||||
life = time.Hour
|
||||
}
|
||||
gauth.expires = time.Now().Add(life - time.Minute)
|
||||
tc.googleExpires = time.Now().Add(life - time.Minute)
|
||||
}
|
||||
|
||||
// googleToken returns an access token, refreshing it when it's run out.
|
||||
func (s *Server) googleToken(ctx context.Context) (string, error) {
|
||||
gauth.mu.Lock()
|
||||
tok, exp := gauth.token, gauth.expires
|
||||
gauth.mu.Unlock()
|
||||
tc := s.cache()
|
||||
tc.mu.Lock()
|
||||
tok, exp := tc.googleToken, tc.googleExpires
|
||||
tc.mu.Unlock()
|
||||
if tok != "" && time.Now().Before(exp) {
|
||||
return tok, nil
|
||||
}
|
||||
@@ -177,9 +169,10 @@ func (s *Server) searchSettingsSave(w http.ResponseWriter, r *http.Request) {
|
||||
s.serverError(w, err)
|
||||
return
|
||||
}
|
||||
gauth.mu.Lock()
|
||||
gauth.token = ""
|
||||
gauth.mu.Unlock()
|
||||
tc := s.cache()
|
||||
tc.mu.Lock()
|
||||
tc.googleToken = ""
|
||||
tc.mu.Unlock()
|
||||
}
|
||||
if _, has := r.PostForm["gitea_url"]; has {
|
||||
u := strings.TrimRight(strings.TrimSpace(r.PostFormValue("gitea_url")), "/")
|
||||
|
||||
@@ -61,7 +61,6 @@ func TestSearchConsole(t *testing.T) {
|
||||
defer func() {
|
||||
oauth.SetGoogleURLs("https://accounts.google.com/o/oauth2/v2/auth", "https://oauth2.googleapis.com/token", "https://openidconnect.googleapis.com/v1/userinfo")
|
||||
gscBase = ""
|
||||
gauth.token = ""
|
||||
}()
|
||||
|
||||
s, h := newTestServer(t, nil)
|
||||
|
||||
+304
-200
@@ -71,34 +71,138 @@ type Server struct {
|
||||
ImportStatus *legacy.Status
|
||||
ImportErr error
|
||||
|
||||
pages map[string]*template.Template
|
||||
|
||||
mu sync.Mutex
|
||||
jobsOnce sync.Once
|
||||
setupDone atomic.Bool // the team has its owner (server edition)
|
||||
// Team is the team this Server works for: 1 on the local and server
|
||||
// editions. On the multi-tenant edition each request is served by a
|
||||
// copy for the viewer's team (forTeam), whose DB is that team's schema.
|
||||
Team int64
|
||||
// Teams opens each team's database (multi-tenant); nil otherwise.
|
||||
Teams *db.Teams
|
||||
// Platform is the database every team shares: people, sessions, keys,
|
||||
// locks. On the local and server editions, DB itself.
|
||||
Platform *db.DB
|
||||
|
||||
testPublisher func(*posting.Account) content.Publisher // tests: posts nowhere
|
||||
|
||||
// What a Server and its teams' copies share.
|
||||
*state
|
||||
}
|
||||
|
||||
// state is what a Server and its copies for each team share.
|
||||
type state struct {
|
||||
pages map[string]*template.Template
|
||||
jobsOnce sync.Once
|
||||
runner *jobs.Runner
|
||||
setupDone atomic.Bool // the team has its owner (server edition)
|
||||
|
||||
mu sync.Mutex
|
||||
copies map[int64]*Server // each team's Server
|
||||
caches map[int64]*teamCache // each team's tokens and lists kept a while
|
||||
}
|
||||
|
||||
// teamCache is what's kept in memory for a team.
|
||||
type teamCache struct {
|
||||
mu sync.Mutex
|
||||
// Reddit: an app-only token for reading rules before sign-in, and the
|
||||
// account's recent posts for the warnings.
|
||||
redditAppToken string
|
||||
redditAppTokenExp time.Time
|
||||
redditHist []reddit.Submission
|
||||
redditHistAt time.Time
|
||||
// Google's access token, which lasts an hour.
|
||||
googleToken string
|
||||
googleExpires time.Time
|
||||
}
|
||||
|
||||
// st is the shared state, made on first use.
|
||||
func (s *Server) st() *state {
|
||||
if s.state == nil {
|
||||
s.state = &state{copies: map[int64]*Server{}, caches: map[int64]*teamCache{}}
|
||||
}
|
||||
return s.state
|
||||
}
|
||||
|
||||
// cache is the team's.
|
||||
func (s *Server) cache() *teamCache {
|
||||
st := s.st()
|
||||
st.mu.Lock()
|
||||
defer st.mu.Unlock()
|
||||
c := st.caches[s.Team]
|
||||
if c == nil {
|
||||
c = &teamCache{}
|
||||
st.caches[s.Team] = c
|
||||
}
|
||||
return c
|
||||
}
|
||||
|
||||
// multi says whether this is the multi-tenant edition.
|
||||
func (s *Server) multi() bool { return s.Teams != nil }
|
||||
|
||||
// platform is the shared database.
|
||||
func (s *Server) platform() *db.DB {
|
||||
if s.Platform != nil {
|
||||
return s.Platform
|
||||
}
|
||||
return s.DB
|
||||
}
|
||||
|
||||
// forTeam is the Server for a team: itself on the local and server
|
||||
// editions; on the multi-tenant edition a copy with the team's database,
|
||||
// secrets and files. Copies are kept.
|
||||
func (s *Server) forTeam(team int64) (*Server, error) {
|
||||
if !s.multi() || team == s.Team {
|
||||
return s, nil
|
||||
}
|
||||
st := s.st()
|
||||
st.mu.Lock()
|
||||
c := st.copies[team]
|
||||
st.mu.Unlock()
|
||||
if c != nil {
|
||||
return c, nil
|
||||
}
|
||||
d, err := s.Teams.Open(team)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
key := []byte(nil)
|
||||
if s.Config != nil {
|
||||
key = s.Config.SecretKey
|
||||
}
|
||||
if key == nil {
|
||||
key = testSecretKey // tests without a Config
|
||||
}
|
||||
sec, err := secrets.OpenDB(d, key, nil)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
cp := *s
|
||||
cp.Team, cp.DB, cp.Secrets = team, d, sec
|
||||
cp.Platform = s.platform()
|
||||
st.mu.Lock()
|
||||
defer st.mu.Unlock()
|
||||
if c := st.copies[team]; c != nil {
|
||||
return c, nil
|
||||
}
|
||||
st.copies[team] = &cp
|
||||
return &cp, nil
|
||||
}
|
||||
|
||||
// testSecretKey seals teams' secrets in tests, which have no Config.
|
||||
var testSecretKey = []byte("0123456789abcdef0123456789abcdef")
|
||||
|
||||
// jobs is this copy of the app, for the locks it shares with the others.
|
||||
func (s *Server) jobs() *jobs.Runner {
|
||||
s.jobsOnce.Do(func() {
|
||||
if s.Jobs == nil {
|
||||
r, err := jobs.New(s.DB, s.Version, s.Log)
|
||||
st := s.st()
|
||||
st.jobsOnce.Do(func() {
|
||||
st.runner = s.Jobs
|
||||
if st.runner == nil {
|
||||
r, err := jobs.New(s.platform(), s.Version, s.Log)
|
||||
if err != nil {
|
||||
panic(fmt.Sprintf("jobs: %v", err)) // only without a Runner from main: tests
|
||||
}
|
||||
s.Jobs = r
|
||||
st.runner = r
|
||||
}
|
||||
})
|
||||
return s.Jobs
|
||||
return st.runner
|
||||
}
|
||||
|
||||
// alone says whether no other copy of the app is running: only then is
|
||||
@@ -142,48 +246,48 @@ func (s *Server) Handler() (http.Handler, error) {
|
||||
mux.Handle("/mcp", s.MCP)
|
||||
}
|
||||
|
||||
mux.HandleFunc("GET /{$}", s.dashboard)
|
||||
mux.HandleFunc("GET /{$}", (*Server).dashboard)
|
||||
|
||||
// Signing in (the server edition).
|
||||
mux.HandleFunc("GET /setup/{token}", s.setupPage)
|
||||
mux.HandleFunc("POST /setup/{token}", s.setupSave)
|
||||
mux.HandleFunc("GET /signin", s.signinPage)
|
||||
mux.HandleFunc("POST /signin", s.signin)
|
||||
mux.HandleFunc("POST /signin/code", s.signinCode)
|
||||
mux.HandleFunc("POST /signout", s.signout)
|
||||
mux.HandleFunc("GET /forgot", s.forgotPage)
|
||||
mux.HandleFunc("POST /forgot", s.forgot)
|
||||
mux.HandleFunc("GET /reset/{token}", s.resetPage)
|
||||
mux.HandleFunc("POST /reset/{token}", s.reset)
|
||||
mux.HandleFunc("GET /settings/account", s.accountPage)
|
||||
mux.HandleFunc("POST /settings/account/profile", s.accountProfile)
|
||||
mux.HandleFunc("POST /settings/account/password", s.accountPassword)
|
||||
mux.HandleFunc("POST /settings/account/sessions/end-others", s.accountEndOthers)
|
||||
mux.HandleFunc("POST /settings/account/sessions/{id}/end", s.accountEndSession)
|
||||
mux.HandleFunc("GET /settings/account/two-factor", s.twoFactorPage)
|
||||
mux.HandleFunc("POST /settings/account/two-factor", s.twoFactorOn)
|
||||
mux.HandleFunc("POST /settings/account/two-factor/off", s.twoFactorOff)
|
||||
mux.HandleFunc("POST /settings/account/recovery-codes", s.recoveryCodes)
|
||||
mux.HandleFunc("POST /settings/account/photo", s.accountPhoto)
|
||||
mux.HandleFunc("GET /users/{id}/photo", s.userPhoto)
|
||||
mux.HandleFunc("GET /settings/users", s.usersPage)
|
||||
mux.HandleFunc("POST /settings/users", s.userInvite)
|
||||
mux.HandleFunc("GET /settings/users/{id}", s.userPage)
|
||||
mux.HandleFunc("POST /settings/users/{id}/{action}", s.userAction)
|
||||
mux.HandleFunc("GET /invite/{token}", s.invitePage)
|
||||
mux.HandleFunc("POST /invite/{token}", s.inviteAccept)
|
||||
mux.HandleFunc("GET /setup/{token}", (*Server).setupPage)
|
||||
mux.HandleFunc("POST /setup/{token}", (*Server).setupSave)
|
||||
mux.HandleFunc("GET /signin", (*Server).signinPage)
|
||||
mux.HandleFunc("POST /signin", (*Server).signin)
|
||||
mux.HandleFunc("POST /signin/code", (*Server).signinCode)
|
||||
mux.HandleFunc("POST /signout", (*Server).signout)
|
||||
mux.HandleFunc("GET /forgot", (*Server).forgotPage)
|
||||
mux.HandleFunc("POST /forgot", (*Server).forgot)
|
||||
mux.HandleFunc("GET /reset/{token}", (*Server).resetPage)
|
||||
mux.HandleFunc("POST /reset/{token}", (*Server).reset)
|
||||
mux.HandleFunc("GET /settings/account", (*Server).accountPage)
|
||||
mux.HandleFunc("POST /settings/account/profile", (*Server).accountProfile)
|
||||
mux.HandleFunc("POST /settings/account/password", (*Server).accountPassword)
|
||||
mux.HandleFunc("POST /settings/account/sessions/end-others", (*Server).accountEndOthers)
|
||||
mux.HandleFunc("POST /settings/account/sessions/{id}/end", (*Server).accountEndSession)
|
||||
mux.HandleFunc("GET /settings/account/two-factor", (*Server).twoFactorPage)
|
||||
mux.HandleFunc("POST /settings/account/two-factor", (*Server).twoFactorOn)
|
||||
mux.HandleFunc("POST /settings/account/two-factor/off", (*Server).twoFactorOff)
|
||||
mux.HandleFunc("POST /settings/account/recovery-codes", (*Server).recoveryCodes)
|
||||
mux.HandleFunc("POST /settings/account/photo", (*Server).accountPhoto)
|
||||
mux.HandleFunc("GET /users/{id}/photo", (*Server).userPhoto)
|
||||
mux.HandleFunc("GET /settings/users", (*Server).usersPage)
|
||||
mux.HandleFunc("POST /settings/users", (*Server).userInvite)
|
||||
mux.HandleFunc("GET /settings/users/{id}", (*Server).userPage)
|
||||
mux.HandleFunc("POST /settings/users/{id}/{action}", (*Server).userAction)
|
||||
mux.HandleFunc("GET /invite/{token}", (*Server).invitePage)
|
||||
mux.HandleFunc("POST /invite/{token}", (*Server).inviteAccept)
|
||||
|
||||
mux.HandleFunc("GET /search", s.searchPage)
|
||||
mux.HandleFunc("GET /search", (*Server).searchPage)
|
||||
|
||||
mux.HandleFunc("GET /market", s.inventoryList)
|
||||
mux.HandleFunc("GET /market/new", s.inventoryEdit)
|
||||
mux.HandleFunc("GET /market/{id}", s.inventoryEdit)
|
||||
mux.HandleFunc("POST /market/save", s.inventorySave)
|
||||
mux.HandleFunc("POST /market/fill", s.inventoryFill)
|
||||
mux.HandleFunc("POST /market/{id}/delete", s.inventoryDelete)
|
||||
mux.HandleFunc("GET /market/import", s.inventoryImportPage)
|
||||
mux.HandleFunc("POST /market/import", s.inventoryImport)
|
||||
mux.HandleFunc("GET /market/export", s.inventoryExport)
|
||||
mux.HandleFunc("GET /market", (*Server).inventoryList)
|
||||
mux.HandleFunc("GET /market/new", (*Server).inventoryEdit)
|
||||
mux.HandleFunc("GET /market/{id}", (*Server).inventoryEdit)
|
||||
mux.HandleFunc("POST /market/save", (*Server).inventorySave)
|
||||
mux.HandleFunc("POST /market/fill", (*Server).inventoryFill)
|
||||
mux.HandleFunc("POST /market/{id}/delete", (*Server).inventoryDelete)
|
||||
mux.HandleFunc("GET /market/import", (*Server).inventoryImportPage)
|
||||
mux.HandleFunc("POST /market/import", (*Server).inventoryImport)
|
||||
mux.HandleFunc("GET /market/export", (*Server).inventoryExport)
|
||||
// The Market was the Inventory: its old addresses lead to the new ones
|
||||
// (308 keeps a form's POST a POST).
|
||||
mux.HandleFunc("/inventory", marketMoved)
|
||||
@@ -197,28 +301,28 @@ func (s *Server) Handler() (http.Handler, error) {
|
||||
}
|
||||
http.Redirect(w, r, "/settings/profile", http.StatusSeeOther)
|
||||
})
|
||||
mux.HandleFunc("GET /settings/profile", s.profilePage)
|
||||
mux.HandleFunc("POST /settings/profile", s.profileSave)
|
||||
mux.HandleFunc("POST /settings/profile/draft", s.profileDraft)
|
||||
mux.HandleFunc("GET /settings/profile", (*Server).profilePage)
|
||||
mux.HandleFunc("POST /settings/profile", (*Server).profileSave)
|
||||
mux.HandleFunc("POST /settings/profile/draft", (*Server).profileDraft)
|
||||
|
||||
mux.HandleFunc("GET /settings/ai", s.aiPage)
|
||||
mux.HandleFunc("POST /settings/ai", s.aiSave)
|
||||
mux.HandleFunc("POST /settings/ai/test", s.aiTest)
|
||||
mux.HandleFunc("GET /settings/ai/models", s.aiModels)
|
||||
mux.HandleFunc("GET /settings/ai", (*Server).aiPage)
|
||||
mux.HandleFunc("POST /settings/ai", (*Server).aiSave)
|
||||
mux.HandleFunc("POST /settings/ai/test", (*Server).aiTest)
|
||||
mux.HandleFunc("GET /settings/ai/models", (*Server).aiModels)
|
||||
|
||||
mux.HandleFunc("GET /settings/accounts", s.accountsPage)
|
||||
mux.HandleFunc("POST /settings/accounts", s.accountsSave)
|
||||
mux.HandleFunc("POST /settings/accounts/linkedin-page", s.linkedInPageSave)
|
||||
mux.HandleFunc("POST /auth/{provider}/start", s.oauthStart)
|
||||
mux.HandleFunc("GET /auth/{provider}/callback", s.oauthCallback)
|
||||
mux.HandleFunc("GET /settings/accounts", (*Server).accountsPage)
|
||||
mux.HandleFunc("POST /settings/accounts", (*Server).accountsSave)
|
||||
mux.HandleFunc("POST /settings/accounts/linkedin-page", (*Server).linkedInPageSave)
|
||||
mux.HandleFunc("POST /auth/{provider}/start", (*Server).oauthStart)
|
||||
mux.HandleFunc("GET /auth/{provider}/callback", (*Server).oauthCallback)
|
||||
|
||||
mux.HandleFunc("GET /content", s.contentIndex)
|
||||
mux.HandleFunc("GET /content/{id}", s.contentEntry)
|
||||
mux.HandleFunc("POST /content/{id}/fetch", s.contentFetch)
|
||||
mux.HandleFunc("POST /content/{id}/items", s.contentItems)
|
||||
mux.HandleFunc("GET /content/scheduled", s.scheduledPage)
|
||||
mux.HandleFunc("GET /content/published", s.publishedPage)
|
||||
mux.HandleFunc("GET /posts", s.inboxPage)
|
||||
mux.HandleFunc("GET /content", (*Server).contentIndex)
|
||||
mux.HandleFunc("GET /content/{id}", (*Server).contentEntry)
|
||||
mux.HandleFunc("POST /content/{id}/fetch", (*Server).contentFetch)
|
||||
mux.HandleFunc("POST /content/{id}/items", (*Server).contentItems)
|
||||
mux.HandleFunc("GET /content/scheduled", (*Server).scheduledPage)
|
||||
mux.HandleFunc("GET /content/published", (*Server).publishedPage)
|
||||
mux.HandleFunc("GET /posts", (*Server).inboxPage)
|
||||
// Posts was called the Inbox, and before that Drafts.
|
||||
mux.HandleFunc("GET /inbox", func(w http.ResponseWriter, r *http.Request) {
|
||||
redirect(w, r, "/posts", r.URL.Query().Get("msg"))
|
||||
@@ -226,140 +330,140 @@ func (s *Server) Handler() (http.Handler, error) {
|
||||
mux.HandleFunc("GET /drafts", func(w http.ResponseWriter, r *http.Request) {
|
||||
redirect(w, r, "/posts", r.URL.Query().Get("msg"))
|
||||
})
|
||||
mux.HandleFunc("POST /drafts/{id}/{action}", s.draftAction)
|
||||
mux.HandleFunc("POST /reddit/rules/{name}", s.refreshRules)
|
||||
mux.HandleFunc("POST /drafts/{id}/{action}", (*Server).draftAction)
|
||||
mux.HandleFunc("POST /reddit/rules/{name}", (*Server).refreshRules)
|
||||
|
||||
mux.HandleFunc("GET /prospects", s.prospectsPage)
|
||||
mux.HandleFunc("GET /prospects/new", s.prospectForm)
|
||||
mux.HandleFunc("POST /prospects/new", s.prospectAdd)
|
||||
mux.HandleFunc("GET /prospects/suppressed", s.suppressedPage)
|
||||
mux.HandleFunc("POST /prospects/suppressed", s.suppressedAction)
|
||||
mux.HandleFunc("POST /prospects/verify", s.prospectsVerify)
|
||||
mux.HandleFunc("POST /prospects/{kind}/{id}/{action}", s.prospectAction)
|
||||
mux.HandleFunc("GET /signals", s.signalsPage)
|
||||
mux.HandleFunc("GET /signals/new", s.signalPage)
|
||||
mux.HandleFunc("POST /signals/new", s.signalSave)
|
||||
mux.HandleFunc("POST /signals/campaigns", s.signalCampaign)
|
||||
mux.HandleFunc("POST /lead-sources/{source}/import", s.importSource)
|
||||
mux.HandleFunc("GET /signals/{id}", s.signalPage)
|
||||
mux.HandleFunc("POST /signals/{id}", s.signalSave)
|
||||
mux.HandleFunc("POST /signals/{id}/delete", s.signalDelete)
|
||||
mux.HandleFunc("POST /signals/{id}/discover/{source}", s.signalDiscover)
|
||||
mux.HandleFunc("GET /signals/{id}/runs", s.signalRuns)
|
||||
mux.HandleFunc("POST /funnel/{id}/delete", s.funnelDelete)
|
||||
mux.HandleFunc("GET /settings/sources", s.sourcesPage)
|
||||
mux.HandleFunc("POST /settings/sources", s.sourcesSave)
|
||||
mux.HandleFunc("POST /settings/sources/test/{source}", s.sourcesTest)
|
||||
mux.HandleFunc("GET /settings/email", s.emailPage)
|
||||
mux.HandleFunc("POST /settings/email", s.emailSave)
|
||||
mux.HandleFunc("POST /settings/email/test", s.emailTest)
|
||||
mux.HandleFunc("POST /settings/email/send-test", s.emailSendTest)
|
||||
mux.HandleFunc("GET /metrics", s.metricsPage)
|
||||
mux.HandleFunc("POST /metrics/sync", s.metricsSync)
|
||||
mux.HandleFunc("POST /metrics/margins", s.metricsMargins)
|
||||
mux.HandleFunc("POST /metrics/start", s.metricsStart)
|
||||
mux.HandleFunc("GET /metrics/month/{month}", s.metricsMonth)
|
||||
mux.HandleFunc("GET /metrics/customers", s.metricsCustomers)
|
||||
mux.HandleFunc("GET /metrics/spend", s.metricsSpend)
|
||||
mux.HandleFunc("GET /metrics/clv", s.metricsCLV)
|
||||
mux.HandleFunc("GET /metrics/export/{name}", s.metricsExport)
|
||||
mux.HandleFunc("GET /metrics/publish", s.metricsPublishPage)
|
||||
mux.HandleFunc("POST /metrics/publish", s.metricsPublish)
|
||||
mux.HandleFunc("POST /metrics/spend", s.metricsSpendAdd)
|
||||
mux.HandleFunc("POST /metrics/spend/{id}/delete", s.metricsSpendDelete)
|
||||
mux.HandleFunc("POST /metrics/customers/{id}", s.metricsCustomerMatch)
|
||||
mux.HandleFunc("GET /sites", s.sitesPage)
|
||||
mux.HandleFunc("POST /sites/sync", s.sitesSync)
|
||||
mux.HandleFunc("GET /sites/pages", s.sitePagesPage)
|
||||
mux.HandleFunc("POST /sites/pages", s.sitePageNew)
|
||||
mux.HandleFunc("GET /sites/pages/{id}", s.sitePagePage)
|
||||
mux.HandleFunc("POST /sites/pages/{id}/{action}", s.sitePageAction)
|
||||
mux.HandleFunc("GET /sites/publishing", s.sitesPublishingPage)
|
||||
mux.HandleFunc("POST /sites/theme/update", s.sitesThemeUpdate)
|
||||
mux.HandleFunc("GET /sites/new", s.newSitePage)
|
||||
mux.HandleFunc("POST /sites/new", s.newSiteCreate)
|
||||
mux.HandleFunc("GET /sites/forms", s.sitesFormsPage)
|
||||
mux.HandleFunc("POST /sites/forms/{action}", s.sitesFormsAction)
|
||||
mux.HandleFunc("GET /sites/previews", s.sitesPreviewsPage)
|
||||
mux.HandleFunc("POST /sites/previews/build", s.sitesPreviewBuild)
|
||||
mux.HandleFunc("POST /sites/previews/delete", s.sitesPreviewDelete)
|
||||
mux.HandleFunc("GET /preview/{site}/{slug}/{path...}", s.previewServe)
|
||||
mux.HandleFunc("GET /prospects", (*Server).prospectsPage)
|
||||
mux.HandleFunc("GET /prospects/new", (*Server).prospectForm)
|
||||
mux.HandleFunc("POST /prospects/new", (*Server).prospectAdd)
|
||||
mux.HandleFunc("GET /prospects/suppressed", (*Server).suppressedPage)
|
||||
mux.HandleFunc("POST /prospects/suppressed", (*Server).suppressedAction)
|
||||
mux.HandleFunc("POST /prospects/verify", (*Server).prospectsVerify)
|
||||
mux.HandleFunc("POST /prospects/{kind}/{id}/{action}", (*Server).prospectAction)
|
||||
mux.HandleFunc("GET /signals", (*Server).signalsPage)
|
||||
mux.HandleFunc("GET /signals/new", (*Server).signalPage)
|
||||
mux.HandleFunc("POST /signals/new", (*Server).signalSave)
|
||||
mux.HandleFunc("POST /signals/campaigns", (*Server).signalCampaign)
|
||||
mux.HandleFunc("POST /lead-sources/{source}/import", (*Server).importSource)
|
||||
mux.HandleFunc("GET /signals/{id}", (*Server).signalPage)
|
||||
mux.HandleFunc("POST /signals/{id}", (*Server).signalSave)
|
||||
mux.HandleFunc("POST /signals/{id}/delete", (*Server).signalDelete)
|
||||
mux.HandleFunc("POST /signals/{id}/discover/{source}", (*Server).signalDiscover)
|
||||
mux.HandleFunc("GET /signals/{id}/runs", (*Server).signalRuns)
|
||||
mux.HandleFunc("POST /funnel/{id}/delete", (*Server).funnelDelete)
|
||||
mux.HandleFunc("GET /settings/sources", (*Server).sourcesPage)
|
||||
mux.HandleFunc("POST /settings/sources", (*Server).sourcesSave)
|
||||
mux.HandleFunc("POST /settings/sources/test/{source}", (*Server).sourcesTest)
|
||||
mux.HandleFunc("GET /settings/email", (*Server).emailPage)
|
||||
mux.HandleFunc("POST /settings/email", (*Server).emailSave)
|
||||
mux.HandleFunc("POST /settings/email/test", (*Server).emailTest)
|
||||
mux.HandleFunc("POST /settings/email/send-test", (*Server).emailSendTest)
|
||||
mux.HandleFunc("GET /metrics", (*Server).metricsPage)
|
||||
mux.HandleFunc("POST /metrics/sync", (*Server).metricsSync)
|
||||
mux.HandleFunc("POST /metrics/margins", (*Server).metricsMargins)
|
||||
mux.HandleFunc("POST /metrics/start", (*Server).metricsStart)
|
||||
mux.HandleFunc("GET /metrics/month/{month}", (*Server).metricsMonth)
|
||||
mux.HandleFunc("GET /metrics/customers", (*Server).metricsCustomers)
|
||||
mux.HandleFunc("GET /metrics/spend", (*Server).metricsSpend)
|
||||
mux.HandleFunc("GET /metrics/clv", (*Server).metricsCLV)
|
||||
mux.HandleFunc("GET /metrics/export/{name}", (*Server).metricsExport)
|
||||
mux.HandleFunc("GET /metrics/publish", (*Server).metricsPublishPage)
|
||||
mux.HandleFunc("POST /metrics/publish", (*Server).metricsPublish)
|
||||
mux.HandleFunc("POST /metrics/spend", (*Server).metricsSpendAdd)
|
||||
mux.HandleFunc("POST /metrics/spend/{id}/delete", (*Server).metricsSpendDelete)
|
||||
mux.HandleFunc("POST /metrics/customers/{id}", (*Server).metricsCustomerMatch)
|
||||
mux.HandleFunc("GET /sites", (*Server).sitesPage)
|
||||
mux.HandleFunc("POST /sites/sync", (*Server).sitesSync)
|
||||
mux.HandleFunc("GET /sites/pages", (*Server).sitePagesPage)
|
||||
mux.HandleFunc("POST /sites/pages", (*Server).sitePageNew)
|
||||
mux.HandleFunc("GET /sites/pages/{id}", (*Server).sitePagePage)
|
||||
mux.HandleFunc("POST /sites/pages/{id}/{action}", (*Server).sitePageAction)
|
||||
mux.HandleFunc("GET /sites/publishing", (*Server).sitesPublishingPage)
|
||||
mux.HandleFunc("POST /sites/theme/update", (*Server).sitesThemeUpdate)
|
||||
mux.HandleFunc("GET /sites/new", (*Server).newSitePage)
|
||||
mux.HandleFunc("POST /sites/new", (*Server).newSiteCreate)
|
||||
mux.HandleFunc("GET /sites/forms", (*Server).sitesFormsPage)
|
||||
mux.HandleFunc("POST /sites/forms/{action}", (*Server).sitesFormsAction)
|
||||
mux.HandleFunc("GET /sites/previews", (*Server).sitesPreviewsPage)
|
||||
mux.HandleFunc("POST /sites/previews/build", (*Server).sitesPreviewBuild)
|
||||
mux.HandleFunc("POST /sites/previews/delete", (*Server).sitesPreviewDelete)
|
||||
mux.HandleFunc("GET /preview/{site}/{slug}/{path...}", (*Server).previewServe)
|
||||
mux.HandleFunc("GET /preview/{site}/{slug}", func(w http.ResponseWriter, r *http.Request) {
|
||||
http.Redirect(w, r, r.URL.Path+"/", http.StatusMovedPermanently)
|
||||
})
|
||||
mux.HandleFunc("GET /seo", s.seoPage)
|
||||
mux.HandleFunc("GET /seo/check", s.seoCheckPage)
|
||||
mux.HandleFunc("GET /seo/engines", s.seoEnginesPage)
|
||||
mux.HandleFunc("POST /seo/engines/setup", s.seoEnginesSetup)
|
||||
mux.HandleFunc("POST /seo/engines/ping", s.seoEnginesPing)
|
||||
mux.HandleFunc("GET /seo/briefs", s.seoBriefsPage)
|
||||
mux.HandleFunc("POST /seo/briefs", s.seoBriefNew)
|
||||
mux.HandleFunc("GET /seo/briefs/{id}", s.seoBriefPage)
|
||||
mux.HandleFunc("POST /seo/briefs/{id}/{action}", s.seoBriefAction)
|
||||
mux.HandleFunc("GET /seo/keywords", s.seoKeywordsPage)
|
||||
mux.HandleFunc("POST /seo/keywords", s.seoKeywordsFind)
|
||||
mux.HandleFunc("POST /seo/keywords/{id}/{action}", s.seoKeywordAction)
|
||||
mux.HandleFunc("GET /seo/changes", s.seoChangesPage)
|
||||
mux.HandleFunc("POST /seo/changes/suggest", s.seoChangesSuggest)
|
||||
mux.HandleFunc("POST /seo/changes/page", s.seoChangeForPage)
|
||||
mux.HandleFunc("POST /seo/changes/{id}/{action}", s.seoChangeAction)
|
||||
mux.HandleFunc("POST /settings/search/test/gitea", s.giteaTest)
|
||||
mux.HandleFunc("GET /seo/audit", s.seoAuditPage)
|
||||
mux.HandleFunc("POST /seo/audit", s.seoAuditRun)
|
||||
mux.HandleFunc("GET /seo/audit/status", s.seoAuditStatus)
|
||||
mux.HandleFunc("GET /seo/report", s.seoReportPage)
|
||||
mux.HandleFunc("GET /seo/next", s.seoNextPage)
|
||||
mux.HandleFunc("POST /settings/email/listmonk", s.listmonkSave)
|
||||
mux.HandleFunc("POST /settings/email/listmonk/test", s.listmonkTest)
|
||||
mux.HandleFunc("POST /settings/email/listmonk/sync", s.listmonkSync)
|
||||
mux.HandleFunc("GET /seo/links", s.seoLinksPage)
|
||||
mux.HandleFunc("POST /seo/links/bing", s.seoLinksBing)
|
||||
mux.HandleFunc("POST /seo/links/{action}", s.seoLinksAction)
|
||||
mux.HandleFunc("GET /sites/pages/add", s.sitesAddPage)
|
||||
mux.HandleFunc("POST /sites/pages/add", s.sitesAdd)
|
||||
mux.HandleFunc("POST /seo/next/dismiss", s.seoNextDismiss)
|
||||
mux.HandleFunc("POST /seo/report", s.seoReportWrite)
|
||||
mux.HandleFunc("GET /settings/search", s.searchSettingsPage)
|
||||
mux.HandleFunc("POST /settings/search", s.searchSettingsSave)
|
||||
mux.HandleFunc("POST /settings/search/sync", s.seoSync)
|
||||
mux.HandleFunc("GET /settings/tracking", s.trackingPage)
|
||||
mux.HandleFunc("POST /settings/tracking", s.trackingSave)
|
||||
mux.HandleFunc("POST /settings/tracking/test/{source}", s.trackingTest)
|
||||
mux.HandleFunc("POST /settings/tracking/signups", s.trackingSignups)
|
||||
mux.HandleFunc("POST /settings/tracking/run/{source}", s.trackingRun)
|
||||
mux.HandleFunc("GET /outreach", s.outreachPage)
|
||||
mux.HandleFunc("POST /outreach/draft", s.outreachDraft)
|
||||
mux.HandleFunc("POST /outreach/draft-many", s.outreachDraftMany)
|
||||
mux.HandleFunc("POST /outreach/check", s.outreachCheck)
|
||||
mux.HandleFunc("POST /outreach/{id}/{action}", s.outreachAction)
|
||||
mux.HandleFunc("GET /crm", s.crmPage)
|
||||
mux.HandleFunc("GET /crm/reach", s.crmReach)
|
||||
mux.HandleFunc("POST /crm/{action}", s.crmAction)
|
||||
mux.HandleFunc("POST /crm/{id}/{action}", s.crmAction)
|
||||
mux.HandleFunc("GET /seo", (*Server).seoPage)
|
||||
mux.HandleFunc("GET /seo/check", (*Server).seoCheckPage)
|
||||
mux.HandleFunc("GET /seo/engines", (*Server).seoEnginesPage)
|
||||
mux.HandleFunc("POST /seo/engines/setup", (*Server).seoEnginesSetup)
|
||||
mux.HandleFunc("POST /seo/engines/ping", (*Server).seoEnginesPing)
|
||||
mux.HandleFunc("GET /seo/briefs", (*Server).seoBriefsPage)
|
||||
mux.HandleFunc("POST /seo/briefs", (*Server).seoBriefNew)
|
||||
mux.HandleFunc("GET /seo/briefs/{id}", (*Server).seoBriefPage)
|
||||
mux.HandleFunc("POST /seo/briefs/{id}/{action}", (*Server).seoBriefAction)
|
||||
mux.HandleFunc("GET /seo/keywords", (*Server).seoKeywordsPage)
|
||||
mux.HandleFunc("POST /seo/keywords", (*Server).seoKeywordsFind)
|
||||
mux.HandleFunc("POST /seo/keywords/{id}/{action}", (*Server).seoKeywordAction)
|
||||
mux.HandleFunc("GET /seo/changes", (*Server).seoChangesPage)
|
||||
mux.HandleFunc("POST /seo/changes/suggest", (*Server).seoChangesSuggest)
|
||||
mux.HandleFunc("POST /seo/changes/page", (*Server).seoChangeForPage)
|
||||
mux.HandleFunc("POST /seo/changes/{id}/{action}", (*Server).seoChangeAction)
|
||||
mux.HandleFunc("POST /settings/search/test/gitea", (*Server).giteaTest)
|
||||
mux.HandleFunc("GET /seo/audit", (*Server).seoAuditPage)
|
||||
mux.HandleFunc("POST /seo/audit", (*Server).seoAuditRun)
|
||||
mux.HandleFunc("GET /seo/audit/status", (*Server).seoAuditStatus)
|
||||
mux.HandleFunc("GET /seo/report", (*Server).seoReportPage)
|
||||
mux.HandleFunc("GET /seo/next", (*Server).seoNextPage)
|
||||
mux.HandleFunc("POST /settings/email/listmonk", (*Server).listmonkSave)
|
||||
mux.HandleFunc("POST /settings/email/listmonk/test", (*Server).listmonkTest)
|
||||
mux.HandleFunc("POST /settings/email/listmonk/sync", (*Server).listmonkSync)
|
||||
mux.HandleFunc("GET /seo/links", (*Server).seoLinksPage)
|
||||
mux.HandleFunc("POST /seo/links/bing", (*Server).seoLinksBing)
|
||||
mux.HandleFunc("POST /seo/links/{action}", (*Server).seoLinksAction)
|
||||
mux.HandleFunc("GET /sites/pages/add", (*Server).sitesAddPage)
|
||||
mux.HandleFunc("POST /sites/pages/add", (*Server).sitesAdd)
|
||||
mux.HandleFunc("POST /seo/next/dismiss", (*Server).seoNextDismiss)
|
||||
mux.HandleFunc("POST /seo/report", (*Server).seoReportWrite)
|
||||
mux.HandleFunc("GET /settings/search", (*Server).searchSettingsPage)
|
||||
mux.HandleFunc("POST /settings/search", (*Server).searchSettingsSave)
|
||||
mux.HandleFunc("POST /settings/search/sync", (*Server).seoSync)
|
||||
mux.HandleFunc("GET /settings/tracking", (*Server).trackingPage)
|
||||
mux.HandleFunc("POST /settings/tracking", (*Server).trackingSave)
|
||||
mux.HandleFunc("POST /settings/tracking/test/{source}", (*Server).trackingTest)
|
||||
mux.HandleFunc("POST /settings/tracking/signups", (*Server).trackingSignups)
|
||||
mux.HandleFunc("POST /settings/tracking/run/{source}", (*Server).trackingRun)
|
||||
mux.HandleFunc("GET /outreach", (*Server).outreachPage)
|
||||
mux.HandleFunc("POST /outreach/draft", (*Server).outreachDraft)
|
||||
mux.HandleFunc("POST /outreach/draft-many", (*Server).outreachDraftMany)
|
||||
mux.HandleFunc("POST /outreach/check", (*Server).outreachCheck)
|
||||
mux.HandleFunc("POST /outreach/{id}/{action}", (*Server).outreachAction)
|
||||
mux.HandleFunc("GET /crm", (*Server).crmPage)
|
||||
mux.HandleFunc("GET /crm/reach", (*Server).crmReach)
|
||||
mux.HandleFunc("POST /crm/{action}", (*Server).crmAction)
|
||||
mux.HandleFunc("POST /crm/{id}/{action}", (*Server).crmAction)
|
||||
|
||||
mux.HandleFunc("GET /settings/backups", s.backupsPage)
|
||||
mux.HandleFunc("POST /settings/backups/{action}", s.backupsAction)
|
||||
mux.HandleFunc("GET /settings/backups/file/{name}", s.backupDownload)
|
||||
mux.HandleFunc("POST /settings/backups/upload", s.backupUpload)
|
||||
mux.HandleFunc("GET /settings/about", s.aboutPage)
|
||||
mux.HandleFunc("GET /settings/connections", s.connectionsPage)
|
||||
mux.HandleFunc("GET /settings/activity", s.activityPage)
|
||||
mux.HandleFunc("GET /api/v1/docs", s.apiDocs)
|
||||
mux.HandleFunc("GET /api/v1/tools", s.apiTools)
|
||||
mux.HandleFunc("POST /api/v1/{tool}", s.apiCall)
|
||||
mux.HandleFunc("GET /approvals", s.approvalsPage)
|
||||
mux.HandleFunc("POST /approvals/allowed/withdraw", s.approvalWithdraw)
|
||||
mux.HandleFunc("POST /approvals/{id}/{action}", s.approvalAction)
|
||||
mux.HandleFunc("GET /settings/agents", s.agentsPage)
|
||||
mux.HandleFunc("POST /settings/agents", s.agentCreate)
|
||||
mux.HandleFunc("GET /settings/agents/{id}", s.agentPage)
|
||||
mux.HandleFunc("POST /settings/agents/{id}/{action}", s.agentAction)
|
||||
mux.HandleFunc("GET /settings/posting", s.postingPage)
|
||||
mux.HandleFunc("POST /settings/posting", s.postingSave)
|
||||
mux.HandleFunc("POST /settings/posting/{id}/remove", s.postingRemove)
|
||||
mux.HandleFunc("POST /settings/account/posting/{id}/remove", s.postingRemove)
|
||||
mux.HandleFunc("GET /settings/core", s.corePage)
|
||||
mux.HandleFunc("GET /settings/core/checks", s.coreChecks)
|
||||
mux.HandleFunc("GET /settings/backups", (*Server).backupsPage)
|
||||
mux.HandleFunc("POST /settings/backups/{action}", (*Server).backupsAction)
|
||||
mux.HandleFunc("GET /settings/backups/file/{name}", (*Server).backupDownload)
|
||||
mux.HandleFunc("POST /settings/backups/upload", (*Server).backupUpload)
|
||||
mux.HandleFunc("GET /settings/about", (*Server).aboutPage)
|
||||
mux.HandleFunc("GET /settings/connections", (*Server).connectionsPage)
|
||||
mux.HandleFunc("GET /settings/activity", (*Server).activityPage)
|
||||
mux.HandleFunc("GET /api/v1/docs", (*Server).apiDocs)
|
||||
mux.HandleFunc("GET /api/v1/tools", (*Server).apiTools)
|
||||
mux.HandleFunc("POST /api/v1/{tool}", (*Server).apiCall)
|
||||
mux.HandleFunc("GET /approvals", (*Server).approvalsPage)
|
||||
mux.HandleFunc("POST /approvals/allowed/withdraw", (*Server).approvalWithdraw)
|
||||
mux.HandleFunc("POST /approvals/{id}/{action}", (*Server).approvalAction)
|
||||
mux.HandleFunc("GET /settings/agents", (*Server).agentsPage)
|
||||
mux.HandleFunc("POST /settings/agents", (*Server).agentCreate)
|
||||
mux.HandleFunc("GET /settings/agents/{id}", (*Server).agentPage)
|
||||
mux.HandleFunc("POST /settings/agents/{id}/{action}", (*Server).agentAction)
|
||||
mux.HandleFunc("GET /settings/posting", (*Server).postingPage)
|
||||
mux.HandleFunc("POST /settings/posting", (*Server).postingSave)
|
||||
mux.HandleFunc("POST /settings/posting/{id}/remove", (*Server).postingRemove)
|
||||
mux.HandleFunc("POST /settings/account/posting/{id}/remove", (*Server).postingRemove)
|
||||
mux.HandleFunc("GET /settings/core", (*Server).corePage)
|
||||
mux.HandleFunc("GET /settings/core/checks", (*Server).coreChecks)
|
||||
|
||||
// Where these pages used to be, for bookmarks.
|
||||
for old, now := range map[string]string{
|
||||
@@ -554,7 +658,7 @@ func (s *Server) loadTemplates() error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
s.pages = map[string]*template.Template{}
|
||||
s.st().pages = map[string]*template.Template{}
|
||||
for _, name := range names {
|
||||
base := strings.TrimSuffix(strings.TrimPrefix(name, "templates/"), ".html")
|
||||
if base == "layout" {
|
||||
@@ -564,7 +668,7 @@ func (s *Server) loadTemplates() error {
|
||||
if err != nil {
|
||||
return fmt.Errorf("template %s: %w", name, err)
|
||||
}
|
||||
s.pages[base] = t
|
||||
s.st().pages[base] = t
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -645,7 +749,7 @@ func (p page) Can(area string) bool { return p.Viewer == nil || p.Viewer.can(are
|
||||
// render writes a full page, or only its "content" block for htmx requests
|
||||
// that ask for a fragment.
|
||||
func (s *Server) render(w http.ResponseWriter, r *http.Request, name string, p page) {
|
||||
t, ok := s.pages[name]
|
||||
t, ok := s.st().pages[name]
|
||||
if !ok {
|
||||
http.Error(w, "no template "+name, http.StatusInternalServerError)
|
||||
return
|
||||
@@ -677,7 +781,7 @@ func (s *Server) render(w http.ResponseWriter, r *http.Request, name string, p p
|
||||
|
||||
// fragment writes one named template (for htmx swaps).
|
||||
func (s *Server) fragment(w http.ResponseWriter, r *http.Request, page, name string, data any) {
|
||||
t, ok := s.pages[page]
|
||||
t, ok := s.st().pages[page]
|
||||
if !ok {
|
||||
http.Error(w, "no template "+page, http.StatusInternalServerError)
|
||||
return
|
||||
|
||||
@@ -16,12 +16,12 @@ import (
|
||||
|
||||
// hasOwner says whether the setup is finished.
|
||||
func (s *Server) hasOwner() (bool, error) {
|
||||
if s.setupDone.Load() {
|
||||
if s.st().setupDone.Load() {
|
||||
return true, nil
|
||||
}
|
||||
ok, err := users.HasOwner(s.DB, users.Team)
|
||||
ok, err := users.HasOwner(s.DB, s.team())
|
||||
if ok {
|
||||
s.setupDone.Store(true)
|
||||
s.st().setupDone.Store(true)
|
||||
}
|
||||
return ok, err
|
||||
}
|
||||
@@ -111,11 +111,11 @@ func (s *Server) setupSave(w http.ResponseWriter, r *http.Request) {
|
||||
s.serverError(w, err)
|
||||
return
|
||||
}
|
||||
if err := users.Join(s.DB, users.Team, u.ID, users.Owner, nil, now); err != nil {
|
||||
if err := users.Join(s.DB, s.team(), u.ID, users.Owner, nil, now); err != nil {
|
||||
s.serverError(w, err)
|
||||
return
|
||||
}
|
||||
s.setupDone.Store(true)
|
||||
s.st().setupDone.Store(true)
|
||||
s.Log.Info("setup: the owner is created", "email", u.Email)
|
||||
s.record(audit.Entry{UserID: u.ID, UserName: displayName(u), Action: "setup", Target: u.Email, IP: clientIP(r)})
|
||||
if err := s.startSession(w, r, u); err != nil {
|
||||
|
||||
@@ -115,7 +115,7 @@ func (s *Server) cannotSignIn(u *users.User) string {
|
||||
case u.Status != users.Active || u.Kind != users.Person:
|
||||
return badSignIn
|
||||
}
|
||||
if _, err := users.MembershipOf(s.DB, users.Team, u.ID); err != nil {
|
||||
if _, err := users.MembershipOf(s.DB, s.team(), u.ID); err != nil {
|
||||
return "This account isn't part of the team any more. Ask an admin if you need it again."
|
||||
}
|
||||
return ""
|
||||
|
||||
@@ -0,0 +1,135 @@
|
||||
package web
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"supermarket/internal/config"
|
||||
"supermarket/internal/db"
|
||||
"supermarket/internal/inventory"
|
||||
"supermarket/internal/users"
|
||||
)
|
||||
|
||||
// newMultiEdition is a test server run as the multi-tenant edition: each
|
||||
// team in its own schema. Postgres only.
|
||||
func newMultiEdition(t *testing.T) (*Server, http.Handler) {
|
||||
t.Helper()
|
||||
if !db.OnPostgres() {
|
||||
t.Skip("the multi-tenant edition needs Postgres")
|
||||
}
|
||||
s, h := newServerEdition(t)
|
||||
s.Config = &config.Config{Edition: config.Multi}
|
||||
teams, err := s.DB.Teams()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(teams.Close)
|
||||
s.Teams, s.Platform = teams, s.DB
|
||||
return s, h
|
||||
}
|
||||
|
||||
// newTeam makes a team with its schema and an owner, signed in.
|
||||
func newTeam(t *testing.T, s *Server, name, owner string) (*users.TeamInfo, *users.User, *http.Cookie) {
|
||||
t.Helper()
|
||||
team, err := users.CreateTeam(s.platform(), name, strings.ToLower(name)+".example", time.Now())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := s.Teams.Create(team.ID); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
u := &users.User{Email: owner, Name: name + " owner", Status: users.Active}
|
||||
if err := users.Create(s.platform(), u, time.Now()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
users.SetPassword(s.platform(), u, "a long enough one")
|
||||
if err := users.Join(s.platform(), team.ID, u.ID, users.Owner, nil, time.Now()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
token, _, err := users.StartSessionIn(s.platform(), u.ID, team.ID, "", "", time.Now())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return team, u, &http.Cookie{Name: sessionCookie, Value: token}
|
||||
}
|
||||
|
||||
func TestTeamsDontSeeEachOther(t *testing.T) {
|
||||
s, h := newMultiEdition(t)
|
||||
a, _, ac := newTeam(t, s, "Acme", "olu@acme.example")
|
||||
b, _, bc := newTeam(t, s, "Bolt", "bea@bolt.example")
|
||||
|
||||
// Each saves its profile and a Market entry, through the pages.
|
||||
for _, c := range []struct {
|
||||
cookie *http.Cookie
|
||||
name string
|
||||
}{{ac, "Acme"}, {bc, "Bolt"}} {
|
||||
if rec := as(h, c.cookie, http.MethodPost, "/settings/profile", url.Values{"name": {c.name + " Inc"}, "description": {"We are " + c.name}}); rec.Code != http.StatusSeeOther {
|
||||
t.Fatalf("%s profile: %d %s", c.name, rec.Code, rec.Body.String())
|
||||
}
|
||||
if rec := as(h, c.cookie, http.MethodPost, "/market/save", url.Values{"name": {c.name + "'s rival"}, "relationship": {"competitor"}, "description": {"x"}}); rec.Code != http.StatusSeeOther {
|
||||
t.Fatalf("%s market: %d %s", c.name, rec.Code, rec.Body.String())
|
||||
}
|
||||
}
|
||||
for _, c := range []struct {
|
||||
cookie *http.Cookie
|
||||
mine, other string
|
||||
}{{ac, "Acme", "Bolt"}, {bc, "Bolt", "Acme"}} {
|
||||
for _, p := range []string{"/settings/profile", "/market", "/search?q=rival", "/"} {
|
||||
body := as(h, c.cookie, http.MethodGet, p, nil).Body.String()
|
||||
if strings.Contains(body, c.other) {
|
||||
t.Errorf("%s sees %s on %s", c.mine, c.other, p)
|
||||
}
|
||||
}
|
||||
if body := as(h, c.cookie, http.MethodGet, "/market", nil).Body.String(); !strings.Contains(body, c.mine+"'s rival") {
|
||||
t.Errorf("%s doesn't see its own entry", c.mine)
|
||||
}
|
||||
}
|
||||
// In the database: each team's rows in its own schema, none in the main.
|
||||
if list, _ := inventory.List(s.platform(), ""); len(list) != 0 {
|
||||
t.Errorf("rows in the main schema: %v", list)
|
||||
}
|
||||
ta, _ := s.forTeam(a.ID)
|
||||
tb, _ := s.forTeam(b.ID)
|
||||
if la, _ := inventory.List(ta.DB, ""); len(la) != 1 || la[0].Name != "Acme's rival" {
|
||||
t.Errorf("team a: %v", la)
|
||||
}
|
||||
if lb, _ := inventory.List(tb.DB, ""); len(lb) != 1 || lb[0].Name != "Bolt's rival" {
|
||||
t.Errorf("team b: %v", lb)
|
||||
}
|
||||
|
||||
// Agents: each team's agent sees its own team's data only.
|
||||
_, key := newAgentIn(t, ta, "A's agent", map[string]users.Access{"market": users.View})
|
||||
text, _ := mcpCall(t, h, key, "market_list", map[string]any{})
|
||||
if !strings.Contains(text, "Acme's rival") || strings.Contains(text, "Bolt") {
|
||||
t.Errorf("agent's market: %s", text)
|
||||
}
|
||||
text, _ = mcpCall(t, h, key, "profile_get", map[string]any{})
|
||||
if !strings.Contains(text, "Acme Inc") {
|
||||
t.Errorf("agent's profile: %s", text)
|
||||
}
|
||||
// Secrets too: each team's own.
|
||||
as(h, ac, http.MethodPost, "/settings/sources", url.Values{"hunter.api_key": {"acme-key"}})
|
||||
if ta.Secrets.Get("hunter.api_key") != "acme-key" || tb.Secrets.Has("hunter.api_key") {
|
||||
t.Error("secrets shared between teams")
|
||||
}
|
||||
}
|
||||
|
||||
// newAgentIn makes an agent in a team.
|
||||
func newAgentIn(t *testing.T, ts *Server, name string, scopes map[string]users.Access) (*users.User, string) {
|
||||
t.Helper()
|
||||
u, err := users.CreateAgent(ts.platform(), name, "", time.Now())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := users.Join(ts.platform(), ts.team(), u.ID, users.Member, scopes, time.Now()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
key, _, err := users.NewKey(ts.platform(), u.ID, time.Time{}, time.Now())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return u, key
|
||||
}
|
||||
@@ -109,7 +109,7 @@ type memberRow struct {
|
||||
}
|
||||
|
||||
func (s *Server) memberRows() ([]memberRow, error) {
|
||||
list, err := users.Members(s.DB, users.Team)
|
||||
list, err := users.Members(s.DB, s.team())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
@@ -241,7 +241,7 @@ func (s *Server) userInvite(w http.ResponseWriter, r *http.Request) {
|
||||
s.serverError(w, err)
|
||||
return
|
||||
}
|
||||
if err := users.Join(s.DB, users.Team, u.ID, role, mods, now); err != nil {
|
||||
if err := users.Join(s.DB, s.team(), u.ID, role, mods, now); err != nil {
|
||||
s.serverError(w, err)
|
||||
return
|
||||
}
|
||||
@@ -299,7 +299,7 @@ func (s *Server) target(w http.ResponseWriter, r *http.Request) (*users.User, us
|
||||
s.serverError(w, err)
|
||||
return nil, users.Membership{}, false
|
||||
}
|
||||
m, err := users.MembershipOf(s.DB, users.Team, u.ID)
|
||||
m, err := users.MembershipOf(s.DB, s.team(), u.ID)
|
||||
if errors.Is(err, users.ErrNotFound) {
|
||||
http.NotFound(w, r)
|
||||
return nil, users.Membership{}, false
|
||||
@@ -381,8 +381,8 @@ func (s *Server) userAction(w http.ResponseWriter, r *http.Request) {
|
||||
s.renderUser(w, r, v, u, m, "Give them at least one module, or make them an admin.", http.StatusUnprocessableEntity)
|
||||
return
|
||||
}
|
||||
if err = users.Join(s.DB, users.Team, u.ID, role, mods, time.Now()); err == nil {
|
||||
nm, _ := users.MembershipOf(s.DB, users.Team, u.ID)
|
||||
if err = users.Join(s.DB, s.team(), u.ID, role, mods, time.Now()); err == nil {
|
||||
nm, _ := users.MembershipOf(s.DB, s.team(), u.ID)
|
||||
u.Emails = pickEmails(nm, u.Emails) // none for modules they've lost
|
||||
err = users.SaveProfile(s.DB, u)
|
||||
}
|
||||
@@ -527,7 +527,7 @@ func (s *Server) inviteData(w http.ResponseWriter, r *http.Request) (*inviteData
|
||||
s.serverError(w, err)
|
||||
return nil, false
|
||||
}
|
||||
m, err := users.MembershipOf(s.DB, users.Team, d.U.ID)
|
||||
m, err := users.MembershipOf(s.DB, s.team(), d.U.ID)
|
||||
if err != nil {
|
||||
s.serverError(w, err)
|
||||
return nil, false
|
||||
@@ -549,7 +549,7 @@ func (s *Server) inviteAccept(w http.ResponseWriter, r *http.Request) {
|
||||
u.Name = strings.TrimSpace(r.PostFormValue("name"))
|
||||
u.Title = strings.TrimSpace(r.PostFormValue("title"))
|
||||
u.TimeZone = strings.TrimSpace(r.PostFormValue("time_zone"))
|
||||
m, _ := users.MembershipOf(s.DB, users.Team, u.ID)
|
||||
m, _ := users.MembershipOf(s.DB, s.team(), u.ID)
|
||||
u.Emails = pickEmails(m, r.PostForm["emails"])
|
||||
pw := r.PostFormValue("password")
|
||||
switch {
|
||||
@@ -604,7 +604,7 @@ func (s *Server) mailTeam(ctx context.Context, kind, subject, body string) int {
|
||||
ek = k
|
||||
}
|
||||
}
|
||||
list, err := users.Members(s.DB, users.Team)
|
||||
list, err := users.Members(s.DB, s.team())
|
||||
if err != nil {
|
||||
s.Log.Warn("mail: listing who gets "+kind, "err", err)
|
||||
return 0
|
||||
|
||||
Reference in New Issue
Block a user