docwell-server converts between page documents and Markdown or HTML (a new convert package), so every client and the API get the same results. Pages export as a download from the page menu; spaces import one page per .md, .txt or .html file, taking a leading level-1 heading as the title. Import keeps only what the editor schema knows, which drops scripts, styles, event handlers and javascript: links; tables become one paragraph per row until the editor has tables. The UI package gains DwMenu, a small accessible action menu. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
872 lines
27 KiB
Go
872 lines
27 KiB
Go
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
|
|
// Package directory manages users, organizations, workspaces, spaces, pages
|
|
// and their memberships in PocketBase. Every action asks the access package
|
|
// first; this package only loads the facts those rules need and applies the
|
|
// result.
|
|
package directory
|
|
|
|
import (
|
|
"context"
|
|
"errors"
|
|
"fmt"
|
|
"net/http"
|
|
"regexp"
|
|
"sort"
|
|
"strings"
|
|
|
|
"docwell/server/internal/access"
|
|
"docwell/server/internal/apperr"
|
|
"docwell/server/internal/auth"
|
|
"docwell/server/internal/store/pocketbase"
|
|
)
|
|
|
|
type Service struct {
|
|
pb *pocketbase.Client
|
|
// forget drops a user's cached token checks after their rights change.
|
|
forget func(userID string)
|
|
docs Docs
|
|
mailer Mailer
|
|
// maxUpload caps one attachment in bytes (0 = 50 MB).
|
|
maxUpload int64
|
|
search Searcher
|
|
publicURL string
|
|
}
|
|
|
|
func New(pb *pocketbase.Client, forget func(userID string), docs Docs) *Service {
|
|
if forget == nil {
|
|
forget = func(string) {}
|
|
}
|
|
return &Service{pb: pb, forget: forget, docs: docs}
|
|
}
|
|
|
|
// PocketBase record ids are short alphanumerics; anything else is rejected
|
|
// before it can reach a filter expression.
|
|
var idPattern = regexp.MustCompile(`^[A-Za-z0-9_-]{1,64}$`)
|
|
|
|
func validID(id string) bool { return idPattern.MatchString(id) }
|
|
|
|
// filterValue keeps free text from breaking out of a filter string literal.
|
|
func filterValue(s string) string {
|
|
return strings.Map(func(r rune) rune {
|
|
switch r {
|
|
case '\'', '"', '\\', '`':
|
|
return -1
|
|
}
|
|
return r
|
|
}, strings.TrimSpace(s))
|
|
}
|
|
|
|
// mapPB turns PocketBase errors into apperr errors.
|
|
func mapPB(err error, notFound string) error {
|
|
var pbErr *pocketbase.Error
|
|
if !errors.As(err, &pbErr) {
|
|
return err
|
|
}
|
|
switch {
|
|
case pbErr.Status == http.StatusNotFound:
|
|
return apperr.NotFound(notFound)
|
|
case pbErr.Status == http.StatusBadRequest && len(pbErr.Data) > 0:
|
|
fields := map[string]string{}
|
|
for k, v := range pbErr.Data {
|
|
if k != "passwordConfirm" {
|
|
fields[k] = v.Message
|
|
}
|
|
}
|
|
return apperr.InvalidFields(fields)
|
|
}
|
|
return err
|
|
}
|
|
|
|
func cleanName(name, what string) (string, error) {
|
|
name = strings.TrimSpace(name)
|
|
switch {
|
|
case name == "":
|
|
return "", apperr.InvalidFields(map[string]string{"name": what + " name is required."})
|
|
case len(name) > 120:
|
|
return "", apperr.InvalidFields(map[string]string{"name": what + " name is too long (max 120)."})
|
|
}
|
|
return name, nil
|
|
}
|
|
|
|
// ---- Users -----------------------------------------------------------------
|
|
|
|
func (s *Service) getUser(ctx context.Context, id string) (auth.User, error) {
|
|
if !validID(id) {
|
|
return auth.User{}, apperr.NotFound("user not found")
|
|
}
|
|
rec, err := pocketbase.GetExpand[auth.UserRecord](ctx, s.pb, "users", id, "organization")
|
|
if err != nil {
|
|
return auth.User{}, mapPB(err, "user not found")
|
|
}
|
|
return rec.User(), nil
|
|
}
|
|
|
|
func target(u auth.User) access.Target {
|
|
return access.Target{ID: u.ID, Role: u.Role, OrgID: u.Organization}
|
|
}
|
|
|
|
type UserList struct {
|
|
Items []auth.User `json:"items"`
|
|
Page int `json:"page"`
|
|
PerPage int `json:"perPage"`
|
|
TotalItems int `json:"totalItems"`
|
|
}
|
|
|
|
type ListUsersInput struct {
|
|
Page int
|
|
PerPage int
|
|
Search string
|
|
// Organization narrows a superadmin's list; "none" = users without one.
|
|
Organization string
|
|
}
|
|
|
|
// ListUsers lists the users c may manage: everyone for a superadmin, their
|
|
// own organization for an admin.
|
|
func (s *Service) ListUsers(ctx context.Context, c access.Caller, in ListUsersInput) (UserList, error) {
|
|
all, org, err := access.UserScope(c)
|
|
if err != nil {
|
|
return UserList{}, err
|
|
}
|
|
if !all && org == "" {
|
|
return UserList{Items: []auth.User{}, Page: 1, PerPage: in.PerPage}, nil
|
|
}
|
|
|
|
var filters []string
|
|
switch {
|
|
case !all:
|
|
filters = append(filters, fmt.Sprintf("organization = '%s'", org))
|
|
case in.Organization == "none":
|
|
filters = append(filters, "organization = ''")
|
|
case in.Organization != "":
|
|
if !validID(in.Organization) {
|
|
return UserList{}, apperr.Invalid("invalid organization id")
|
|
}
|
|
filters = append(filters, fmt.Sprintf("organization = '%s'", in.Organization))
|
|
}
|
|
if q := filterValue(in.Search); q != "" {
|
|
filters = append(filters, fmt.Sprintf("(email ~ '%s' || name ~ '%s')", q, q))
|
|
}
|
|
|
|
opts := pocketbase.ListOptions{Page: in.Page, PerPage: in.PerPage, Sort: "email", Filter: strings.Join(filters, " && "), Expand: "organization"}
|
|
res, err := pocketbase.List[auth.UserRecord](ctx, s.pb, "users", opts)
|
|
if err != nil {
|
|
return UserList{}, err
|
|
}
|
|
out := UserList{Items: make([]auth.User, 0, len(res.Items)), Page: res.Page, PerPage: res.PerPage, TotalItems: res.TotalItems}
|
|
for _, r := range res.Items {
|
|
out.Items = append(out.Items, r.User())
|
|
}
|
|
return out, nil
|
|
}
|
|
|
|
type CreateUserInput struct {
|
|
Email string `json:"email"`
|
|
Password string `json:"password"`
|
|
Name string `json:"name"`
|
|
Role string `json:"role"`
|
|
Organization string `json:"organization"`
|
|
}
|
|
|
|
// CreateUser adds an account. Admins create inside their own organization
|
|
// only; superadmins pick any organization (or none) and any role.
|
|
func (s *Service) CreateUser(ctx context.Context, c access.Caller, in CreateUserInput) (auth.User, error) {
|
|
email := strings.ToLower(strings.TrimSpace(in.Email))
|
|
fields := map[string]string{}
|
|
if !strings.Contains(email, "@") {
|
|
fields["email"] = "A valid email is required."
|
|
}
|
|
if strings.TrimSpace(in.Name) == "" {
|
|
fields["name"] = "Name is required."
|
|
}
|
|
if len(in.Password) < 8 {
|
|
fields["password"] = "Password must be at least 8 characters."
|
|
}
|
|
role, ok := access.NormalizeRole(in.Role)
|
|
if !ok {
|
|
fields["role"] = "Role must be user, admin or superadmin."
|
|
}
|
|
if len(fields) > 0 {
|
|
return auth.User{}, apperr.InvalidFields(fields)
|
|
}
|
|
|
|
org, err := access.CreateUser(c, role, strings.TrimSpace(in.Organization))
|
|
if err != nil {
|
|
return auth.User{}, err
|
|
}
|
|
if org != "" {
|
|
if _, err := s.getOrg(ctx, org); err != nil {
|
|
return auth.User{}, err
|
|
}
|
|
}
|
|
|
|
rec, err := pocketbase.Create[auth.UserRecord](ctx, s.pb, "users", map[string]any{
|
|
"email": email,
|
|
"password": in.Password,
|
|
"passwordConfirm": in.Password,
|
|
"name": strings.TrimSpace(in.Name),
|
|
"role": role,
|
|
"organization": org,
|
|
"status": "active",
|
|
// An account a manager creates is trusted; there is no inbox to prove.
|
|
"verified": true,
|
|
"emailVisibility": false,
|
|
})
|
|
if err != nil {
|
|
return auth.User{}, mapPB(err, "user not found")
|
|
}
|
|
return s.getUser(ctx, rec.ID)
|
|
}
|
|
|
|
type UpdateUserInput struct {
|
|
Email *string `json:"email"`
|
|
Name *string `json:"name"`
|
|
Role *string `json:"role"`
|
|
Password *string `json:"password"`
|
|
Status *string `json:"status"`
|
|
Verified *bool `json:"verified"`
|
|
Organization *string `json:"organization"`
|
|
}
|
|
|
|
// UpdateUser edits any subset of a user's fields, within c's rights.
|
|
func (s *Service) UpdateUser(ctx context.Context, c access.Caller, id string, in UpdateUserInput) (auth.User, error) {
|
|
t, err := s.getUser(ctx, id)
|
|
if err != nil {
|
|
return auth.User{}, err
|
|
}
|
|
if err := access.ManageUser(c, target(t)); err != nil {
|
|
return auth.User{}, err
|
|
}
|
|
|
|
patch := map[string]any{}
|
|
if in.Email != nil {
|
|
email := strings.ToLower(strings.TrimSpace(*in.Email))
|
|
if !strings.Contains(email, "@") {
|
|
return auth.User{}, apperr.InvalidFields(map[string]string{"email": "A valid email is required."})
|
|
}
|
|
patch["email"] = email
|
|
}
|
|
if in.Name != nil {
|
|
name := strings.TrimSpace(*in.Name)
|
|
if name == "" {
|
|
return auth.User{}, apperr.InvalidFields(map[string]string{"name": "Name is required."})
|
|
}
|
|
patch["name"] = name
|
|
}
|
|
if in.Role != nil {
|
|
role, ok := access.NormalizeRole(*in.Role)
|
|
if !ok {
|
|
return auth.User{}, apperr.InvalidFields(map[string]string{"role": "Role must be user, admin or superadmin."})
|
|
}
|
|
if err := access.ChangeRole(c, target(t), role); err != nil {
|
|
return auth.User{}, err
|
|
}
|
|
patch["role"] = role
|
|
}
|
|
if in.Password != nil {
|
|
if len(*in.Password) < 8 {
|
|
return auth.User{}, apperr.InvalidFields(map[string]string{"password": "Password must be at least 8 characters."})
|
|
}
|
|
patch["password"] = *in.Password
|
|
patch["passwordConfirm"] = *in.Password
|
|
}
|
|
if in.Status != nil {
|
|
switch *in.Status {
|
|
case "active", "disabled", "invited":
|
|
default:
|
|
return auth.User{}, apperr.InvalidFields(map[string]string{"status": "Status must be active, disabled or invited."})
|
|
}
|
|
if c.ID == t.ID && *in.Status != "active" {
|
|
return auth.User{}, apperr.Invalid("you cannot disable your own account")
|
|
}
|
|
patch["status"] = *in.Status
|
|
}
|
|
if in.Verified != nil {
|
|
patch["verified"] = *in.Verified
|
|
}
|
|
moved := false
|
|
if in.Organization != nil {
|
|
org := strings.TrimSpace(*in.Organization)
|
|
if org != "" && !validID(org) {
|
|
return auth.User{}, apperr.Invalid("invalid organization id")
|
|
}
|
|
if err := access.MoveUser(c, target(t), org); err != nil {
|
|
return auth.User{}, err
|
|
}
|
|
if org != t.Organization {
|
|
if org != "" {
|
|
if _, err := s.getOrg(ctx, org); err != nil {
|
|
return auth.User{}, err
|
|
}
|
|
}
|
|
patch["organization"] = org
|
|
moved = true
|
|
}
|
|
}
|
|
if len(patch) == 0 {
|
|
return auth.User{}, apperr.Invalid("no changes provided")
|
|
}
|
|
|
|
if _, err := pocketbase.Update[auth.UserRecord](ctx, s.pb, "users", t.ID, patch); err != nil {
|
|
return auth.User{}, mapPB(err, "user not found")
|
|
}
|
|
if moved {
|
|
// Memberships in the old organization's workspaces would be inert
|
|
// anyway (access.WorkspaceRole), but leaving them around invites
|
|
// surprises if the user ever moves back.
|
|
s.dropMemberships(ctx, t.ID)
|
|
}
|
|
s.forget(t.ID)
|
|
return s.getUser(ctx, t.ID)
|
|
}
|
|
|
|
// DeleteUser removes an account (never the caller's own).
|
|
func (s *Service) DeleteUser(ctx context.Context, c access.Caller, id string) error {
|
|
t, err := s.getUser(ctx, id)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if err := access.DeleteUser(c, target(t)); err != nil {
|
|
return err
|
|
}
|
|
if err := s.pb.Delete(ctx, "users", t.ID); err != nil {
|
|
return mapPB(err, "user not found")
|
|
}
|
|
s.forget(t.ID)
|
|
return nil
|
|
}
|
|
|
|
func (s *Service) findUserByEmail(ctx context.Context, email string) (auth.User, error) {
|
|
email = filterValue(strings.ToLower(email))
|
|
if !strings.Contains(email, "@") {
|
|
return auth.User{}, apperr.InvalidFields(map[string]string{"email": "A valid email is required."})
|
|
}
|
|
res, err := pocketbase.List[auth.UserRecord](ctx, s.pb, "users", pocketbase.ListOptions{
|
|
PerPage: 1, Filter: fmt.Sprintf("email:lower = '%s'", email), Expand: "organization",
|
|
})
|
|
if err != nil {
|
|
return auth.User{}, err
|
|
}
|
|
if len(res.Items) == 0 {
|
|
return auth.User{}, apperr.NotFound("no user with that email")
|
|
}
|
|
return res.Items[0].User(), nil
|
|
}
|
|
|
|
// ---- Organizations ---------------------------------------------------------
|
|
|
|
type Org struct {
|
|
ID string `json:"id"`
|
|
Name string `json:"name"`
|
|
Created string `json:"created"`
|
|
Members int `json:"members"`
|
|
Workspaces int `json:"workspaces"`
|
|
}
|
|
|
|
type orgRecord struct {
|
|
ID string `json:"id"`
|
|
Name string `json:"name"`
|
|
Created string `json:"created"`
|
|
}
|
|
|
|
func (s *Service) getOrg(ctx context.Context, id string) (orgRecord, error) {
|
|
if !validID(id) {
|
|
return orgRecord{}, apperr.NotFound("organization not found")
|
|
}
|
|
rec, err := pocketbase.Get[orgRecord](ctx, s.pb, "organizations", id)
|
|
return rec, mapPB(err, "organization not found")
|
|
}
|
|
|
|
func (s *Service) count(ctx context.Context, collection, filter string) (int, error) {
|
|
res, err := pocketbase.List[struct{}](ctx, s.pb, collection, pocketbase.ListOptions{PerPage: 1, Filter: filter})
|
|
return res.TotalItems, err
|
|
}
|
|
|
|
func (s *Service) orgView(ctx context.Context, r orgRecord) (Org, error) {
|
|
members, err := s.count(ctx, "users", fmt.Sprintf("organization = '%s'", r.ID))
|
|
if err != nil {
|
|
return Org{}, err
|
|
}
|
|
workspaces, err := s.count(ctx, "workspaces", fmt.Sprintf("organization = '%s'", r.ID))
|
|
if err != nil {
|
|
return Org{}, err
|
|
}
|
|
return Org{ID: r.ID, Name: r.Name, Created: r.Created, Members: members, Workspaces: workspaces}, nil
|
|
}
|
|
|
|
// ListOrgs lists every organization for a superadmin, the own one for an admin.
|
|
func (s *Service) ListOrgs(ctx context.Context, c access.Caller) ([]Org, error) {
|
|
all, org, err := access.OrgScope(c)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
out := []Org{}
|
|
if !all && org == "" {
|
|
return out, nil
|
|
}
|
|
opts := pocketbase.ListOptions{PerPage: 500, Sort: "name"}
|
|
if !all {
|
|
opts.Filter = fmt.Sprintf("id = '%s'", org)
|
|
}
|
|
res, err := pocketbase.List[orgRecord](ctx, s.pb, "organizations", opts)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
for _, r := range res.Items {
|
|
v, err := s.orgView(ctx, r)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
out = append(out, v)
|
|
}
|
|
return out, nil
|
|
}
|
|
|
|
// CreateOrg creates an organization. A non-superadmin creator becomes its
|
|
// admin and first member; if that promotion fails the organization is rolled
|
|
// back so nobody is left with an organization they cannot run.
|
|
func (s *Service) CreateOrg(ctx context.Context, c access.Caller, name string) (Org, error) {
|
|
name, err := cleanName(name, "Organization")
|
|
if err != nil {
|
|
return Org{}, err
|
|
}
|
|
join, err := access.CreateOrg(c)
|
|
if err != nil {
|
|
return Org{}, err
|
|
}
|
|
rec, err := pocketbase.Create[orgRecord](ctx, s.pb, "organizations", map[string]any{"name": name})
|
|
if err != nil {
|
|
return Org{}, orgNameError(err)
|
|
}
|
|
if join {
|
|
_, err := pocketbase.Update[auth.UserRecord](ctx, s.pb, "users", c.ID, map[string]any{
|
|
"organization": rec.ID, "role": access.RoleAdmin,
|
|
})
|
|
if err != nil {
|
|
_ = s.pb.Delete(ctx, "organizations", rec.ID)
|
|
return Org{}, err
|
|
}
|
|
s.forget(c.ID)
|
|
}
|
|
return s.orgView(ctx, rec)
|
|
}
|
|
|
|
func orgNameError(err error) error {
|
|
var pbErr *pocketbase.Error
|
|
if errors.As(err, &pbErr) && pbErr.Data["name"].Code == "validation_not_unique" {
|
|
return apperr.Conflict("an organization with this name already exists")
|
|
}
|
|
return mapPB(err, "organization not found")
|
|
}
|
|
|
|
// RenameOrg renames an organization (superadmin: any; admin: their own).
|
|
func (s *Service) RenameOrg(ctx context.Context, c access.Caller, id, name string) (Org, error) {
|
|
name, err := cleanName(name, "Organization")
|
|
if err != nil {
|
|
return Org{}, err
|
|
}
|
|
if err := access.RenameOrg(c, id); err != nil {
|
|
return Org{}, err
|
|
}
|
|
if _, err := s.getOrg(ctx, id); err != nil {
|
|
return Org{}, err
|
|
}
|
|
rec, err := pocketbase.Update[orgRecord](ctx, s.pb, "organizations", id, map[string]any{"name": name})
|
|
if err != nil {
|
|
return Org{}, orgNameError(err)
|
|
}
|
|
return s.orgView(ctx, rec)
|
|
}
|
|
|
|
// DeleteOrg deletes an organization that has no workspaces and no other
|
|
// members. An admin deleting their own is detached and demoted to user.
|
|
func (s *Service) DeleteOrg(ctx context.Context, c access.Caller, id string) error {
|
|
selfDetach, err := access.DeleteOrg(c, id)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if _, err := s.getOrg(ctx, id); err != nil {
|
|
return err
|
|
}
|
|
|
|
filter := fmt.Sprintf("organization = '%s'", id)
|
|
blocked := "organization still has members; move or remove them first"
|
|
if selfDetach {
|
|
filter += fmt.Sprintf(" && id != '%s'", c.ID)
|
|
blocked = "organization still has other members; move or remove them first"
|
|
}
|
|
if n, err := s.count(ctx, "users", filter); err != nil {
|
|
return err
|
|
} else if n > 0 {
|
|
return apperr.Conflict(blocked)
|
|
}
|
|
if n, err := s.count(ctx, "workspaces", fmt.Sprintf("organization = '%s'", id)); err != nil {
|
|
return err
|
|
} else if n > 0 {
|
|
return apperr.Conflict("organization still has workspaces; delete them first")
|
|
}
|
|
|
|
// Detach before deleting: users.organization does not cascade, so a failed
|
|
// delete leaves an empty organization (harmless) rather than a member
|
|
// pointing at nothing.
|
|
if selfDetach {
|
|
if _, err := pocketbase.Update[auth.UserRecord](ctx, s.pb, "users", c.ID, map[string]any{
|
|
"organization": "", "role": access.RoleUser,
|
|
}); err != nil {
|
|
return err
|
|
}
|
|
s.forget(c.ID)
|
|
}
|
|
return mapPB(s.pb.Delete(ctx, "organizations", id), "organization not found")
|
|
}
|
|
|
|
// ---- Workspaces ------------------------------------------------------------
|
|
|
|
type Workspace struct {
|
|
ID string `json:"id"`
|
|
Name string `json:"name"`
|
|
Slug string `json:"slug"`
|
|
Organization string `json:"organization"`
|
|
OrganizationName string `json:"organizationName"`
|
|
// Role is the caller's effective role after the cascade.
|
|
Role string `json:"role"`
|
|
Created string `json:"created"`
|
|
}
|
|
|
|
type workspaceRecord struct {
|
|
ID string `json:"id"`
|
|
Name string `json:"name"`
|
|
Slug string `json:"slug"`
|
|
Organization string `json:"organization"`
|
|
Created string `json:"created"`
|
|
Expand struct {
|
|
Organization *struct {
|
|
Name string `json:"name"`
|
|
} `json:"organization"`
|
|
} `json:"expand"`
|
|
}
|
|
|
|
func (r workspaceRecord) view(role string) Workspace {
|
|
w := Workspace{ID: r.ID, Name: r.Name, Slug: r.Slug, Organization: r.Organization, Role: role, Created: r.Created}
|
|
if r.Expand.Organization != nil {
|
|
w.OrganizationName = r.Expand.Organization.Name
|
|
}
|
|
return w
|
|
}
|
|
|
|
type memberRecord struct {
|
|
ID string `json:"id"`
|
|
Workspace string `json:"workspace"`
|
|
User string `json:"user"`
|
|
Role string `json:"role"`
|
|
Expand struct {
|
|
User *auth.UserRecord `json:"user"`
|
|
Workspace *workspaceRecord `json:"workspace"`
|
|
} `json:"expand"`
|
|
}
|
|
|
|
func (s *Service) getWorkspace(ctx context.Context, id string) (workspaceRecord, error) {
|
|
if !validID(id) {
|
|
return workspaceRecord{}, apperr.NotFound("workspace not found")
|
|
}
|
|
rec, err := pocketbase.GetExpand[workspaceRecord](ctx, s.pb, "workspaces", id, "organization")
|
|
return rec, mapPB(err, "workspace not found")
|
|
}
|
|
|
|
// membership returns userID's membership in workspace wsID (zero value if none).
|
|
func (s *Service) membership(ctx context.Context, wsID, userID string) (memberRecord, error) {
|
|
res, err := pocketbase.List[memberRecord](ctx, s.pb, "workspace_members", pocketbase.ListOptions{
|
|
PerPage: 1, Filter: fmt.Sprintf("workspace = '%s' && user = '%s'", wsID, userID),
|
|
})
|
|
if err != nil || len(res.Items) == 0 {
|
|
return memberRecord{}, err
|
|
}
|
|
return res.Items[0], nil
|
|
}
|
|
|
|
// effective resolves c's role in ws; a membership lookup is only needed for
|
|
// callers the cascade does not already decide.
|
|
func (s *Service) effective(ctx context.Context, c access.Caller, ws workspaceRecord) (string, error) {
|
|
if role := access.WorkspaceRole(c, ws.Organization, ""); role != "" || c.OrgID != ws.Organization {
|
|
return role, nil
|
|
}
|
|
m, err := s.membership(ctx, ws.ID, c.ID)
|
|
if err != nil {
|
|
return "", err
|
|
}
|
|
return access.WorkspaceRole(c, ws.Organization, m.Role), nil
|
|
}
|
|
|
|
// workspaceFor loads a workspace with c's effective role; a workspace c cannot
|
|
// see at all is reported as not found, so its existence does not leak.
|
|
func (s *Service) workspaceFor(ctx context.Context, c access.Caller, id string) (workspaceRecord, string, error) {
|
|
ws, err := s.getWorkspace(ctx, id)
|
|
if err != nil {
|
|
return ws, "", err
|
|
}
|
|
role, err := s.effective(ctx, c, ws)
|
|
if err != nil {
|
|
return ws, "", err
|
|
}
|
|
if role == "" {
|
|
return ws, "", apperr.NotFound("workspace not found")
|
|
}
|
|
return ws, role, nil
|
|
}
|
|
|
|
// ListWorkspaces lists the workspaces c can open, with their effective role.
|
|
func (s *Service) ListWorkspaces(ctx context.Context, c access.Caller) ([]Workspace, error) {
|
|
out := []Workspace{}
|
|
if c.IsSuperadmin() || (c.Role == access.RoleAdmin && c.OrgID != "") {
|
|
opts := pocketbase.ListOptions{PerPage: 500, Sort: "name", Expand: "organization"}
|
|
if !c.IsSuperadmin() {
|
|
opts.Filter = fmt.Sprintf("organization = '%s'", c.OrgID)
|
|
}
|
|
res, err := pocketbase.List[workspaceRecord](ctx, s.pb, "workspaces", opts)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
for _, r := range res.Items {
|
|
out = append(out, r.view(access.WorkspaceRole(c, r.Organization, "")))
|
|
}
|
|
return out, nil
|
|
}
|
|
if c.OrgID == "" {
|
|
return out, nil
|
|
}
|
|
res, err := pocketbase.List[memberRecord](ctx, s.pb, "workspace_members", pocketbase.ListOptions{
|
|
PerPage: 500, Filter: fmt.Sprintf("user = '%s'", c.ID), Expand: "workspace.organization",
|
|
})
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
for _, m := range res.Items {
|
|
ws := m.Expand.Workspace
|
|
if ws == nil {
|
|
continue
|
|
}
|
|
if role := access.WorkspaceRole(c, ws.Organization, m.Role); role != "" {
|
|
out = append(out, ws.view(role))
|
|
}
|
|
}
|
|
sort.Slice(out, func(i, j int) bool { return strings.ToLower(out[i].Name) < strings.ToLower(out[j].Name) })
|
|
return out, nil
|
|
}
|
|
|
|
type CreateWorkspaceInput struct {
|
|
Name string `json:"name"`
|
|
Organization string `json:"organization"`
|
|
}
|
|
|
|
// CreateWorkspace creates a workspace in an organization (org admins: their
|
|
// own; superadmins: the one they name).
|
|
func (s *Service) CreateWorkspace(ctx context.Context, c access.Caller, in CreateWorkspaceInput) (Workspace, error) {
|
|
name, err := cleanName(in.Name, "Workspace")
|
|
if err != nil {
|
|
return Workspace{}, err
|
|
}
|
|
org, err := access.CreateWorkspace(c, strings.TrimSpace(in.Organization))
|
|
if err != nil {
|
|
return Workspace{}, err
|
|
}
|
|
if _, err := s.getOrg(ctx, org); err != nil {
|
|
return Workspace{}, err
|
|
}
|
|
|
|
base := slugify(name, "workspace")
|
|
for i := 1; i <= 50; i++ {
|
|
slug := base
|
|
if i > 1 {
|
|
slug = fmt.Sprintf("%s-%d", base, i)
|
|
}
|
|
rec, err := pocketbase.Create[workspaceRecord](ctx, s.pb, "workspaces", map[string]any{
|
|
"name": name, "slug": slug, "organization": org,
|
|
})
|
|
var pbErr *pocketbase.Error
|
|
if errors.As(err, &pbErr) && pbErr.Data["slug"].Code == "validation_not_unique" {
|
|
continue
|
|
}
|
|
if err != nil {
|
|
return Workspace{}, mapPB(err, "workspace not found")
|
|
}
|
|
full, err := s.getWorkspace(ctx, rec.ID)
|
|
if err != nil {
|
|
return Workspace{}, err
|
|
}
|
|
return full.view(access.WorkspaceRole(c, org, "")), nil
|
|
}
|
|
return Workspace{}, apperr.Conflict("could not find a free workspace address; try another name")
|
|
}
|
|
|
|
var nonSlug = regexp.MustCompile(`[^a-z0-9]+`)
|
|
|
|
func slugify(name, fallback string) string {
|
|
s := strings.Trim(nonSlug.ReplaceAllString(strings.ToLower(name), "-"), "-")
|
|
if len(s) > 48 {
|
|
s = strings.TrimRight(s[:48], "-")
|
|
}
|
|
if s == "" {
|
|
return fallback
|
|
}
|
|
return s
|
|
}
|
|
|
|
// RenameWorkspace renames a workspace (workspace admin or above).
|
|
func (s *Service) RenameWorkspace(ctx context.Context, c access.Caller, id, name string) (Workspace, error) {
|
|
name, err := cleanName(name, "Workspace")
|
|
if err != nil {
|
|
return Workspace{}, err
|
|
}
|
|
ws, role, err := s.workspaceFor(ctx, c, id)
|
|
if err != nil {
|
|
return Workspace{}, err
|
|
}
|
|
if err := access.RenameWorkspace(role); err != nil {
|
|
return Workspace{}, err
|
|
}
|
|
if _, err := pocketbase.Update[workspaceRecord](ctx, s.pb, "workspaces", ws.ID, map[string]any{"name": name}); err != nil {
|
|
return Workspace{}, mapPB(err, "workspace not found")
|
|
}
|
|
ws.Name = name
|
|
return ws.view(role), nil
|
|
}
|
|
|
|
// DeleteWorkspace deletes a workspace with its spaces and pages (owner only).
|
|
func (s *Service) DeleteWorkspace(ctx context.Context, c access.Caller, id string) error {
|
|
ws, role, err := s.workspaceFor(ctx, c, id)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if err := access.DeleteWorkspace(role); err != nil {
|
|
return err
|
|
}
|
|
return mapPB(s.pb.Delete(ctx, "workspaces", ws.ID), "workspace not found")
|
|
}
|
|
|
|
type MemberUser struct {
|
|
ID string `json:"id"`
|
|
Email string `json:"email"`
|
|
Name string `json:"name"`
|
|
}
|
|
|
|
type Member struct {
|
|
User MemberUser `json:"user"`
|
|
Role string `json:"role"`
|
|
}
|
|
|
|
// ListMembers lists a workspace's explicit members. Org admins and
|
|
// superadmins have access through the cascade without being listed here.
|
|
func (s *Service) ListMembers(ctx context.Context, c access.Caller, wsID string) ([]Member, error) {
|
|
ws, role, err := s.workspaceFor(ctx, c, wsID)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if err := access.ViewMembers(role); err != nil {
|
|
return nil, err
|
|
}
|
|
res, err := pocketbase.List[memberRecord](ctx, s.pb, "workspace_members", pocketbase.ListOptions{
|
|
PerPage: 500, Filter: fmt.Sprintf("workspace = '%s'", ws.ID), Expand: "user",
|
|
})
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
out := make([]Member, 0, len(res.Items))
|
|
for _, m := range res.Items {
|
|
if u := m.Expand.User; u != nil {
|
|
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
|
|
}
|
|
|
|
// SetMember adds a user (by email) to a workspace or changes their role. The
|
|
// user must belong to the workspace's organization.
|
|
func (s *Service) SetMember(ctx context.Context, c access.Caller, wsID, email, role string) (Member, error) {
|
|
ws, actorRole, err := s.workspaceFor(ctx, c, wsID)
|
|
if err != nil {
|
|
return Member{}, err
|
|
}
|
|
if !access.AtLeast(actorRole, access.WorkspaceAdmin) {
|
|
return Member{}, apperr.Forbidden("workspace admin role required")
|
|
}
|
|
u, err := s.findUserByEmail(ctx, email)
|
|
if err != nil {
|
|
return Member{}, err
|
|
}
|
|
if u.Organization != ws.Organization {
|
|
return Member{}, apperr.Invalid("that user is not in this workspace's organization")
|
|
}
|
|
current, err := s.membership(ctx, ws.ID, u.ID)
|
|
if err != nil {
|
|
return Member{}, err
|
|
}
|
|
if err := access.SetMember(c.ID, actorRole, u.ID, current.Role, role); err != nil {
|
|
return Member{}, err
|
|
}
|
|
if current.ID != "" {
|
|
_, err = pocketbase.Update[memberRecord](ctx, s.pb, "workspace_members", current.ID, map[string]any{"role": role})
|
|
} else {
|
|
_, err = pocketbase.Create[memberRecord](ctx, s.pb, "workspace_members", map[string]any{
|
|
"workspace": ws.ID, "user": u.ID, "role": role,
|
|
})
|
|
}
|
|
if err != nil {
|
|
return Member{}, mapPB(err, "workspace not found")
|
|
}
|
|
return Member{User: MemberUser{ID: u.ID, Email: u.Email, Name: u.Name}, Role: role}, nil
|
|
}
|
|
|
|
// RemoveMember removes a membership (idempotent). Anyone may leave.
|
|
func (s *Service) RemoveMember(ctx context.Context, c access.Caller, wsID, userID string) error {
|
|
ws, actorRole, err := s.workspaceFor(ctx, c, wsID)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if !validID(userID) {
|
|
return apperr.NotFound("member not found")
|
|
}
|
|
current, err := s.membership(ctx, ws.ID, userID)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if current.ID == "" {
|
|
return nil
|
|
}
|
|
if err := access.RemoveMember(c.ID, actorRole, userID, current.Role); err != nil {
|
|
return err
|
|
}
|
|
if err := s.pb.Delete(ctx, "workspace_members", current.ID); err != nil {
|
|
return mapPB(err, "member not found")
|
|
}
|
|
// Space roles and groups mean nothing without the workspace; drop them (best effort).
|
|
if spaceMembers, err := s.userSpaceMemberships(ctx, userID, ws.ID); err == nil {
|
|
for _, m := range spaceMembers {
|
|
_ = s.pb.Delete(ctx, "space_members", m.ID)
|
|
}
|
|
}
|
|
s.dropGroupMemberships(ctx, userID, ws.ID)
|
|
return nil
|
|
}
|
|
|
|
// dropMemberships removes all of a user's workspace, group and space memberships (best effort).
|
|
func (s *Service) dropMemberships(ctx context.Context, userID string) {
|
|
res, err := pocketbase.List[memberRecord](ctx, s.pb, "workspace_members", pocketbase.ListOptions{
|
|
PerPage: 500, Filter: fmt.Sprintf("user = '%s'", userID),
|
|
})
|
|
if err != nil {
|
|
return
|
|
}
|
|
for _, m := range res.Items {
|
|
_ = s.pb.Delete(ctx, "workspace_members", m.ID)
|
|
}
|
|
s.dropGroupMemberships(ctx, userID, "")
|
|
spaceMembers, err := s.userSpaceMemberships(ctx, userID, "")
|
|
if err != nil {
|
|
return
|
|
}
|
|
for _, m := range spaceMembers {
|
|
_ = s.pb.Delete(ctx, "space_members", m.ID)
|
|
}
|
|
}
|