Workspace admins create groups of members, and space admins grant a role to a whole group. A member's space role is now the highest of their own grant and their groups' grants. Leaving a workspace drops its group memberships, and deleting a group removes its space grants (they are not a real relation, so PocketBase cannot cascade them). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
388 lines
12 KiB
Go
388 lines
12 KiB
Go
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
|
|
package directory
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"sort"
|
|
"strings"
|
|
|
|
"docwell/server/internal/access"
|
|
"docwell/server/internal/apperr"
|
|
"docwell/server/internal/store/pocketbase"
|
|
)
|
|
|
|
// ---- Spaces ----------------------------------------------------------------
|
|
|
|
type Space struct {
|
|
ID string `json:"id"`
|
|
Workspace string `json:"workspace"`
|
|
Name string `json:"name"`
|
|
Slug string `json:"slug"`
|
|
Icon string `json:"icon"`
|
|
Description string `json:"description"`
|
|
Visibility string `json:"visibility"`
|
|
DefaultRole string `json:"defaultRole"`
|
|
// Role is the caller's effective space role after the cascade.
|
|
Role string `json:"role"`
|
|
Created string `json:"created"`
|
|
}
|
|
|
|
type spaceRecord struct {
|
|
ID string `json:"id"`
|
|
Workspace string `json:"workspace"`
|
|
Name string `json:"name"`
|
|
Slug string `json:"slug"`
|
|
Icon string `json:"icon"`
|
|
Description string `json:"description"`
|
|
Visibility string `json:"visibility"`
|
|
DefaultRole string `json:"default_role"`
|
|
Created string `json:"created"`
|
|
}
|
|
|
|
func (r spaceRecord) view(role string) Space {
|
|
def := r.DefaultRole
|
|
if !access.ValidDefaultRole(def) {
|
|
def = access.SpaceEditor
|
|
}
|
|
return Space{
|
|
ID: r.ID, Workspace: r.Workspace, Name: r.Name, Slug: r.Slug, Icon: r.Icon, Description: r.Description,
|
|
Visibility: r.Visibility, DefaultRole: def, Role: role, Created: r.Created,
|
|
}
|
|
}
|
|
|
|
type spaceMemberRecord struct {
|
|
ID string `json:"id"`
|
|
Space string `json:"space"`
|
|
PrincipalID string `json:"principal_id"`
|
|
Role string `json:"role"`
|
|
}
|
|
|
|
// listAll pages through a whole collection query (PocketBase caps a page at 1000 records).
|
|
func listAll[T any](ctx context.Context, s *Service, collection string, opts pocketbase.ListOptions) ([]T, error) {
|
|
opts.PerPage = 1000
|
|
var out []T
|
|
for page := 1; ; page++ {
|
|
opts.Page = page
|
|
res, err := pocketbase.List[T](ctx, s.pb, collection, opts)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
out = append(out, res.Items...)
|
|
if page >= res.TotalPages || len(res.Items) == 0 {
|
|
return out, nil
|
|
}
|
|
}
|
|
}
|
|
|
|
// userSpaceMemberships lists a user's space memberships, in one workspace or ("" ) all.
|
|
func (s *Service) userSpaceMemberships(ctx context.Context, userID, wsID string) ([]spaceMemberRecord, error) {
|
|
filter := fmt.Sprintf("principal_type = 'user' && principal_id = '%s'", userID)
|
|
if wsID != "" {
|
|
filter += fmt.Sprintf(" && space.workspace = '%s'", wsID)
|
|
}
|
|
return listAll[spaceMemberRecord](ctx, s, "space_members", pocketbase.ListOptions{Filter: filter})
|
|
}
|
|
|
|
func (s *Service) spaceMembership(ctx context.Context, spaceID, userID string) (spaceMemberRecord, error) {
|
|
res, err := pocketbase.List[spaceMemberRecord](ctx, s.pb, "space_members", pocketbase.ListOptions{
|
|
PerPage: 1, Filter: fmt.Sprintf("space = '%s' && principal_type = 'user' && principal_id = '%s'", spaceID, userID),
|
|
})
|
|
if err != nil || len(res.Items) == 0 {
|
|
return spaceMemberRecord{}, err
|
|
}
|
|
return res.Items[0], nil
|
|
}
|
|
|
|
// spaceAccess is a space with the caller's workspace and space roles.
|
|
type spaceAccess struct {
|
|
space spaceRecord
|
|
ws workspaceRecord
|
|
wsRole string
|
|
role string
|
|
}
|
|
|
|
// spaceFor loads a space with c's roles. A space c cannot open is reported as
|
|
// not found, like a workspace.
|
|
func (s *Service) spaceFor(ctx context.Context, c access.Caller, id string) (spaceAccess, error) {
|
|
if !validID(id) {
|
|
return spaceAccess{}, apperr.NotFound("space not found")
|
|
}
|
|
sp, err := pocketbase.Get[spaceRecord](ctx, s.pb, "spaces", id)
|
|
if err != nil {
|
|
return spaceAccess{}, mapPB(err, "space not found")
|
|
}
|
|
ws, err := s.getWorkspace(ctx, sp.Workspace)
|
|
if err != nil {
|
|
return spaceAccess{}, err
|
|
}
|
|
wsRole, err := s.effective(ctx, c, ws)
|
|
if err != nil {
|
|
return spaceAccess{}, err
|
|
}
|
|
var explicit string
|
|
if wsRole != "" && !access.AtLeast(wsRole, access.WorkspaceAdmin) {
|
|
if explicit, err = s.explicitSpaceRole(ctx, sp, c.ID); err != nil {
|
|
return spaceAccess{}, err
|
|
}
|
|
}
|
|
a := spaceAccess{space: sp, ws: ws, wsRole: wsRole, role: access.SpaceRole(wsRole, sp.Visibility, sp.DefaultRole, explicit)}
|
|
if err := access.ViewSpace(a.role); err != nil {
|
|
return spaceAccess{}, err
|
|
}
|
|
return a, nil
|
|
}
|
|
|
|
// ListSpaces lists the spaces of a workspace that c can open.
|
|
func (s *Service) ListSpaces(ctx context.Context, c access.Caller, wsID string) ([]Space, error) {
|
|
ws, wsRole, err := s.workspaceFor(ctx, c, wsID)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
spaces, err := listAll[spaceRecord](ctx, s, "spaces", pocketbase.ListOptions{
|
|
Filter: fmt.Sprintf("workspace = '%s'", ws.ID), Sort: "name",
|
|
})
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
explicit := map[string]string{}
|
|
if !access.AtLeast(wsRole, access.WorkspaceAdmin) {
|
|
mine, err := s.userSpaceMemberships(ctx, c.ID, ws.ID)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
for _, m := range mine {
|
|
explicit[m.Space] = m.Role
|
|
}
|
|
groups, err := s.userGroups(ctx, c.ID, ws.ID)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
grants, err := s.groupGrants(ctx, groups, "")
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
for _, g := range grants {
|
|
explicit[g.Space] = access.HigherSpaceRole(explicit[g.Space], g.Role)
|
|
}
|
|
}
|
|
out := []Space{}
|
|
for _, sp := range spaces {
|
|
if role := access.SpaceRole(wsRole, sp.Visibility, sp.DefaultRole, explicit[sp.ID]); role != "" {
|
|
out = append(out, sp.view(role))
|
|
}
|
|
}
|
|
sort.SliceStable(out, func(i, j int) bool { return strings.ToLower(out[i].Name) < strings.ToLower(out[j].Name) })
|
|
return out, nil
|
|
}
|
|
|
|
// GetSpace returns one space with c's role.
|
|
func (s *Service) GetSpace(ctx context.Context, c access.Caller, id string) (Space, error) {
|
|
a, err := s.spaceFor(ctx, c, id)
|
|
if err != nil {
|
|
return Space{}, err
|
|
}
|
|
return a.space.view(a.role), nil
|
|
}
|
|
|
|
type CreateSpaceInput struct {
|
|
Name string `json:"name"`
|
|
Description string `json:"description"`
|
|
Icon string `json:"icon"`
|
|
Visibility string `json:"visibility"`
|
|
}
|
|
|
|
// CreateSpace creates a space in a workspace (workspace admin or above).
|
|
func (s *Service) CreateSpace(ctx context.Context, c access.Caller, wsID string, in CreateSpaceInput) (Space, error) {
|
|
name, err := cleanName(in.Name, "Space")
|
|
if err != nil {
|
|
return Space{}, err
|
|
}
|
|
visibility := in.Visibility
|
|
if visibility == "" {
|
|
visibility = access.SpaceOpen
|
|
}
|
|
if visibility != access.SpaceOpen && visibility != access.SpacePrivate {
|
|
return Space{}, apperr.InvalidFields(map[string]string{"visibility": "Visibility must be open or private."})
|
|
}
|
|
ws, wsRole, err := s.workspaceFor(ctx, c, wsID)
|
|
if err != nil {
|
|
return Space{}, err
|
|
}
|
|
if err := access.CreateSpace(wsRole); err != nil {
|
|
return Space{}, err
|
|
}
|
|
base := slugify(name, "space")
|
|
for i := 1; i <= 50; i++ {
|
|
slug := base
|
|
if i > 1 {
|
|
slug = fmt.Sprintf("%s-%d", base, i)
|
|
}
|
|
rec, err := pocketbase.Create[spaceRecord](ctx, s.pb, "spaces", map[string]any{
|
|
"workspace": ws.ID, "name": name, "slug": slug, "icon": strings.TrimSpace(in.Icon),
|
|
"description": strings.TrimSpace(in.Description), "visibility": visibility, "default_role": access.SpaceEditor,
|
|
})
|
|
var pbErr *pocketbase.Error
|
|
if errors.As(err, &pbErr) && pbErr.Data["slug"].Code == "validation_not_unique" {
|
|
continue
|
|
}
|
|
if err != nil {
|
|
return Space{}, mapPB(err, "space not found")
|
|
}
|
|
return rec.view(access.SpaceAdmin), nil
|
|
}
|
|
return Space{}, apperr.Conflict("could not find a free space address; try another name")
|
|
}
|
|
|
|
// UpdateSpaceInput changes only the fields that are set.
|
|
type UpdateSpaceInput struct {
|
|
Name *string `json:"name"`
|
|
Description *string `json:"description"`
|
|
Icon *string `json:"icon"`
|
|
Visibility *string `json:"visibility"`
|
|
DefaultRole *string `json:"defaultRole"`
|
|
}
|
|
|
|
// UpdateSpace changes a space's settings (space admin).
|
|
func (s *Service) UpdateSpace(ctx context.Context, c access.Caller, id string, in UpdateSpaceInput) (Space, error) {
|
|
a, err := s.spaceFor(ctx, c, id)
|
|
if err != nil {
|
|
return Space{}, err
|
|
}
|
|
if err := access.ManageSpace(a.role); err != nil {
|
|
return Space{}, err
|
|
}
|
|
patch := map[string]any{}
|
|
if in.Name != nil {
|
|
name, err := cleanName(*in.Name, "Space")
|
|
if err != nil {
|
|
return Space{}, err
|
|
}
|
|
patch["name"] = name
|
|
}
|
|
if in.Description != nil {
|
|
patch["description"] = strings.TrimSpace(*in.Description)
|
|
}
|
|
if in.Icon != nil {
|
|
patch["icon"] = strings.TrimSpace(*in.Icon)
|
|
}
|
|
if in.Visibility != nil {
|
|
if *in.Visibility != access.SpaceOpen && *in.Visibility != access.SpacePrivate {
|
|
return Space{}, apperr.InvalidFields(map[string]string{"visibility": "Visibility must be open or private."})
|
|
}
|
|
patch["visibility"] = *in.Visibility
|
|
}
|
|
if in.DefaultRole != nil {
|
|
if !access.ValidDefaultRole(*in.DefaultRole) {
|
|
return Space{}, apperr.InvalidFields(map[string]string{"defaultRole": "Default role must be editor, commenter or viewer."})
|
|
}
|
|
patch["default_role"] = *in.DefaultRole
|
|
}
|
|
if len(patch) == 0 {
|
|
return a.space.view(a.role), nil
|
|
}
|
|
rec, err := pocketbase.Update[spaceRecord](ctx, s.pb, "spaces", a.space.ID, patch)
|
|
if err != nil {
|
|
return Space{}, mapPB(err, "space not found")
|
|
}
|
|
return rec.view(a.role), nil
|
|
}
|
|
|
|
// DeleteSpace deletes a space with all of its pages (workspace admin).
|
|
func (s *Service) DeleteSpace(ctx context.Context, c access.Caller, id string) error {
|
|
a, err := s.spaceFor(ctx, c, id)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if err := access.DeleteSpace(a.wsRole); err != nil {
|
|
return err
|
|
}
|
|
return mapPB(s.pb.Delete(ctx, "spaces", a.space.ID), "space not found")
|
|
}
|
|
|
|
// ListSpaceMembers lists a space's explicit members (any space role may look).
|
|
// Workspace admins manage every space without being listed.
|
|
func (s *Service) ListSpaceMembers(ctx context.Context, c access.Caller, id string) ([]Member, error) {
|
|
a, err := s.spaceFor(ctx, c, id)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
members, err := listAll[spaceMemberRecord](ctx, s, "space_members", pocketbase.ListOptions{
|
|
Filter: fmt.Sprintf("space = '%s' && principal_type = 'user'", a.space.ID),
|
|
})
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
out := make([]Member, 0, len(members))
|
|
for _, m := range members {
|
|
u, err := s.getUser(ctx, m.PrincipalID)
|
|
if err != nil {
|
|
continue // a deleted user's leftover row
|
|
}
|
|
out = append(out, Member{User: MemberUser{ID: u.ID, Email: u.Email, Name: u.Name}, Role: m.Role})
|
|
}
|
|
sort.Slice(out, func(i, j int) bool { return out[i].User.Email < out[j].User.Email })
|
|
return out, nil
|
|
}
|
|
|
|
// SetSpaceMember adds a workspace member (by email) to a space or changes their role (space admin).
|
|
func (s *Service) SetSpaceMember(ctx context.Context, c access.Caller, id, email, role string) (Member, error) {
|
|
a, err := s.spaceFor(ctx, c, id)
|
|
if err != nil {
|
|
return Member{}, err
|
|
}
|
|
if err := access.ManageSpace(a.role); err != nil {
|
|
return Member{}, err
|
|
}
|
|
u, err := s.findUserByEmail(ctx, email)
|
|
if err != nil {
|
|
return Member{}, err
|
|
}
|
|
targetWsRole, err := s.effective(ctx, u.Caller(), a.ws)
|
|
if err != nil {
|
|
return Member{}, err
|
|
}
|
|
if err := access.SetSpaceMember(a.role, targetWsRole, role); err != nil {
|
|
return Member{}, err
|
|
}
|
|
current, err := s.spaceMembership(ctx, a.space.ID, u.ID)
|
|
if err != nil {
|
|
return Member{}, err
|
|
}
|
|
if current.ID != "" {
|
|
_, err = pocketbase.Update[spaceMemberRecord](ctx, s.pb, "space_members", current.ID, map[string]any{"role": role})
|
|
} else {
|
|
_, err = pocketbase.Create[spaceMemberRecord](ctx, s.pb, "space_members", map[string]any{
|
|
"space": a.space.ID, "principal_type": "user", "principal_id": u.ID, "role": role,
|
|
})
|
|
}
|
|
if err != nil {
|
|
return Member{}, mapPB(err, "space not found")
|
|
}
|
|
return Member{User: MemberUser{ID: u.ID, Email: u.Email, Name: u.Name}, Role: role}, nil
|
|
}
|
|
|
|
// RemoveSpaceMember removes a space membership (idempotent). Anyone may leave;
|
|
// removing others needs space admin.
|
|
func (s *Service) RemoveSpaceMember(ctx context.Context, c access.Caller, id, userID string) error {
|
|
a, err := s.spaceFor(ctx, c, id)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if userID != c.ID {
|
|
if err := access.ManageSpace(a.role); err != nil {
|
|
return err
|
|
}
|
|
}
|
|
if !validID(userID) {
|
|
return apperr.NotFound("member not found")
|
|
}
|
|
current, err := s.spaceMembership(ctx, a.space.ID, userID)
|
|
if err != nil || current.ID == "" {
|
|
return err
|
|
}
|
|
return mapPB(s.pb.Delete(ctx, "space_members", current.ID), "member not found")
|
|
}
|