// SPDX-License-Identifier: AGPL-3.0-or-later package directory import ( "context" "crypto/rand" "crypto/sha256" "encoding/base64" "encoding/hex" "fmt" "net/http" "net/url" "sort" "strings" "time" "docwell/server/internal/access" "docwell/server/internal/apperr" "docwell/server/internal/auth" "docwell/server/internal/i18n" "docwell/server/internal/mail" "docwell/server/internal/store/pocketbase" ) // ---- Invites --------------------------------------------------------------- // // An invite emails a link to docwell-web's /invite page. Accepting it creates // the account (or attaches an existing one that has no organization), with // the invite's organization, role and optional workspace membership. Signup // rules do not apply: an invite is a manager's decision. // inviteTTL is how long an invite link works. const inviteTTL = 7 * 24 * time.Hour // Mailer sends the invite emails. type Mailer struct { Sender mail.Sender // WebURL is docwell-web's base URL, for the link in the email. WebURL string // AppName returns the instance name shown in emails. AppName func(ctx context.Context) string } // UseMail enables invite emails. func (s *Service) UseMail(m Mailer) { s.mailer = m } type Invite struct { ID string `json:"id"` Email string `json:"email"` Organization string `json:"organization"` OrganizationName string `json:"organizationName"` Role string `json:"role"` Workspace string `json:"workspace"` WorkspaceName string `json:"workspaceName"` WorkspaceRole string `json:"workspaceRole"` InvitedBy string `json:"invitedBy"` Expires string `json:"expires"` Created string `json:"created"` // Status is pending or expired; "added" means the person already had an // account in the organization and was added to the workspace directly. Status string `json:"status"` // Link and Mailed are only set when an invite is created or resent, so // the inviter can pass the link on when no mail server is configured. Link string `json:"link,omitempty"` Mailed bool `json:"mailed"` } type inviteRecord struct { ID string `json:"id"` Email string `json:"email"` Organization string `json:"organization"` Role string `json:"role"` Workspace string `json:"workspace"` WorkspaceRole string `json:"workspace_role"` Page string `json:"page"` PageRole string `json:"page_role"` InvitedBy string `json:"invited_by"` Expires string `json:"expires"` Accepted string `json:"accepted"` Created string `json:"created"` Expand struct { Organization *orgRecord `json:"organization"` Workspace *workspaceRecord `json:"workspace"` InvitedBy *auth.UserRecord `json:"invited_by"` } `json:"expand"` } const inviteExpand = "organization,workspace,invited_by" func (r inviteRecord) view(now time.Time) Invite { inv := Invite{ ID: r.ID, Email: r.Email, Organization: r.Organization, Role: r.Role, Workspace: r.Workspace, WorkspaceRole: r.WorkspaceRole, Expires: r.Expires, Created: r.Created, Status: "pending", } if r.Expand.Organization != nil { inv.OrganizationName = r.Expand.Organization.Name } if r.Expand.Workspace != nil { inv.WorkspaceName = r.Expand.Workspace.Name } if u := r.Expand.InvitedBy; u != nil { inv.InvitedBy = u.Name if inv.InvitedBy == "" { inv.InvitedBy = u.Email } } if exp, err := parsePBTime(r.Expires); err == nil && now.After(exp) { inv.Status = "expired" } return inv } func parsePBTime(s string) (time.Time, error) { return time.Parse("2006-01-02 15:04:05.000Z", s) } func newInviteToken() (token, hash string, err error) { b := make([]byte, 24) if _, err := rand.Read(b); err != nil { return "", "", err } token = base64.RawURLEncoding.EncodeToString(b) return token, hashToken(token), nil } func hashToken(token string) string { sum := sha256.Sum256([]byte(token)) return hex.EncodeToString(sum[:]) } type CreateInviteInput struct { Email string `json:"email"` // Role is the instance role (organization invites only; default user). Role string `json:"role"` Organization string `json:"organization"` // Workspace, when set, makes this a workspace invite: the inviter needs // workspace admin, and the organization is the workspace's. Workspace string `json:"workspace"` WorkspaceRole string `json:"workspaceRole"` // page and pageRole make a guest invite that shares one page // (SharePageWithUser, which has checked the inviter's rights). page, pageRole string } // CreateInvite invites someone by email. Inviting a person who already has // an account in the workspace's organization adds them to the workspace // instead (Status "added"). func (s *Service) CreateInvite(ctx context.Context, c access.Caller, in CreateInviteInput) (Invite, error) { email := strings.ToLower(strings.TrimSpace(in.Email)) if !strings.Contains(email, "@") || len(email) > 255 { return Invite{}, apperr.InvalidFields(map[string]string{"email": "A valid email is required."}) } body := map[string]any{"email": email} var org string var ws workspaceRecord if in.Workspace != "" { var actorRole string var err error ws, actorRole, err = s.workspaceFor(ctx, c, in.Workspace) if err != nil { return Invite{}, err } role := in.WorkspaceRole if role == "" { role = access.WorkspaceMember } if in.page == "" { if err := access.InviteToWorkspace(actorRole, role); err != nil { return Invite{}, err } } org = ws.Organization body["role"], body["workspace"], body["workspace_role"] = access.RoleUser, ws.ID, role if in.page != "" { body["page"], body["page_role"] = in.page, in.pageRole } } else { role, ok := access.NormalizeRole(in.Role) if !ok { return Invite{}, apperr.InvalidFields(map[string]string{"role": "Role must be user, admin or superadmin."}) } var err error if org, err = access.InviteToOrg(c, role, strings.TrimSpace(in.Organization)); err != nil { return Invite{}, err } if org != "" { if _, err := s.getOrg(ctx, org); err != nil { return Invite{}, err } } body["role"] = role } body["organization"] = org existing, err := s.findUserByEmail(ctx, email) switch { case err == nil && existing.Role == access.RoleSuperadmin: return Invite{}, apperr.Conflict("that person is a superadmin and already has access everywhere") case err == nil && existing.Organization == org && org != "" && ws.ID != "" && in.page == "": // Already in the organization: no invite needed. m, err := s.SetMember(ctx, c, ws.ID, email, body["workspace_role"].(string)) if err != nil { return Invite{}, err } return Invite{ Email: m.User.Email, Organization: org, Role: access.RoleUser, Workspace: ws.ID, WorkspaceName: ws.Name, WorkspaceRole: m.Role, Status: "added", }, nil case err == nil && existing.Organization == org: return Invite{}, apperr.Conflict("that person already has an account here") case err == nil && existing.Organization != "": return Invite{}, apperr.Conflict("that person's account belongs to another organization") case err != nil && !isNotFound(err): return Invite{}, err } token, hash, err := newInviteToken() if err != nil { return Invite{}, err } body["token_hash"] = hash body["invited_by"] = c.ID body["expires"] = pbTime(time.Now().Add(inviteTTL)) // Inviting the same person to the same place again refreshes the invite. filter := fmt.Sprintf("email = '%s' && organization = '%s' && workspace = '%s' && page = '%s' && accepted = ''", filterValue(email), org, ws.ID, in.page) prev, err := pocketbase.List[inviteRecord](ctx, s.pb, "invites", pocketbase.ListOptions{PerPage: 1, Filter: filter}) if err != nil { return Invite{}, err } var rec inviteRecord if len(prev.Items) > 0 { rec, err = pocketbase.Update[inviteRecord](ctx, s.pb, "invites", prev.Items[0].ID, body) } else { rec, err = pocketbase.Create[inviteRecord](ctx, s.pb, "invites", body) } if err != nil { return Invite{}, mapPB(err, "invite not found") } return s.sendInvite(ctx, rec.ID, token) } // sendInvite emails invite id with its token and returns the invite with the link. func (s *Service) sendInvite(ctx context.Context, id, token string) (Invite, error) { rec, err := pocketbase.GetExpand[inviteRecord](ctx, s.pb, "invites", id, inviteExpand) if err != nil { return Invite{}, mapPB(err, "invite not found") } inv := rec.view(time.Now()) inv.Link = strings.TrimRight(s.mailer.WebURL, "/") + "/invite?token=" + url.QueryEscape(token) if s.mailer.Sender == nil { return inv, nil } appName := "Docwell" if s.mailer.AppName != nil { appName = s.mailer.AppName(ctx) } target := inv.OrganizationName if inv.WorkspaceName != "" { target = inv.WorkspaceName } if target == "" { target = appName } // The invite is written in the inviter's language. lang := i18n.Lang(ctx) inviter := inv.InvitedBy if inviter == "" { inviter = i18n.Sprintf(lang, "Someone") } expires := inv.Expires if t, err := parsePBTime(inv.Expires); err == nil { expires = i18n.Date(lang, t) } m, err := mail.RenderIn(lang, inv.Email, "invite", map[string]string{ "AppName": appName, "Inviter": inviter, "Target": target, "Link": inv.Link, "Expires": expires, }) if err != nil { return Invite{}, err } // Without a working mail server the inviter can still pass the link on. inv.Mailed = s.mailer.Sender.Send(ctx, m) == nil return inv, nil } func isNotFound(err error) bool { e, ok := apperr.As(err) return ok && e.Kind == apperr.KindNotFound } type ListInvitesInput struct { // Workspace lists one workspace's invites (workspace admins). Workspace string // Organization narrows a superadmin's list. Organization string } // ListInvites lists open invites: one workspace's for its admins, otherwise // the organization's (admins) or everyone's (superadmins). func (s *Service) ListInvites(ctx context.Context, c access.Caller, in ListInvitesInput) ([]Invite, error) { filters := []string{"accepted = ''"} if in.Workspace != "" { ws, role, err := s.workspaceFor(ctx, c, in.Workspace) if err != nil { return nil, err } if !access.AtLeast(role, access.WorkspaceAdmin) { return nil, apperr.Forbidden("workspace admin role required") } filters = append(filters, fmt.Sprintf("workspace = '%s'", ws.ID)) } else { all, org, err := access.UserScope(c) if err != nil { return nil, err } switch { case !all && org == "": return []Invite{}, nil case !all: filters = append(filters, fmt.Sprintf("organization = '%s'", org)) case in.Organization != "": if !validID(in.Organization) { return nil, apperr.Invalid("invalid organization id") } filters = append(filters, fmt.Sprintf("organization = '%s'", in.Organization)) } } recs, err := listAll[inviteRecord](ctx, s, "invites", pocketbase.ListOptions{ Filter: strings.Join(filters, " && "), Sort: "-created", Expand: inviteExpand, }) if err != nil { return nil, err } now := time.Now() out := make([]Invite, 0, len(recs)) for _, r := range recs { out = append(out, r.view(now)) } sort.SliceStable(out, func(i, j int) bool { return out[i].Created > out[j].Created }) return out, nil } // manageableInvite loads an open invite c may revoke or resend. func (s *Service) manageableInvite(ctx context.Context, c access.Caller, id string) (inviteRecord, error) { if !validID(id) { return inviteRecord{}, apperr.NotFound("invite not found") } rec, err := pocketbase.Get[inviteRecord](ctx, s.pb, "invites", id) if err != nil { return rec, mapPB(err, "invite not found") } if rec.Accepted != "" { return rec, apperr.NotFound("invite not found") } wsRole := "" if rec.Workspace != "" { if _, role, err := s.workspaceFor(ctx, c, rec.Workspace); err == nil { wsRole = role } } if err := access.ManageInvite(c, rec.InvitedBy, rec.Organization, wsRole); err != nil { // Do not reveal invites the caller cannot manage. return rec, apperr.NotFound("invite not found") } return rec, nil } // RevokeInvite deletes an open invite; its link stops working. func (s *Service) RevokeInvite(ctx context.Context, c access.Caller, id string) error { rec, err := s.manageableInvite(ctx, c, id) if err != nil { return err } return mapPB(s.pb.Delete(ctx, "invites", rec.ID), "invite not found") } // ResendInvite issues a new link (the old one stops working) with a fresh expiry. func (s *Service) ResendInvite(ctx context.Context, c access.Caller, id string) (Invite, error) { rec, err := s.manageableInvite(ctx, c, id) if err != nil { return Invite{}, err } token, hash, err := newInviteToken() if err != nil { return Invite{}, err } if _, err := pocketbase.Update[inviteRecord](ctx, s.pb, "invites", rec.ID, map[string]any{ "token_hash": hash, "expires": pbTime(time.Now().Add(inviteTTL)), }); err != nil { return Invite{}, mapPB(err, "invite not found") } return s.sendInvite(ctx, rec.ID, token) } // InviteInfo is what the /invite page shows before the person accepts. type InviteInfo struct { Email string `json:"email"` OrganizationName string `json:"organizationName"` WorkspaceName string `json:"workspaceName"` InvitedBy string `json:"invitedBy"` Expires string `json:"expires"` // HasAccount means the person must sign in to accept instead of signing up. HasAccount bool `json:"hasAccount"` } // openInvite finds the open invite for token; unknown, used and expired // tokens are all reported as auth.ErrInvalidToken. func (s *Service) openInvite(ctx context.Context, token string) (inviteRecord, error) { token = strings.TrimSpace(token) if token == "" || len(token) > 128 { return inviteRecord{}, auth.ErrInvalidToken } res, err := pocketbase.List[inviteRecord](ctx, s.pb, "invites", pocketbase.ListOptions{ PerPage: 1, Filter: fmt.Sprintf("token_hash = '%s'", hashToken(token)), Expand: inviteExpand, }) if err != nil { return inviteRecord{}, err } if len(res.Items) == 0 { return inviteRecord{}, auth.ErrInvalidToken } rec := res.Items[0] if rec.Accepted != "" || rec.view(time.Now()).Status != "pending" { return inviteRecord{}, auth.ErrInvalidToken } return rec, nil } // GetInviteInfo describes an open invite to anyone who holds its token. func (s *Service) GetInviteInfo(ctx context.Context, token string) (InviteInfo, error) { rec, err := s.openInvite(ctx, token) if err != nil { return InviteInfo{}, err } inv := rec.view(time.Now()) _, err = s.findUserByEmail(ctx, rec.Email) if err != nil && !isNotFound(err) { return InviteInfo{}, err } return InviteInfo{ Email: inv.Email, OrganizationName: inv.OrganizationName, WorkspaceName: inv.WorkspaceName, InvitedBy: inv.InvitedBy, Expires: inv.Expires, HasAccount: err == nil, }, nil } type AcceptInviteInput struct { Token string `json:"token"` Name string `json:"name"` Password string `json:"password"` } // AcceptInvite uses an invite. With me == nil it creates the account (name // and password required); otherwise it attaches the signed-in account, which // must own the invited email. It returns the account's email. func (s *Service) AcceptInvite(ctx context.Context, me *auth.User, in AcceptInviteInput) (string, error) { rec, err := s.openInvite(ctx, in.Token) if err != nil { return "", err } _, err = s.findUserByEmail(ctx, rec.Email) if err != nil && !isNotFound(err) { return "", err } hasAccount := err == nil var userID string switch { case me != nil: if !strings.EqualFold(me.Email, rec.Email) { return "", apperr.Forbidden("this invite is for " + rec.Email + "; sign in with that account") } if err := access.AcceptInvite(me.Role, me.Organization, rec.Organization); err != nil { return "", err } patch := map[string]any{"verified": true} if me.Organization != rec.Organization { patch["organization"], patch["role"] = rec.Organization, rec.Role } if _, err := pocketbase.Update[auth.UserRecord](ctx, s.pb, "users", me.ID, patch); err != nil { return "", mapPB(err, "user not found") } userID = me.ID case hasAccount: return "", apperr.Conflict("an account with this email already exists; sign in to accept the invite") default: name := strings.TrimSpace(in.Name) fields := map[string]string{} if name == "" { fields["name"] = "Name is required." } if len(in.Password) < 8 { fields["password"] = "Password must be at least 8 characters." } if len(fields) > 0 { return "", apperr.InvalidFields(fields) } created, err := pocketbase.Create[auth.UserRecord](ctx, s.pb, "users", map[string]any{ "email": rec.Email, "password": in.Password, "passwordConfirm": in.Password, "name": name, "role": rec.Role, "organization": rec.Organization, "status": "active", // The link reached this inbox, which is what verification proves. "verified": true, "emailVisibility": false, }) if err != nil { return "", mapPB(err, "user not found") } userID = created.ID } if rec.Workspace != "" { current, err := s.membership(ctx, rec.Workspace, userID) if err != nil { return "", err } if current.ID == "" { if _, err := pocketbase.Create[memberRecord](ctx, s.pb, "workspace_members", map[string]any{ "workspace": rec.Workspace, "user": userID, "role": rec.WorkspaceRole, }); err != nil { return "", mapPB(err, "workspace not found") } } } if rec.Page != "" && access.ValidPageGrant(rec.PageRole) { // The page may have gone since; the workspace membership still stands. if p, err := s.getPage(ctx, rec.Page); err == nil { if err := s.upsertGrant(ctx, p, "user", userID, rec.PageRole); err != nil { return "", err } } } if _, err := pocketbase.Update[inviteRecord](ctx, s.pb, "invites", rec.ID, map[string]any{ "accepted": pbTime(time.Now()), }); err != nil { return "", err } s.forget(userID) return rec.Email, nil } // SendPasswordReset emails a user a password-reset link (manager). func (s *Service) SendPasswordReset(ctx context.Context, c access.Caller, id string) error { t, err := s.getUser(ctx, id) if err != nil { return err } if err := access.ManageUser(c, target(t)); err != nil { return err } return s.pb.Do(ctx, http.MethodPost, "/api/collections/users/request-password-reset", map[string]string{"email": t.Email}, nil) }