Orgs are created inside their own tenant scope, so signup needs no system scope. Refs #3 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_017GpWAskjmYtZpuQ5JwYTX3
72 lines
1.8 KiB
Go
72 lines
1.8 KiB
Go
package tenant
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
|
|
"github.com/google/uuid"
|
|
"github.com/jackc/pgx/v5"
|
|
"github.com/jackc/pgx/v5/pgxpool"
|
|
|
|
"git.zb-server.de/ZB-Server/uptimesebi/internal/store"
|
|
)
|
|
|
|
// Scope is the row-level-security context of one transaction. The zero value
|
|
// sees nothing.
|
|
type Scope struct {
|
|
OrgID uuid.UUID
|
|
UserID uuid.UUID
|
|
system bool
|
|
global bool
|
|
}
|
|
|
|
func Org(org, user uuid.UUID) Scope { return Scope{OrgID: org, UserID: user} }
|
|
|
|
// User grants access to the user's own memberships and the orgs behind them,
|
|
// which is what login and the org switcher need before an org is chosen.
|
|
func User(user uuid.UUID) Scope { return Scope{UserID: user} }
|
|
|
|
// Global carries no tenant context: only tables without row-level security,
|
|
// such as users, are usable. Login runs here before the user is known.
|
|
func Global() Scope { return Scope{global: true} }
|
|
|
|
// System bypasses tenant isolation. Reserve it for work that is inherently
|
|
// cross-tenant, never for request handling.
|
|
func System() Scope { return Scope{system: true} }
|
|
|
|
var ErrNoScope = errors.New("tenant: empty scope")
|
|
|
|
type DB struct{ pool *pgxpool.Pool }
|
|
|
|
func New(pool *pgxpool.Pool) *DB { return &DB{pool: pool} }
|
|
|
|
func (d *DB) Tx(ctx context.Context, s Scope, fn func(*store.Queries) error) error {
|
|
if s == (Scope{}) {
|
|
return ErrNoScope
|
|
}
|
|
return pgx.BeginFunc(ctx, d.pool, func(tx pgx.Tx) error {
|
|
if _, err := tx.Exec(ctx,
|
|
`SELECT set_config('app.org_id', $1, true), set_config('app.user_id', $2, true), set_config('app.scope', $3, true)`,
|
|
idOrEmpty(s.OrgID), idOrEmpty(s.UserID), scopeName(s),
|
|
); err != nil {
|
|
return fmt.Errorf("tenant: %w", err)
|
|
}
|
|
return fn(store.New(tx))
|
|
})
|
|
}
|
|
|
|
func idOrEmpty(id uuid.UUID) string {
|
|
if id == uuid.Nil {
|
|
return ""
|
|
}
|
|
return id.String()
|
|
}
|
|
|
|
func scopeName(s Scope) string {
|
|
if s.system {
|
|
return "system"
|
|
}
|
|
return ""
|
|
}
|