PocketBase keeps one set of email templates on the users collection, so before docwell-server asks it for a verification, password-reset or magic-link email, the new authmail package writes the templates in the recipient's language (stored locale, else the request's), one send at a time. Adds Polish, German, French and Spanish templates; English stays in the schema snapshot. New-login alerts use the language written last. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
193 lines
6.3 KiB
Go
193 lines
6.3 KiB
Go
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
|
|
// Package authmail puts PocketBase's own emails (email verification,
|
|
// password reset, the magic-link code, email change, new-login alerts) in
|
|
// the language of the person they go to.
|
|
//
|
|
// PocketBase keeps one set of these templates on the "users" collection, not
|
|
// one per person, and docwell-db runs a stock PocketBase with no hooks. So
|
|
// before docwell-server asks PocketBase to send one of them, Mailer writes
|
|
// the templates of the person's language onto "users", and it lets one such
|
|
// send run at a time. PocketBase reads the templates when the request
|
|
// arrives, so the next swap cannot change a mail already on its way.
|
|
//
|
|
// The English templates are the ones in pbschema's snapshot (from the
|
|
// migrations); templates/<lang>.json hold the translations. Emails that
|
|
// PocketBase sends unasked, the new-login alert, go out in whichever
|
|
// language was written last.
|
|
package authmail
|
|
|
|
import (
|
|
"context"
|
|
"embed"
|
|
"encoding/json"
|
|
"fmt"
|
|
"net/http"
|
|
"strings"
|
|
"sync"
|
|
|
|
"docwell/server/internal/i18n"
|
|
"docwell/server/internal/pbschema"
|
|
"docwell/server/internal/store/pocketbase"
|
|
)
|
|
|
|
// Template is one email: subject and HTML body with PocketBase's
|
|
// placeholders ({APP_NAME}, {APP_URL}, {TOKEN}, {OTP}, ...).
|
|
type Template struct {
|
|
Subject string `json:"subject"`
|
|
Body string `json:"body"`
|
|
}
|
|
|
|
// Set is the templates of one language, keyed like the fields of the users
|
|
// collection that hold them.
|
|
type Set struct {
|
|
Verification Template `json:"verificationTemplate"`
|
|
ResetPassword Template `json:"resetPasswordTemplate"`
|
|
ConfirmEmailChange Template `json:"confirmEmailChangeTemplate"`
|
|
OTP Template `json:"otp"`
|
|
AuthAlert Template `json:"authAlert"`
|
|
}
|
|
|
|
//go:embed templates/*.json
|
|
var files embed.FS
|
|
|
|
// Templates returns the set for lang: English from pbschema's snapshot,
|
|
// the others from templates/<lang>.json.
|
|
func Templates(lang string) (Set, error) {
|
|
if lang == i18n.Default {
|
|
return english()
|
|
}
|
|
raw, err := files.ReadFile("templates/" + lang + ".json")
|
|
if err != nil {
|
|
return Set{}, fmt.Errorf("authmail: no templates for %q", lang)
|
|
}
|
|
var s Set
|
|
if err := json.Unmarshal(raw, &s); err != nil {
|
|
return Set{}, fmt.Errorf("authmail: templates/%s.json: %w", lang, err)
|
|
}
|
|
return s, nil
|
|
}
|
|
|
|
func english() (Set, error) {
|
|
cols, err := pbschema.Collections()
|
|
if err != nil {
|
|
return Set{}, err
|
|
}
|
|
for _, c := range cols {
|
|
if c["name"] != "users" {
|
|
continue
|
|
}
|
|
raw, err := json.Marshal(c)
|
|
if err != nil {
|
|
return Set{}, err
|
|
}
|
|
var u struct {
|
|
Verification Template `json:"verificationTemplate"`
|
|
ResetPassword Template `json:"resetPasswordTemplate"`
|
|
ConfirmEmailChange Template `json:"confirmEmailChangeTemplate"`
|
|
OTP struct {
|
|
EmailTemplate Template `json:"emailTemplate"`
|
|
} `json:"otp"`
|
|
AuthAlert struct {
|
|
EmailTemplate Template `json:"emailTemplate"`
|
|
} `json:"authAlert"`
|
|
}
|
|
if err := json.Unmarshal(raw, &u); err != nil {
|
|
return Set{}, err
|
|
}
|
|
return Set{u.Verification, u.ResetPassword, u.ConfirmEmailChange, u.OTP.EmailTemplate, u.AuthAlert.EmailTemplate}, nil
|
|
}
|
|
return Set{}, fmt.Errorf("authmail: pbschema has no users collection")
|
|
}
|
|
|
|
// Check reports a language with missing or unreadable templates (for tests
|
|
// and start-up).
|
|
func Check() error {
|
|
for _, lang := range i18n.Supported {
|
|
s, err := Templates(lang)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
for name, t := range map[string]Template{
|
|
"verificationTemplate": s.Verification, "resetPasswordTemplate": s.ResetPassword,
|
|
"confirmEmailChangeTemplate": s.ConfirmEmailChange, "otp": s.OTP, "authAlert": s.AuthAlert,
|
|
} {
|
|
if strings.TrimSpace(t.Subject) == "" || strings.TrimSpace(t.Body) == "" {
|
|
return fmt.Errorf("authmail: %s: %s is empty", lang, name)
|
|
}
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
// patch is the body that writes s onto the users collection. otp and
|
|
// authAlert are partial: PocketBase merges them, so their other settings
|
|
// (the admin panel's magic-link switch, durations) stay.
|
|
func (s Set) patch() map[string]any {
|
|
return map[string]any{
|
|
"verificationTemplate": s.Verification,
|
|
"resetPasswordTemplate": s.ResetPassword,
|
|
"confirmEmailChangeTemplate": s.ConfirmEmailChange,
|
|
"otp": map[string]any{"emailTemplate": s.OTP},
|
|
"authAlert": map[string]any{"emailTemplate": s.AuthAlert},
|
|
}
|
|
}
|
|
|
|
// Mailer swaps the users templates to a person's language around a send.
|
|
type Mailer struct {
|
|
pb *pocketbase.Client
|
|
mu sync.Mutex
|
|
current string // language on the users collection now; "" = unknown
|
|
}
|
|
|
|
// New returns a Mailer for pb. It assumes nothing about the templates
|
|
// PocketBase has, so its first send always writes them.
|
|
func New(pb *pocketbase.Client) *Mailer { return &Mailer{pb: pb} }
|
|
|
|
// Send runs send, which asks PocketBase to email someone, with the users
|
|
// templates in lang (an unsupported lang is English). Sends run one at a
|
|
// time. When the templates cannot be written, send still runs, in whatever
|
|
// language PocketBase has: a mail in the wrong language beats none.
|
|
func (m *Mailer) Send(ctx context.Context, lang string, send func() error) error {
|
|
if !i18n.IsSupported(lang) {
|
|
lang = i18n.Default
|
|
}
|
|
m.mu.Lock()
|
|
defer m.mu.Unlock()
|
|
if m.current != lang {
|
|
if err := m.write(ctx, lang); err != nil {
|
|
m.current = ""
|
|
} else {
|
|
m.current = lang
|
|
}
|
|
}
|
|
return send()
|
|
}
|
|
|
|
func (m *Mailer) write(ctx context.Context, lang string) error {
|
|
s, err := Templates(lang)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
return m.pb.Do(ctx, http.MethodPatch, "/api/collections/users", s.patch(), nil)
|
|
}
|
|
|
|
// LangFor picks the language of an email to address: the language its
|
|
// account last used the app in, else the language of the request (ctx),
|
|
// else English.
|
|
func (m *Mailer) LangFor(ctx context.Context, address string) string {
|
|
address = strings.ToLower(strings.TrimSpace(address))
|
|
if strings.ContainsAny(address, `'"\`+"`") || !strings.Contains(address, "@") {
|
|
return i18n.Lang(ctx)
|
|
}
|
|
res, err := pocketbase.List[struct {
|
|
Locale string `json:"locale"`
|
|
}](ctx, m.pb, "users", pocketbase.ListOptions{
|
|
PerPage: 1, Filter: fmt.Sprintf("email:lower = '%s'", address), Fields: "locale",
|
|
})
|
|
if err == nil && len(res.Items) > 0 && i18n.IsSupported(res.Items[0].Locale) {
|
|
return res.Items[0].Locale
|
|
}
|
|
return i18n.Lang(ctx)
|
|
}
|