Sign-in:
- Google, GitHub, Microsoft and any OpenID Connect provider, set up in the
admin panel (secrets are write-only). PocketBase talks to the provider,
and docwell-server keeps the state and PKCE verifier. Accounts a
provider creates follow the sign-up switch and the domain list; refused
ones are removed again.
- Two-step sign-in with an authenticator app (TOTP), set up under "Your
account", with ten single-use recovery codes. After any first factor
(password, email code, provider) the session is held behind a
five-minute challenge: five tries, each code works once. Turning it off
needs a code. Managers can reset it for someone who lost their phone.
Both the web app and the admin panel ask for the code.
Integrations:
- Personal API tokens ("dw_…") that act as their owner, read-only or
read-write, with optional expiry. Only a hash is stored, and the token is
shown once. Tokens cannot manage tokens or two-step sign-in. Admins see
and can revoke their organization's tokens.
- Workspace webhooks for page, comment and space events. Deliveries are
HMAC-SHA256 signed and retried (10 s, 1 min, 5 min), with a 30-day log
and a test button. Loopback and link-local addresses are refused
(DOCWELL_WEBHOOKS_ALLOW_LOCAL is for development).
Audit log: sign-ins (including failures and second steps, filed under the
account's organization) and every successful change request, by route and
path ids, never bodies. Superadmins see everything and org admins their
organization. It is searchable and exportable as CSV in the admin panel's
new Security page, and kept for DOCWELL_AUDIT_RETENTION_DAYS (365).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
631 lines
19 KiB
Go
631 lines
19 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/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"
|
|
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
|
|
}
|
|
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; with a username set, assume one is stored.
|
|
PasswordSet: pb.SMTP.Username != "", 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.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.Render(to, "test", map[string]string{"AppName": b.AppName})
|
|
if err != nil {
|
|
return err
|
|
}
|
|
if err := s.mail.Send(ctx, m); err != nil {
|
|
var pbErr *pocketbase.Error
|
|
if errors.As(err, &pbErr) {
|
|
return apperr.Invalid("the mail server rejected the message: " + pbErr.Message)
|
|
}
|
|
return err
|
|
}
|
|
return 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
|
|
}
|