CI / go (Media) (push) Successful in 13m40s
CI / go (Server) (push) Failing after 23m20s
CI / go (Web-App) (push) Canceled after 0s
CI / frontend (push) Failing after 10m35s
Docs / build (push) Canceled after 0s
Docs / deploy (push) Canceled after 0s
CI / desktop (ubuntu-latest) (push) Failing after 3h4m42s
CI / desktop (macos-latest) (push) Canceled after 0s
CI / desktop (windows-latest) (push) Canceled after 0s
CI / mobile (push) Failing after 9m19s
CI / docker (push) Successful in 2h2m57s
- Columns: /columns puts 2 to 4 columns side by side, with widths dragged between them; they stack on phones. HTML export and import keep them (also Notion column lists and Confluence page layouts). - Suggesting mode: edits become suggested insertions and deletions that editors accept or reject one by one or all at once. Text only. - Verified pages: editors verify a page for a while or without end; the verifier is notified when it runs out (migration 1764700000). - Scanned PDFs attached to pages are read by AI for search where a workspace turns it on. - The server writes error messages, emails, digests and phone notifications in English, Polish, German, French and Spanish; the apps send their language with each request. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
668 lines
20 KiB
Go
668 lines
20 KiB
Go
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
|
|
// Package settings holds the instance settings superadmins edit in the admin
|
|
// panel. Signup rules and branding are stored in the instance_settings
|
|
// collection (environment variables only seed the defaults); mail and file
|
|
// storage are PocketBase's own settings, patched through its settings API.
|
|
package settings
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"fmt"
|
|
"net/http"
|
|
"regexp"
|
|
"strings"
|
|
"sync"
|
|
"time"
|
|
|
|
"docwell/server/internal/access"
|
|
"docwell/server/internal/apperr"
|
|
"docwell/server/internal/i18n"
|
|
"docwell/server/internal/mail"
|
|
"docwell/server/internal/store/pocketbase"
|
|
)
|
|
|
|
// Signup controls self-service account creation.
|
|
type Signup struct {
|
|
Enabled bool `json:"enabled"`
|
|
// Domains limits signup to these email domains when not empty.
|
|
Domains []string `json:"domains"`
|
|
}
|
|
|
|
// Branding is how the instance presents itself in the apps and emails.
|
|
type Branding struct {
|
|
AppName string `json:"appName"`
|
|
// AccentColor is "#rrggbb", or "" for the design system's default.
|
|
AccentColor string `json:"accentColor"`
|
|
// Logo is a data: URL (PNG, JPEG, WebP or SVG), or "" for the Docwell logo.
|
|
Logo string `json:"logo"`
|
|
}
|
|
|
|
// SMTP is the outgoing mail server. Password is write-only: reads leave it
|
|
// empty and report PasswordSet instead.
|
|
type SMTP struct {
|
|
Enabled bool `json:"enabled"`
|
|
Host string `json:"host"`
|
|
Port int `json:"port"`
|
|
Username string `json:"username"`
|
|
Password string `json:"password,omitempty"`
|
|
PasswordSet bool `json:"passwordSet"`
|
|
TLS bool `json:"tls"`
|
|
SenderName string `json:"senderName"`
|
|
SenderAddress string `json:"senderAddress"`
|
|
}
|
|
|
|
// Storage selects where uploaded files live: PocketBase's local disk, or S3.
|
|
// Secret is write-only like SMTP.Password.
|
|
type Storage struct {
|
|
S3 bool `json:"s3"`
|
|
Bucket string `json:"bucket"`
|
|
Region string `json:"region"`
|
|
Endpoint string `json:"endpoint"`
|
|
AccessKey string `json:"accessKey"`
|
|
Secret string `json:"secret,omitempty"`
|
|
SecretSet bool `json:"secretSet"`
|
|
ForcePathStyle bool `json:"forcePathStyle"`
|
|
}
|
|
|
|
// Auth holds the sign-in methods the admin panel switches.
|
|
type Auth struct {
|
|
// MagicLink emails a one-time sign-in link and code (PocketBase's email OTP).
|
|
MagicLink bool `json:"magicLink"`
|
|
// OAuth2 are the providers people can sign in with; leaving one out
|
|
// turns it off. Saving replaces the whole list.
|
|
OAuth2 []OAuthProvider `json:"oauth2"`
|
|
// CallbackURL is the address to register with each provider (read-only).
|
|
CallbackURL string `json:"callbackUrl,omitempty"`
|
|
}
|
|
|
|
// OAuthProviders Docwell offers: Google, GitHub, Microsoft, and any OpenID
|
|
// Connect provider (Keycloak, Authentik, Okta, Entra ID, …).
|
|
var OAuthProviders = []string{"google", "github", "microsoft", "oidc"}
|
|
|
|
// OAuthProvider is one sign-in provider. ClientSecret is write-only: reads
|
|
// leave it empty (PocketBase never returns it), and saving without one keeps
|
|
// the stored secret. AuthURL, TokenURL and UserInfoURL are for "oidc".
|
|
type OAuthProvider struct {
|
|
Name string `json:"name"`
|
|
ClientID string `json:"clientId"`
|
|
ClientSecret string `json:"clientSecret,omitempty"`
|
|
DisplayName string `json:"displayName"`
|
|
AuthURL string `json:"authUrl"`
|
|
TokenURL string `json:"tokenUrl"`
|
|
UserInfoURL string `json:"userInfoUrl"`
|
|
}
|
|
|
|
// Instance is every setting, as the admin panel shows it.
|
|
type Instance struct {
|
|
Signup Signup `json:"signup"`
|
|
Auth Auth `json:"auth"`
|
|
Branding Branding `json:"branding"`
|
|
SMTP SMTP `json:"smtp"`
|
|
Storage Storage `json:"storage"`
|
|
}
|
|
|
|
// Update changes the sections that are set. A nil SMTP.Password or
|
|
// Storage.Secret keeps the stored one.
|
|
type Update struct {
|
|
Signup *Signup `json:"signup"`
|
|
Auth *Auth `json:"auth"`
|
|
Branding *Branding `json:"branding"`
|
|
SMTP *struct {
|
|
SMTP
|
|
Password *string `json:"password"`
|
|
} `json:"smtp"`
|
|
Storage *struct {
|
|
Storage
|
|
Secret *string `json:"secret"`
|
|
} `json:"storage"`
|
|
}
|
|
|
|
// Public is what signed-out visitors may know (the login page needs it).
|
|
type Public struct {
|
|
AppName string `json:"appName"`
|
|
AccentColor string `json:"accentColor"`
|
|
Logo string `json:"logo"`
|
|
Signup bool `json:"signup"`
|
|
MagicLink bool `json:"magicLink"`
|
|
}
|
|
|
|
const (
|
|
keySignup = "signup"
|
|
keyBranding = "branding"
|
|
// keySMTPPassword is docwell-server's copy of the mail server password.
|
|
// PocketBase never returns it, and the server needs it to send its own
|
|
// emails. instance_settings is superuser-only, like PocketBase's settings.
|
|
keySMTPPassword = "smtp_password"
|
|
cacheTTL = 30 * time.Second
|
|
)
|
|
|
|
type Service struct {
|
|
pb *pocketbase.Client
|
|
// callback is the web app's OAuth callback address, shown to admins.
|
|
callback string
|
|
defaults Signup
|
|
mail mail.Sender
|
|
now func() time.Time
|
|
|
|
mu sync.Mutex
|
|
cache map[string]cached
|
|
}
|
|
|
|
type cached struct {
|
|
raw json.RawMessage
|
|
expires time.Time
|
|
}
|
|
|
|
// SetOAuthCallback sets the address admins register with sign-in providers.
|
|
func (s *Service) SetOAuthCallback(url string) { s.callback = url }
|
|
|
|
// New returns the settings service; defaults apply until a superadmin saves
|
|
// signup rules of their own.
|
|
func New(pb *pocketbase.Client, defaults Signup, sender mail.Sender) *Service {
|
|
return &Service{pb: pb, defaults: defaults, mail: sender, now: time.Now, cache: map[string]cached{}}
|
|
}
|
|
|
|
type kvRecord struct {
|
|
ID string `json:"id"`
|
|
Key string `json:"key"`
|
|
Value json.RawMessage `json:"value"`
|
|
}
|
|
|
|
// load reads one key into out; found is false when it was never saved.
|
|
func (s *Service) load(ctx context.Context, key string, out any) (found bool, err error) {
|
|
s.mu.Lock()
|
|
c, ok := s.cache[key]
|
|
s.mu.Unlock()
|
|
if !ok || s.now().After(c.expires) {
|
|
res, err := pocketbase.List[kvRecord](ctx, s.pb, "instance_settings", pocketbase.ListOptions{
|
|
PerPage: 1, Filter: fmt.Sprintf("key = '%s'", key),
|
|
})
|
|
if err != nil {
|
|
return false, err
|
|
}
|
|
c = cached{expires: s.now().Add(cacheTTL)}
|
|
if len(res.Items) > 0 {
|
|
c.raw = res.Items[0].Value
|
|
}
|
|
s.mu.Lock()
|
|
s.cache[key] = c
|
|
s.mu.Unlock()
|
|
}
|
|
if len(c.raw) == 0 || string(c.raw) == "null" {
|
|
return false, nil
|
|
}
|
|
return true, json.Unmarshal(c.raw, out)
|
|
}
|
|
|
|
func (s *Service) save(ctx context.Context, key string, v any) error {
|
|
raw, err := json.Marshal(v)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
res, err := pocketbase.List[kvRecord](ctx, s.pb, "instance_settings", pocketbase.ListOptions{
|
|
PerPage: 1, Filter: fmt.Sprintf("key = '%s'", key),
|
|
})
|
|
if err != nil {
|
|
return err
|
|
}
|
|
body := map[string]any{"key": key, "value": json.RawMessage(raw)}
|
|
if len(res.Items) > 0 {
|
|
_, err = pocketbase.Update[kvRecord](ctx, s.pb, "instance_settings", res.Items[0].ID, body)
|
|
} else {
|
|
_, err = pocketbase.Create[kvRecord](ctx, s.pb, "instance_settings", body)
|
|
}
|
|
if err != nil {
|
|
return err
|
|
}
|
|
s.mu.Lock()
|
|
s.cache[key] = cached{raw: raw, expires: s.now().Add(cacheTTL)}
|
|
s.mu.Unlock()
|
|
return nil
|
|
}
|
|
|
|
// Signup returns the signup rules (the defaults until a superadmin saves some).
|
|
func (s *Service) Signup(ctx context.Context) (Signup, error) {
|
|
out := s.defaults
|
|
if _, err := s.load(ctx, keySignup, &out); err != nil {
|
|
return Signup{}, err
|
|
}
|
|
if out.Domains == nil {
|
|
out.Domains = []string{}
|
|
}
|
|
return out, nil
|
|
}
|
|
|
|
// Branding returns the instance branding; an unset name is "Docwell".
|
|
func (s *Service) Branding(ctx context.Context) (Branding, error) {
|
|
var out Branding
|
|
if _, err := s.load(ctx, keyBranding, &out); err != nil {
|
|
return Branding{}, err
|
|
}
|
|
if out.AppName == "" {
|
|
out.AppName = "Docwell"
|
|
}
|
|
return out, nil
|
|
}
|
|
|
|
// Public returns the settings signed-out visitors may see.
|
|
func (s *Service) Public(ctx context.Context) (Public, error) {
|
|
b, err := s.Branding(ctx)
|
|
if err != nil {
|
|
return Public{}, err
|
|
}
|
|
su, err := s.Signup(ctx)
|
|
if err != nil {
|
|
return Public{}, err
|
|
}
|
|
a, err := s.auth(ctx)
|
|
if err != nil {
|
|
return Public{}, err
|
|
}
|
|
return Public{AppName: b.AppName, AccentColor: b.AccentColor, Logo: b.Logo, Signup: su.Enabled, MagicLink: a.MagicLink}, nil
|
|
}
|
|
|
|
// auth reads the sign-in switches from the users collection.
|
|
func (s *Service) auth(ctx context.Context) (Auth, error) {
|
|
var users struct {
|
|
OTP struct {
|
|
Enabled bool `json:"enabled"`
|
|
} `json:"otp"`
|
|
OAuth2 struct {
|
|
Enabled bool `json:"enabled"`
|
|
Providers []struct {
|
|
Name string `json:"name"`
|
|
ClientID string `json:"clientId"`
|
|
DisplayName string `json:"displayName"`
|
|
AuthURL string `json:"authURL"`
|
|
TokenURL string `json:"tokenURL"`
|
|
UserInfoURL string `json:"userInfoURL"`
|
|
} `json:"providers"`
|
|
} `json:"oauth2"`
|
|
}
|
|
if err := s.pb.Do(ctx, http.MethodGet, "/api/collections/users", nil, &users); err != nil {
|
|
return Auth{}, err
|
|
}
|
|
a := Auth{MagicLink: users.OTP.Enabled, OAuth2: []OAuthProvider{}, CallbackURL: s.callback}
|
|
if users.OAuth2.Enabled {
|
|
for _, p := range users.OAuth2.Providers {
|
|
a.OAuth2 = append(a.OAuth2, OAuthProvider{
|
|
Name: p.Name, ClientID: p.ClientID, DisplayName: p.DisplayName,
|
|
AuthURL: p.AuthURL, TokenURL: p.TokenURL, UserInfoURL: p.UserInfoURL,
|
|
})
|
|
}
|
|
}
|
|
return a, nil
|
|
}
|
|
|
|
// oauthBody validates providers and builds PocketBase's oauth2 settings.
|
|
func oauthBody(providers []OAuthProvider) (map[string]any, error) {
|
|
fields := map[string]string{}
|
|
seen := map[string]bool{}
|
|
list := []map[string]any{}
|
|
for i, p := range providers {
|
|
key := fmt.Sprintf("auth.oauth2.%d", i)
|
|
known := false
|
|
for _, n := range OAuthProviders {
|
|
known = known || p.Name == n
|
|
}
|
|
switch {
|
|
case !known:
|
|
fields[key+".name"] = "Unknown provider."
|
|
continue
|
|
case seen[p.Name]:
|
|
fields[key+".name"] = "This provider is listed twice."
|
|
continue
|
|
case strings.TrimSpace(p.ClientID) == "":
|
|
fields[key+".clientId"] = "Client ID is required."
|
|
}
|
|
seen[p.Name] = true
|
|
entry := map[string]any{"name": p.Name, "clientId": strings.TrimSpace(p.ClientID), "displayName": strings.TrimSpace(p.DisplayName)}
|
|
if p.ClientSecret != "" {
|
|
entry["clientSecret"] = p.ClientSecret
|
|
}
|
|
if p.Name == "oidc" {
|
|
for k, v := range map[string]string{"authURL": p.AuthURL, "tokenURL": p.TokenURL, "userInfoURL": p.UserInfoURL} {
|
|
v = strings.TrimSpace(v)
|
|
if !strings.HasPrefix(v, "https://") && !strings.HasPrefix(v, "http://") {
|
|
fields[key+"."+strings.Replace(k, "URL", "Url", 1)] = "Enter the provider's address (https://…)."
|
|
}
|
|
entry[k] = v
|
|
}
|
|
if entry["displayName"] == "" {
|
|
entry["displayName"] = "Single sign-on"
|
|
}
|
|
}
|
|
list = append(list, entry)
|
|
}
|
|
if len(fields) > 0 {
|
|
return nil, apperr.InvalidFields(fields)
|
|
}
|
|
return map[string]any{"enabled": len(list) > 0, "providers": list}, nil
|
|
}
|
|
|
|
// pbSettings is the part of PocketBase's /api/settings this package uses.
|
|
// PocketBase never returns passwords or secrets.
|
|
type pbSettings struct {
|
|
Meta struct {
|
|
AppName string `json:"appName"`
|
|
SenderName string `json:"senderName"`
|
|
SenderAddress string `json:"senderAddress"`
|
|
} `json:"meta"`
|
|
SMTP struct {
|
|
Enabled bool `json:"enabled"`
|
|
Host string `json:"host"`
|
|
Port int `json:"port"`
|
|
Username string `json:"username"`
|
|
TLS bool `json:"tls"`
|
|
} `json:"smtp"`
|
|
S3 struct {
|
|
Enabled bool `json:"enabled"`
|
|
Bucket string `json:"bucket"`
|
|
Region string `json:"region"`
|
|
Endpoint string `json:"endpoint"`
|
|
AccessKey string `json:"accessKey"`
|
|
ForcePathStyle bool `json:"forcePathStyle"`
|
|
} `json:"s3"`
|
|
}
|
|
|
|
func (s *Service) pbSettings(ctx context.Context) (pbSettings, error) {
|
|
var out pbSettings
|
|
err := s.pb.Do(ctx, http.MethodGet, "/api/settings", nil, &out)
|
|
return out, err
|
|
}
|
|
|
|
// Get returns every instance setting (superadmin).
|
|
func (s *Service) Get(ctx context.Context, c access.Caller) (Instance, error) {
|
|
if err := access.ManageInstance(c); err != nil {
|
|
return Instance{}, err
|
|
}
|
|
return s.get(ctx)
|
|
}
|
|
|
|
func (s *Service) get(ctx context.Context) (Instance, error) {
|
|
su, err := s.Signup(ctx)
|
|
if err != nil {
|
|
return Instance{}, err
|
|
}
|
|
b, err := s.Branding(ctx)
|
|
if err != nil {
|
|
return Instance{}, err
|
|
}
|
|
pb, err := s.pbSettings(ctx)
|
|
if err != nil {
|
|
return Instance{}, err
|
|
}
|
|
a, err := s.auth(ctx)
|
|
if err != nil {
|
|
return Instance{}, err
|
|
}
|
|
var smtpPassword string
|
|
if _, err := s.load(ctx, keySMTPPassword, &smtpPassword); err != nil {
|
|
return Instance{}, err
|
|
}
|
|
return Instance{
|
|
Signup: su,
|
|
Auth: a,
|
|
Branding: b,
|
|
SMTP: SMTP{
|
|
Enabled: pb.SMTP.Enabled, Host: pb.SMTP.Host, Port: pb.SMTP.Port, Username: pb.SMTP.Username,
|
|
// PocketBase hides the password, so this reports the server's own copy:
|
|
// a password saved before the server kept one shows as unset and has
|
|
// to be entered again before Docwell's own emails can be sent.
|
|
PasswordSet: smtpPassword != "", TLS: pb.SMTP.TLS,
|
|
SenderName: pb.Meta.SenderName, SenderAddress: pb.Meta.SenderAddress,
|
|
},
|
|
Storage: Storage{
|
|
S3: pb.S3.Enabled, Bucket: pb.S3.Bucket, Region: pb.S3.Region, Endpoint: pb.S3.Endpoint,
|
|
AccessKey: pb.S3.AccessKey, SecretSet: pb.S3.AccessKey != "", ForcePathStyle: pb.S3.ForcePathStyle,
|
|
},
|
|
}, nil
|
|
}
|
|
|
|
var (
|
|
domainPattern = regexp.MustCompile(`^[a-z0-9-]+(\.[a-z0-9-]+)+$`)
|
|
colorPattern = regexp.MustCompile(`^#[0-9a-fA-F]{6}$`)
|
|
logoPattern = regexp.MustCompile(`^data:image/(png|jpeg|webp|svg\+xml);base64,[A-Za-z0-9+/=]+$`)
|
|
)
|
|
|
|
// maxLogo caps the logo data URL; it is sent with every public settings read.
|
|
const maxLogo = 256 << 10
|
|
|
|
// CleanDomains normalizes an allow-list ("@Example.com " → "example.com").
|
|
func CleanDomains(in []string) ([]string, error) {
|
|
out := []string{}
|
|
seen := map[string]bool{}
|
|
for _, d := range in {
|
|
d = strings.ToLower(strings.TrimPrefix(strings.TrimSpace(d), "@"))
|
|
if d == "" || seen[d] {
|
|
continue
|
|
}
|
|
if !domainPattern.MatchString(d) {
|
|
return nil, apperr.InvalidFields(map[string]string{"signup.domains": fmt.Sprintf("%q is not a domain.", d)})
|
|
}
|
|
seen[d] = true
|
|
out = append(out, d)
|
|
}
|
|
return out, nil
|
|
}
|
|
|
|
func cleanBranding(b Branding) (Branding, error) {
|
|
b.AppName = strings.TrimSpace(b.AppName)
|
|
b.AccentColor = strings.TrimSpace(b.AccentColor)
|
|
fields := map[string]string{}
|
|
if b.AppName == "" {
|
|
fields["branding.appName"] = "Name is required."
|
|
} else if len(b.AppName) > 60 {
|
|
fields["branding.appName"] = "Name is too long (max 60)."
|
|
}
|
|
if b.AccentColor != "" && !colorPattern.MatchString(b.AccentColor) {
|
|
fields["branding.accentColor"] = "Colour must look like #2f7d6d."
|
|
}
|
|
if b.Logo != "" && (len(b.Logo) > maxLogo || !logoPattern.MatchString(b.Logo)) {
|
|
fields["branding.logo"] = "Logo must be a PNG, JPEG, WebP or SVG image under 190 KB."
|
|
}
|
|
if len(fields) > 0 {
|
|
return Branding{}, apperr.InvalidFields(fields)
|
|
}
|
|
return b, nil
|
|
}
|
|
|
|
// Apply saves the sections set in in (superadmin) and returns the result.
|
|
func (s *Service) Apply(ctx context.Context, c access.Caller, in Update) (Instance, error) {
|
|
if err := access.ManageInstance(c); err != nil {
|
|
return Instance{}, err
|
|
}
|
|
|
|
// Checked before anything is saved, so a mistake changes nothing.
|
|
var oauth map[string]any
|
|
if in.Auth != nil && in.Auth.OAuth2 != nil {
|
|
var err error
|
|
if oauth, err = oauthBody(in.Auth.OAuth2); err != nil {
|
|
return Instance{}, err
|
|
}
|
|
}
|
|
|
|
patch := map[string]any{}
|
|
meta := map[string]any{}
|
|
var branding *Branding
|
|
if in.Branding != nil {
|
|
b, err := cleanBranding(*in.Branding)
|
|
if err != nil {
|
|
return Instance{}, err
|
|
}
|
|
branding = &b
|
|
// PocketBase signs its own emails (verification, reset) with this name.
|
|
meta["appName"] = b.AppName
|
|
meta["senderName"] = b.AppName
|
|
if b.AccentColor != "" {
|
|
meta["accentColor"] = b.AccentColor
|
|
}
|
|
}
|
|
var signup *Signup
|
|
if in.Signup != nil {
|
|
domains, err := CleanDomains(in.Signup.Domains)
|
|
if err != nil {
|
|
return Instance{}, err
|
|
}
|
|
signup = &Signup{Enabled: in.Signup.Enabled, Domains: domains}
|
|
}
|
|
if in.SMTP != nil {
|
|
m := in.SMTP
|
|
m.Host = strings.TrimSpace(m.Host)
|
|
m.SenderAddress = strings.TrimSpace(m.SenderAddress)
|
|
fields := map[string]string{}
|
|
if m.Enabled && m.Host == "" {
|
|
fields["smtp.host"] = "Host is required."
|
|
}
|
|
if m.Enabled && (m.Port < 1 || m.Port > 65535) {
|
|
fields["smtp.port"] = "Port must be between 1 and 65535."
|
|
}
|
|
if !strings.Contains(m.SenderAddress, "@") {
|
|
fields["smtp.senderAddress"] = "A valid sender address is required."
|
|
}
|
|
if len(fields) > 0 {
|
|
return Instance{}, apperr.InvalidFields(fields)
|
|
}
|
|
smtp := map[string]any{
|
|
"enabled": m.Enabled, "host": m.Host, "port": m.Port, "username": strings.TrimSpace(m.Username), "tls": m.TLS,
|
|
}
|
|
if m.Password != nil {
|
|
smtp["password"] = *m.Password
|
|
}
|
|
patch["smtp"] = smtp
|
|
meta["senderAddress"] = m.SenderAddress
|
|
if name := strings.TrimSpace(m.SenderName); name != "" {
|
|
meta["senderName"] = name
|
|
}
|
|
}
|
|
if in.Storage != nil {
|
|
st := in.Storage
|
|
if st.S3 && (strings.TrimSpace(st.Bucket) == "" || strings.TrimSpace(st.Endpoint) == "") {
|
|
return Instance{}, apperr.InvalidFields(map[string]string{"storage.bucket": "Bucket and endpoint are required for S3."})
|
|
}
|
|
s3 := map[string]any{
|
|
"enabled": st.S3, "bucket": strings.TrimSpace(st.Bucket), "region": strings.TrimSpace(st.Region),
|
|
"endpoint": strings.TrimSpace(st.Endpoint), "accessKey": strings.TrimSpace(st.AccessKey), "forcePathStyle": st.ForcePathStyle,
|
|
}
|
|
if st.Secret != nil {
|
|
s3["secret"] = *st.Secret
|
|
}
|
|
patch["s3"] = s3
|
|
}
|
|
if len(meta) > 0 {
|
|
patch["meta"] = meta
|
|
}
|
|
|
|
if len(patch) > 0 {
|
|
if err := s.pb.Do(ctx, http.MethodPatch, "/api/settings", patch, nil); err != nil {
|
|
return Instance{}, settingsError(err)
|
|
}
|
|
}
|
|
if in.SMTP != nil && in.SMTP.Password != nil {
|
|
if err := s.save(ctx, keySMTPPassword, *in.SMTP.Password); err != nil {
|
|
return Instance{}, err
|
|
}
|
|
}
|
|
if in.Auth != nil {
|
|
body := map[string]any{"otp": map[string]any{"enabled": in.Auth.MagicLink}}
|
|
if oauth != nil {
|
|
body["oauth2"] = oauth
|
|
}
|
|
if err := s.pb.Do(ctx, http.MethodPatch, "/api/collections/users", body, nil); err != nil {
|
|
return Instance{}, err
|
|
}
|
|
}
|
|
if branding != nil {
|
|
if err := s.save(ctx, keyBranding, branding); err != nil {
|
|
return Instance{}, err
|
|
}
|
|
}
|
|
if signup != nil {
|
|
if err := s.save(ctx, keySignup, signup); err != nil {
|
|
return Instance{}, err
|
|
}
|
|
}
|
|
return s.get(ctx)
|
|
}
|
|
|
|
// settingsError reports PocketBase's validation of mail and storage settings
|
|
// as field errors ("smtp.host", "s3.bucket", ...).
|
|
func settingsError(err error) error {
|
|
var pbErr *pocketbase.Error
|
|
if !errors.As(err, &pbErr) || pbErr.Status != http.StatusBadRequest {
|
|
return err
|
|
}
|
|
fields := map[string]string{}
|
|
for k, v := range pbErr.Data {
|
|
fields[k] = v.Message
|
|
}
|
|
if len(fields) == 0 {
|
|
return apperr.Invalid(pbErr.Message)
|
|
}
|
|
return apperr.InvalidFields(fields)
|
|
}
|
|
|
|
// TestEmail sends a test message to to (superadmin).
|
|
func (s *Service) TestEmail(ctx context.Context, c access.Caller, to string) error {
|
|
if err := access.ManageInstance(c); err != nil {
|
|
return err
|
|
}
|
|
to = strings.TrimSpace(to)
|
|
if !strings.Contains(to, "@") {
|
|
return apperr.InvalidFields(map[string]string{"to": "A valid email is required."})
|
|
}
|
|
b, err := s.Branding(ctx)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
m, err := mail.RenderIn(i18n.Lang(ctx), to, "test", map[string]string{"AppName": b.AppName})
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if err := s.mail.Send(ctx, m); err != nil {
|
|
if errors.Is(err, mail.ErrNotConfigured) {
|
|
return apperr.Invalid("No mail server is configured.")
|
|
}
|
|
var delivery *mail.DeliveryError
|
|
if errors.As(err, &delivery) {
|
|
return apperr.Invalid("the mail server rejected the message: " + delivery.Err.Error())
|
|
}
|
|
return err
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// MailConfig is the mail server docwell-server sends its own emails through:
|
|
// PocketBase's SMTP settings, with the password from the server's own copy.
|
|
func (s *Service) MailConfig(ctx context.Context) (mail.Config, error) {
|
|
pb, err := s.pbSettings(ctx)
|
|
if err != nil {
|
|
return mail.Config{}, err
|
|
}
|
|
var password string
|
|
if _, err := s.load(ctx, keySMTPPassword, &password); err != nil {
|
|
return mail.Config{}, err
|
|
}
|
|
return mail.Config{
|
|
Enabled: pb.SMTP.Enabled, Host: pb.SMTP.Host, Port: pb.SMTP.Port,
|
|
Username: pb.SMTP.Username, Password: password, TLS: pb.SMTP.TLS,
|
|
SenderName: pb.Meta.SenderName, SenderAddress: pb.Meta.SenderAddress,
|
|
}, nil
|
|
}
|
|
|
|
// TestStorage checks that PocketBase can reach the configured S3 bucket (superadmin).
|
|
func (s *Service) TestStorage(ctx context.Context, c access.Caller) error {
|
|
if err := access.ManageInstance(c); err != nil {
|
|
return err
|
|
}
|
|
err := s.pb.Do(ctx, http.MethodPost, "/api/settings/test/s3", map[string]string{"filesystem": "storage"}, nil)
|
|
var pbErr *pocketbase.Error
|
|
if errors.As(err, &pbErr) && pbErr.Status == http.StatusBadRequest {
|
|
return apperr.Invalid("storage test failed: " + pbErr.Message)
|
|
}
|
|
return err
|
|
}
|