Files
base/apis/collection.go
zeekay 7419d13323 A member reads the org's schema, and a grow keeps an index it already has
A client draws a record by its schema, a field's label and a select
value's colour, so every member of the org reads the org's own
collections. Changing them stays an admin's, and Base's own tables stay
hidden from a member.

A module that indexes a column the org already indexed under another
name no longer fails the install: the index is there.
2026-10-18 21:29:25 -07:00

302 lines
9.8 KiB
Go

package apis
import (
"errors"
"net/http"
"strings"
validation "github.com/go-ozzo/ozzo-validation/v4"
"github.com/hanzoai/base/core"
"github.com/hanzoai/base/tools/router"
"github.com/hanzoai/base/tools/search"
"github.com/hanzoai/base/tools/security"
"github.com/hanzoai/dbx"
)
// bindCollectionApi registers the collection api endpoints and the corresponding handlers.
func bindCollectionApi(app core.App, rg *router.RouterGroup[*core.RequestEvent]) {
// A superuser, or an org admin in its own org's Base: the org's schema is
// the org's to change. Which collections an org admin may touch is each
// route's to ask (refuseUnmanageable); a token secret is not among them.
//
// Reading it is every member's: a client draws a record by its schema (a
// field's label, a select value's colour), so a member who could not read
// it could not be shown the org's own data.
subGroup := rg.Group("/collections")
subGroup.GET("", collectionsList).Bind(RequireSchemaReadAuth())
subGroup.POST("", collectionCreate).Bind(RequireSchemaAuth())
subGroup.GET("/{collection}", collectionView).Bind(RequireSchemaReadAuth())
subGroup.PATCH("/{collection}", collectionUpdate).Bind(RequireSchemaAuth())
subGroup.POST("/{collection}/rotate", collectionRotate).Bind(RequireSuperuserAuth())
subGroup.DELETE("/{collection}", collectionDelete).Bind(RequireSchemaAuth())
subGroup.DELETE("/{collection}/truncate", collectionTruncate).Bind(RequireSchemaAuth())
subGroup.PUT("/import", collectionsImport).Bind(RequireSchemaAuth())
subGroup.GET("/meta/scaffolds", collectionScaffolds).Bind(RequireSchemaAuth())
}
// readsBasesOwn reports whether a request may read the collections Base keeps for
// itself (system collections and the underscore-named tables): a superuser's and
// an org admin's, never a member's.
func readsBasesOwn(e *core.RequestEvent) bool {
return e.HasSuperuserAuth() || IsOrgAdmin(e)
}
func collectionsList(e *core.RequestEvent) error {
fieldResolver := search.NewSimpleFieldResolver(
e.App.Dialect(),
"id", "created", "updated", "name", "system", "type",
)
collections := []*core.Collection{}
query := e.App.CollectionQuery()
if !readsBasesOwn(e) {
query.AndWhere(dbx.NewExp("[[system]] = {:no} AND substr([[name]], 1, 1) != '_'", dbx.Params{"no": false}))
}
result, err := search.NewProvider(fieldResolver).
Query(query).
ParseAndExec(e.Request.URL.Query().Encode(), &collections)
if err != nil {
return e.BadRequestError("", err)
}
event := new(core.CollectionsListRequestEvent)
event.RequestEvent = e
event.Collections = collections
event.Result = result
return event.App.OnCollectionsListRequest().Trigger(event, func(e *core.CollectionsListRequestEvent) error {
return execAfterSuccessTx(true, e.App, func() error {
return e.JSON(http.StatusOK, e.Result)
})
})
}
func collectionView(e *core.RequestEvent) error {
collection, err := e.App.FindCachedCollectionByNameOrId(e.Request.PathValue("collection"))
if err != nil || collection == nil {
return e.NotFoundError("", err)
}
if !readsBasesOwn(e) && (collection.System || strings.HasPrefix(collection.Name, "_")) {
return e.NotFoundError("", nil)
}
event := new(core.CollectionRequestEvent)
event.RequestEvent = e
event.Collection = collection
return e.App.OnCollectionViewRequest().Trigger(event, func(e *core.CollectionRequestEvent) error {
return execAfterSuccessTx(true, e.App, func() error {
return e.JSON(http.StatusOK, e.Collection)
})
})
}
func collectionCreate(e *core.RequestEvent) error {
// populate the minimal required factory collection data (if any)
factoryExtract := struct {
Type string `form:"type" json:"type"`
Name string `form:"name" json:"name"`
}{}
if err := e.BindBody(&factoryExtract); err != nil {
return e.BadRequestError("Failed to load the collection type data due to invalid formatting.", err)
}
// create scaffold
collection := core.NewCollection(factoryExtract.Type, factoryExtract.Name)
// merge the scaffold with the submitted request data
if err := e.BindBody(collection); err != nil {
return e.BadRequestError("Failed to load the submitted data due to invalid formatting.", err)
}
if err := refuseUnmanageable(e, "create", collection); err != nil {
return err
}
event := new(core.CollectionRequestEvent)
event.RequestEvent = e
event.Collection = collection
return e.App.OnCollectionCreateRequest().Trigger(event, func(e *core.CollectionRequestEvent) error {
if err := refuseUnmanageable(e.RequestEvent, "create", e.Collection); err != nil {
return err
}
if err := e.App.Save(e.Collection); err != nil {
// validation failure
var validationErrors validation.Errors
if errors.As(err, &validationErrors) {
return e.BadRequestError("Failed to create collection.", validationErrors)
}
// other generic db error
return e.BadRequestError("Failed to create collection. Raw error: \n"+err.Error(), nil)
}
logOrgAdminSchemaChange(e.RequestEvent, "create", e.Collection.Name)
return execAfterSuccessTx(true, e.App, func() error {
return e.JSON(http.StatusOK, e.Collection)
})
})
}
func collectionUpdate(e *core.RequestEvent) error {
collection, err := e.App.FindCollectionByNameOrId(e.Request.PathValue("collection"))
if err != nil || collection == nil {
return e.NotFoundError("", err)
}
if err := refuseUnmanageable(e, "change", collection); err != nil {
return err
}
if err := e.BindBody(collection); err != nil {
return e.BadRequestError("Failed to load the submitted data due to invalid formatting.", err)
}
// and as the change would leave it
if err := refuseUnmanageable(e, "change", collection); err != nil {
return err
}
event := new(core.CollectionRequestEvent)
event.RequestEvent = e
event.Collection = collection
return event.App.OnCollectionUpdateRequest().Trigger(event, func(e *core.CollectionRequestEvent) error {
if err := refuseUnmanageable(e.RequestEvent, "change", e.Collection); err != nil {
return err
}
if err := e.App.Save(e.Collection); err != nil {
// validation failure
var validationErrors validation.Errors
if errors.As(err, &validationErrors) {
return e.BadRequestError("Failed to update collection.", validationErrors)
}
// other generic db error
return e.BadRequestError("Failed to update collection. Raw error: \n"+err.Error(), nil)
}
logOrgAdminSchemaChange(e.RequestEvent, "update", e.Collection.Name)
return execAfterSuccessTx(true, e.App, func() error {
return e.JSON(http.StatusOK, e.Collection)
})
})
}
// collectionRotate mints a fresh signing secret for every token the collection
// issues. A secret is server material, so replacing one is a request that
// carries no value; every token already issued stops verifying.
func collectionRotate(e *core.RequestEvent) error {
collection, err := e.App.FindCollectionByNameOrId(e.Request.PathValue("collection"))
if err != nil || collection == nil {
return e.NotFoundError("", err)
}
if !collection.IsAuth() {
return e.BadRequestError("Only auth collections issue tokens.", nil)
}
collection.RotateTokenSecrets()
event := new(core.CollectionRequestEvent)
event.RequestEvent = e
event.Collection = collection
return event.App.OnCollectionUpdateRequest().Trigger(event, func(e *core.CollectionRequestEvent) error {
if err := e.App.Save(e.Collection); err != nil {
return e.BadRequestError("Failed to rotate the collection token secrets.", err)
}
return execAfterSuccessTx(true, e.App, func() error {
return e.JSON(http.StatusOK, e.Collection)
})
})
}
func collectionDelete(e *core.RequestEvent) error {
collection, err := e.App.FindCachedCollectionByNameOrId(e.Request.PathValue("collection"))
if err != nil || collection == nil {
return e.NotFoundError("", err)
}
if err := refuseUnmanageable(e, "delete", collection); err != nil {
return err
}
event := new(core.CollectionRequestEvent)
event.RequestEvent = e
event.Collection = collection
return e.App.OnCollectionDeleteRequest().Trigger(event, func(e *core.CollectionRequestEvent) error {
if err := e.App.Delete(e.Collection); err != nil {
msg := "Failed to delete collection"
// check fo references
refs, _ := e.App.FindCollectionReferences(e.Collection, e.Collection.Id)
if len(refs) > 0 {
names := make([]string, 0, len(refs))
for ref := range refs {
names = append(names, ref.Name)
}
msg += " probably due to existing reference in " + strings.Join(names, ", ")
}
return e.BadRequestError(msg, err)
}
logOrgAdminSchemaChange(e.RequestEvent, "delete", e.Collection.Name)
return execAfterSuccessTx(true, e.App, func() error {
return e.NoContent(http.StatusNoContent)
})
})
}
func collectionTruncate(e *core.RequestEvent) error {
collection, err := e.App.FindCachedCollectionByNameOrId(e.Request.PathValue("collection"))
if err != nil || collection == nil {
return e.NotFoundError("", err)
}
if collection.IsView() {
return e.BadRequestError("View collections cannot be truncated since they don't store their own records.", nil)
}
if err := refuseUnmanageable(e, "truncate", collection); err != nil {
return err
}
err = e.App.TruncateCollection(collection)
if err != nil {
return e.BadRequestError("Failed to truncate collection (most likely due to required cascade delete record references).", err)
}
logOrgAdminSchemaChange(e, "truncate", collection.Name)
return e.NoContent(http.StatusNoContent)
}
func collectionScaffolds(e *core.RequestEvent) error {
randomId := security.RandomStringWithAlphabet(10, core.DefaultIdAlphabet) // could be used as part of the default indexes name
collections := map[string]*core.Collection{
core.CollectionTypeBase: core.NewBaseCollection("", randomId),
core.CollectionTypeAuth: core.NewAuthCollection("", randomId),
core.CollectionTypeView: core.NewViewCollection("", randomId),
}
for _, c := range collections {
c.Id = "" // clear random id
}
return e.JSON(http.StatusOK, collections)
}