Send PocketBase's auth emails in the recipient's language
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>
This commit is contained in:
1 parent
cad42fbe89
commit
7f09338b60
13 files changed
+570
-5
No files matched your search
@@ -2,6 +2,16 @@
|
||||
|
||||
What changed in each Docwell release. The release workflow copies a version's section into its release on Gitea.
|
||||
|
||||
## Unreleased
|
||||
|
||||
### Email
|
||||
|
||||
- PocketBase's own emails (email verification, password reset, the magic-link code, email change and new-login
|
||||
alerts) now come in Polish, German, French and Spanish as well as English. Each email uses the language the person
|
||||
last used the app in, or the language of the request when the account has none yet. A password reset that a
|
||||
manager sends goes out in the recipient's language. New-login alerts, which PocketBase sends without being asked,
|
||||
use the language of the last email it sent.
|
||||
|
||||
## 0.3.0 — 2026-11-17
|
||||
|
||||
The AFFiNE parity work ([docs/AFFINE.md](docs/AFFINE.md), phases A–G), the integrations, and the last v2 rows of
|
||||
|
||||
+4
-1
@@ -6,7 +6,10 @@ docwell-db is a stock [PocketBase](https://pocketbase.io): the stack runs
|
||||
docwell-server brings PocketBase up to Docwell's schema itself, every time it starts
|
||||
([`Server/internal/pbschema`](../Server/internal/pbschema/pbschema.go)): missing collections and fields are created,
|
||||
existing ones keep their data. It also writes the `DOCWELL_*` settings (app name and URL, mail, file storage) and
|
||||
sends Docwell's own emails, so PocketBase needs no hooks either.
|
||||
sends Docwell's own emails, so PocketBase needs no hooks either. PocketBase's auth emails (verification, password
|
||||
reset, magic link) use the templates on `users`; docwell-server rewrites them in the recipient's language before
|
||||
each send ([`Server/internal/authmail`](../Server/internal/authmail/authmail.go)), so edits made to them in the
|
||||
PocketBase dashboard do not last.
|
||||
|
||||
This folder is where that schema is written:
|
||||
|
||||
|
||||
@@ -20,6 +20,7 @@ import (
|
||||
"docwell/server/internal/ai"
|
||||
"docwell/server/internal/audit"
|
||||
"docwell/server/internal/auth"
|
||||
"docwell/server/internal/authmail"
|
||||
"docwell/server/internal/calendar"
|
||||
"docwell/server/internal/collab"
|
||||
"docwell/server/internal/config"
|
||||
@@ -83,7 +84,9 @@ func run(log *slog.Logger) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
authMail := authmail.New(db)
|
||||
authSvc := auth.NewService(db, auth.Options{
|
||||
Mail: authMail,
|
||||
Rules: func(ctx context.Context) (bool, []string, error) {
|
||||
rules, err := settingsSvc.Signup(ctx)
|
||||
return rules.Enabled, rules.Domains, err
|
||||
@@ -212,6 +215,7 @@ func run(log *slog.Logger) error {
|
||||
hooks.Listen(integrationsSvc.Listen)
|
||||
dirSvc.SetPublicURL(cfg.PublicURL)
|
||||
dirSvc.SetMaxUpload(int64(cfg.MaxUploadMB) << 20)
|
||||
dirSvc.UseAuthMail(authMail)
|
||||
dirSvc.UseMail(directory.Mailer{Sender: mailer, WebURL: cfg.WebURL, AppName: func(ctx context.Context) string {
|
||||
b, _ := settingsSvc.Branding(ctx)
|
||||
return b.AppName
|
||||
|
||||
@@ -17,6 +17,7 @@ import (
|
||||
"time"
|
||||
|
||||
"docwell/server/internal/access"
|
||||
"docwell/server/internal/authmail"
|
||||
"docwell/server/internal/store/pocketbase"
|
||||
)
|
||||
|
||||
@@ -153,6 +154,9 @@ type Options struct {
|
||||
// OAuthRedirects are the addresses providers may send people back to
|
||||
// (the web app's /oauth/callback, docwell://oauth/callback).
|
||||
OAuthRedirects []string
|
||||
// Mail, when set, writes PocketBase's auth email templates in the
|
||||
// recipient's language before each send.
|
||||
Mail *authmail.Mailer
|
||||
}
|
||||
|
||||
type Service struct {
|
||||
@@ -212,7 +216,9 @@ func (s *Service) RequestOTP(ctx context.Context, email string) (string, error)
|
||||
var res struct {
|
||||
OTPID string `json:"otpId"`
|
||||
}
|
||||
err := s.pb.DoAs(ctx, http.MethodPost, usersPath+"/request-otp", "", map[string]string{"email": strings.TrimSpace(email)}, &res)
|
||||
err := s.mailTo(ctx, email, func() error {
|
||||
return s.pb.DoAs(ctx, http.MethodPost, usersPath+"/request-otp", "", map[string]string{"email": strings.TrimSpace(email)}, &res)
|
||||
})
|
||||
return res.OTPID, mapError(err)
|
||||
}
|
||||
|
||||
@@ -513,7 +519,9 @@ func (s *Service) Methods(ctx context.Context) (Methods, error) {
|
||||
|
||||
// RequestPasswordReset emails a reset link. It succeeds for unknown emails too.
|
||||
func (s *Service) RequestPasswordReset(ctx context.Context, email string) error {
|
||||
return mapError(s.pb.DoAs(ctx, http.MethodPost, usersPath+"/request-password-reset", "", map[string]string{"email": strings.TrimSpace(email)}, nil))
|
||||
return mapError(s.mailTo(ctx, email, func() error {
|
||||
return s.pb.DoAs(ctx, http.MethodPost, usersPath+"/request-password-reset", "", map[string]string{"email": strings.TrimSpace(email)}, nil)
|
||||
}))
|
||||
}
|
||||
|
||||
// ConfirmPasswordReset sets a new password using the emailed token.
|
||||
@@ -525,7 +533,18 @@ func (s *Service) ConfirmPasswordReset(ctx context.Context, token, password stri
|
||||
|
||||
// RequestVerification emails an email-verification link.
|
||||
func (s *Service) RequestVerification(ctx context.Context, email string) error {
|
||||
return mapError(s.pb.DoAs(ctx, http.MethodPost, usersPath+"/request-verification", "", map[string]string{"email": strings.TrimSpace(email)}, nil))
|
||||
return mapError(s.mailTo(ctx, email, func() error {
|
||||
return s.pb.DoAs(ctx, http.MethodPost, usersPath+"/request-verification", "", map[string]string{"email": strings.TrimSpace(email)}, nil)
|
||||
}))
|
||||
}
|
||||
|
||||
// mailTo runs send, which has PocketBase email address, with the templates
|
||||
// in address's language when Options.Mail is set.
|
||||
func (s *Service) mailTo(ctx context.Context, address string, send func() error) error {
|
||||
if s.opts.Mail == nil {
|
||||
return send()
|
||||
}
|
||||
return s.opts.Mail.Send(ctx, s.opts.Mail.LangFor(ctx, address), send)
|
||||
}
|
||||
|
||||
// ConfirmVerification marks the email as verified using the emailed token.
|
||||
|
||||
@@ -13,6 +13,8 @@ import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"docwell/server/internal/authmail"
|
||||
"docwell/server/internal/i18n"
|
||||
"docwell/server/internal/store/pocketbase"
|
||||
)
|
||||
|
||||
@@ -23,6 +25,10 @@ type fakePB struct {
|
||||
passwords map[string]string
|
||||
verifyCalls atomic.Int32
|
||||
mfaFor string // email that requires MFA
|
||||
// resetSubject is the users collection's reset subject now; sentWith
|
||||
// collects it at each password-reset request.
|
||||
resetSubject string
|
||||
sentWith []string
|
||||
}
|
||||
|
||||
func newFakePB(t *testing.T) (*fakePB, *pocketbase.Client) {
|
||||
@@ -142,6 +148,24 @@ func newFakePB(t *testing.T) (*fakePB, *pocketbase.Client) {
|
||||
mux.HandleFunc("POST /api/collections/users/request-verification", func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(204)
|
||||
})
|
||||
mux.HandleFunc("PATCH /api/collections/users", func(w http.ResponseWriter, r *http.Request) {
|
||||
var body struct {
|
||||
Reset struct {
|
||||
Subject string `json:"subject"`
|
||||
} `json:"resetPasswordTemplate"`
|
||||
}
|
||||
json.NewDecoder(r.Body).Decode(&body)
|
||||
f.mu.Lock()
|
||||
f.resetSubject = body.Reset.Subject
|
||||
f.mu.Unlock()
|
||||
reply(w, 200, map[string]any{})
|
||||
})
|
||||
mux.HandleFunc("POST /api/collections/users/request-password-reset", func(w http.ResponseWriter, r *http.Request) {
|
||||
f.mu.Lock()
|
||||
f.sentWith = append(f.sentWith, f.resetSubject)
|
||||
f.mu.Unlock()
|
||||
w.WriteHeader(204)
|
||||
})
|
||||
mux.HandleFunc("POST /api/collections/users/confirm-password-reset", func(w http.ResponseWriter, r *http.Request) {
|
||||
reply(w, 400, map[string]any{"status": 400, "message": "fail", "data": map[string]any{"token": map[string]string{"code": "validation_invalid_token", "message": "Invalid or expired token."}}})
|
||||
})
|
||||
@@ -348,3 +372,25 @@ func TestLoginFillsOrganizationName(t *testing.T) {
|
||||
t.Errorf("user = %+v", sess.User)
|
||||
}
|
||||
}
|
||||
|
||||
// Password-reset emails are written in the person's stored language, else
|
||||
// the request's.
|
||||
func TestPasswordResetInRecipientLanguage(t *testing.T) {
|
||||
f, pb := newFakePB(t)
|
||||
svc := NewService(pb, Options{Mail: authmail.New(pb)})
|
||||
ctx := i18n.WithLang(context.Background(), "de")
|
||||
|
||||
if err := svc.RequestPasswordReset(ctx, "nobody@example.com"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
f.mu.Lock()
|
||||
f.users["ola@example.com"] = map[string]any{"id": "u1", "email": "ola@example.com", "locale": "pl"}
|
||||
f.mu.Unlock()
|
||||
if err := svc.RequestPasswordReset(ctx, "ola@example.com"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want := []string{"Setze dein Passwort für {APP_NAME} zurück", "Zresetuj hasło do {APP_NAME}"}
|
||||
if len(f.sentWith) != 2 || f.sentWith[0] != want[0] || f.sentWith[1] != want[1] {
|
||||
t.Fatalf("sent with %q, want %q", f.sentWith, want)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,192 @@
|
||||
// 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)
|
||||
}
|
||||
@@ -0,0 +1,188 @@
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
package authmail
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"regexp"
|
||||
"slices"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"docwell/server/internal/i18n"
|
||||
"docwell/server/internal/store/pocketbase"
|
||||
)
|
||||
|
||||
func TestCheck(t *testing.T) {
|
||||
if err := Check(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
var placeholder = regexp.MustCompile(`\{[A-Z_]+\}`)
|
||||
|
||||
// Every translation keeps the English template's placeholders and links.
|
||||
func TestTranslationsKeepPlaceholders(t *testing.T) {
|
||||
en, err := Templates(i18n.Default)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
pairs := func(s Set) map[string]Template {
|
||||
return map[string]Template{"verification": s.Verification, "reset": s.ResetPassword,
|
||||
"emailChange": s.ConfirmEmailChange, "otp": s.OTP, "authAlert": s.AuthAlert}
|
||||
}
|
||||
set := func(s string) []string {
|
||||
got := placeholder.FindAllString(s, -1)
|
||||
slices.Sort(got)
|
||||
return slices.Compact(got)
|
||||
}
|
||||
hrefs := regexp.MustCompile(`href="[^"]*"`)
|
||||
for _, lang := range i18n.Supported[1:] {
|
||||
tr, err := Templates(lang)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for name, want := range pairs(en) {
|
||||
got := pairs(tr)[name]
|
||||
if !slices.Equal(set(got.Subject), set(want.Subject)) || !slices.Equal(set(got.Body), set(want.Body)) {
|
||||
t.Errorf("%s %s: placeholders %v / %v, want %v / %v", lang, name,
|
||||
set(got.Subject), set(got.Body), set(want.Subject), set(want.Body))
|
||||
}
|
||||
if !slices.Equal(hrefs.FindAllString(got.Body, -1), hrefs.FindAllString(want.Body, -1)) {
|
||||
t.Errorf("%s %s: links differ from English", lang, name)
|
||||
}
|
||||
if got.Subject == want.Subject {
|
||||
t.Errorf("%s %s: subject not translated", lang, name)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type fakePB struct {
|
||||
mu sync.Mutex
|
||||
patches []map[string]any
|
||||
locale map[string]string // email -> locale
|
||||
sending bool
|
||||
overlap bool
|
||||
}
|
||||
|
||||
func newFake(t *testing.T) (*fakePB, *pocketbase.Client) {
|
||||
f := &fakePB{locale: map[string]string{}}
|
||||
mux := http.NewServeMux()
|
||||
reply := func(w http.ResponseWriter, v any) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
json.NewEncoder(w).Encode(v)
|
||||
}
|
||||
mux.HandleFunc("POST /api/collections/_superusers/auth-with-password", func(w http.ResponseWriter, r *http.Request) {
|
||||
reply(w, map[string]string{"token": "su"})
|
||||
})
|
||||
mux.HandleFunc("PATCH /api/collections/users", func(w http.ResponseWriter, r *http.Request) {
|
||||
var body map[string]any
|
||||
json.NewDecoder(r.Body).Decode(&body)
|
||||
f.mu.Lock()
|
||||
f.patches = append(f.patches, body)
|
||||
f.mu.Unlock()
|
||||
reply(w, map[string]any{})
|
||||
})
|
||||
mux.HandleFunc("GET /api/collections/users/records", func(w http.ResponseWriter, r *http.Request) {
|
||||
m := regexp.MustCompile(`email:lower = '([^']*)'`).FindStringSubmatch(r.URL.Query().Get("filter"))
|
||||
items := []map[string]string{}
|
||||
if m != nil {
|
||||
if l, ok := f.locale[m[1]]; ok {
|
||||
items = append(items, map[string]string{"locale": l})
|
||||
}
|
||||
}
|
||||
reply(w, map[string]any{"page": 1, "perPage": 1, "items": items})
|
||||
})
|
||||
srv := httptest.NewServer(mux)
|
||||
t.Cleanup(srv.Close)
|
||||
return f, pocketbase.New(srv.URL, "su@test", "pw")
|
||||
}
|
||||
|
||||
func subject(p map[string]any) string {
|
||||
return p["verificationTemplate"].(map[string]any)["subject"].(string)
|
||||
}
|
||||
|
||||
func TestSendSwapsOnlyWhenLanguageChanges(t *testing.T) {
|
||||
f, pb := newFake(t)
|
||||
m := New(pb)
|
||||
ctx := context.Background()
|
||||
sent := 0
|
||||
send := func() error { sent++; return nil }
|
||||
for _, lang := range []string{"pl", "pl", "de", "xx", "en"} {
|
||||
if err := m.Send(ctx, lang, send); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if sent != 5 {
|
||||
t.Fatalf("sent %d, want 5", sent)
|
||||
}
|
||||
// pl, de, en (xx falls back to English); the second pl and the final en
|
||||
// need no write.
|
||||
if len(f.patches) != 3 {
|
||||
t.Fatalf("%d patches, want 3", len(f.patches))
|
||||
}
|
||||
if !strings.Contains(subject(f.patches[0]), "Potwierdź") || !strings.Contains(subject(f.patches[1]), "Bestätige") ||
|
||||
!strings.HasPrefix(subject(f.patches[2]), "Verify") {
|
||||
t.Errorf("subjects: %q, %q, %q", subject(f.patches[0]), subject(f.patches[1]), subject(f.patches[2]))
|
||||
}
|
||||
otp := f.patches[0]["otp"].(map[string]any)
|
||||
if len(otp) != 1 || otp["emailTemplate"] == nil {
|
||||
t.Errorf("otp patch touches more than its template: %v", otp)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSendsDoNotOverlap(t *testing.T) {
|
||||
f, pb := newFake(t)
|
||||
m := New(pb)
|
||||
var wg sync.WaitGroup
|
||||
for _, lang := range []string{"pl", "de", "fr", "es", "en", "pl", "de", "fr"} {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
m.Send(context.Background(), lang, func() error {
|
||||
f.mu.Lock()
|
||||
if f.sending {
|
||||
f.overlap = true
|
||||
}
|
||||
f.sending = true
|
||||
f.mu.Unlock()
|
||||
time.Sleep(2 * time.Millisecond)
|
||||
f.mu.Lock()
|
||||
f.sending = false
|
||||
f.mu.Unlock()
|
||||
return nil
|
||||
})
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
if f.overlap {
|
||||
t.Fatal("two sends ran at once")
|
||||
}
|
||||
}
|
||||
|
||||
func TestLangFor(t *testing.T) {
|
||||
f, pb := newFake(t)
|
||||
f.locale["ana@example.com"] = "es"
|
||||
f.locale["old@example.com"] = ""
|
||||
m := New(pb)
|
||||
ctx := i18n.WithLang(context.Background(), "fr")
|
||||
for addr, want := range map[string]string{
|
||||
"Ana@Example.com ": "es", // stored locale, any case
|
||||
"old@example.com": "fr", // no locale: the request's
|
||||
"new@example.com": "fr", // no account: the request's
|
||||
"x'@example.com": "fr", // never reaches a filter
|
||||
} {
|
||||
if got := m.LangFor(ctx, addr); got != want {
|
||||
t.Errorf("LangFor(%q) = %q, want %q", addr, got, want)
|
||||
}
|
||||
}
|
||||
if got := m.LangFor(context.Background(), "new@example.com"); got != i18n.Default {
|
||||
t.Errorf("no request language: %q", got)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
{
|
||||
"verificationTemplate": {
|
||||
"subject": "Bestätige deine E-Mail-Adresse für {APP_NAME}",
|
||||
"body": "<p>Hallo,</p><p>bitte bestätige deine E-Mail-Adresse für {APP_NAME}:</p><p><a href=\"{APP_URL}/verify-email?token={TOKEN}\">E-Mail-Adresse bestätigen</a></p><p>Wenn du kein Konto angelegt hast, kannst du diese E-Mail ignorieren.</p>"
|
||||
},
|
||||
"resetPasswordTemplate": {
|
||||
"subject": "Setze dein Passwort für {APP_NAME} zurück",
|
||||
"body": "<p>Hallo,</p><p>jemand möchte das Passwort deines Kontos bei {APP_NAME} zurücksetzen:</p><p><a href=\"{APP_URL}/reset-password?token={TOKEN}\">Neues Passwort wählen</a></p><p>Wenn du das nicht warst, kannst du diese E-Mail ignorieren.</p>"
|
||||
},
|
||||
"confirmEmailChangeTemplate": {
|
||||
"subject": "Bestätige deine neue E-Mail-Adresse für {APP_NAME}",
|
||||
"body": "<p>Hallo,</p><p>bitte bestätige deine neue E-Mail-Adresse für {APP_NAME}:</p><p><a href=\"{APP_URL}/confirm-email-change?token={TOKEN}\">Neue E-Mail-Adresse bestätigen</a></p>"
|
||||
},
|
||||
"otp": {
|
||||
"subject": "Bei {APP_NAME} anmelden",
|
||||
"body": "<p>Hallo,</p><p>mit diesem Link meldest du dich bei {APP_NAME} an:</p><p><a href=\"{APP_URL}/magic-link?otp={OTP_ID}&code={OTP}\">Anmelden</a></p><p>Oder gib diesen Code ein: <strong>{OTP}</strong></p><p>Link und Code funktionieren einmal, 15 Minuten lang. Wenn du dich nicht anmelden wolltest, kannst du diese E-Mail ignorieren.</p>"
|
||||
},
|
||||
"authAlert": {
|
||||
"subject": "Anmeldung von einem neuen Ort",
|
||||
"body": "<p>Hallo,</p>\n<p>wir haben eine Anmeldung bei deinem Konto bei {APP_NAME} von einem neuen Ort bemerkt:</p>\n<p><em>{ALERT_INFO}</em></p>\n<p><strong>Wenn du das nicht warst, ändere sofort dein Passwort für {APP_NAME}, um allen anderen Orten den Zugriff zu entziehen.</strong></p>\n<p>Wenn du das warst, kannst du diese E-Mail ignorieren.</p>\n<p>\n Danke,<br/>\n dein {APP_NAME}-Team\n</p>"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
{
|
||||
"verificationTemplate": {
|
||||
"subject": "Verifica tu correo de {APP_NAME}",
|
||||
"body": "<p>Hola:</p><p>Confirma tu dirección de correo para {APP_NAME}:</p><p><a href=\"{APP_URL}/verify-email?token={TOKEN}\">Verificar correo</a></p><p>Si no has creado una cuenta, puedes ignorar este correo.</p>"
|
||||
},
|
||||
"resetPasswordTemplate": {
|
||||
"subject": "Restablece tu contraseña de {APP_NAME}",
|
||||
"body": "<p>Hola:</p><p>Alguien ha pedido restablecer la contraseña de tu cuenta de {APP_NAME}:</p><p><a href=\"{APP_URL}/reset-password?token={TOKEN}\">Elegir una contraseña nueva</a></p><p>Si no has sido tú, puedes ignorar este correo.</p>"
|
||||
},
|
||||
"confirmEmailChangeTemplate": {
|
||||
"subject": "Confirma tu nueva dirección de correo de {APP_NAME}",
|
||||
"body": "<p>Hola:</p><p>Confirma tu nueva dirección de correo para {APP_NAME}:</p><p><a href=\"{APP_URL}/confirm-email-change?token={TOKEN}\">Confirmar nuevo correo</a></p>"
|
||||
},
|
||||
"otp": {
|
||||
"subject": "Inicia sesión en {APP_NAME}",
|
||||
"body": "<p>Hola:</p><p>Usa este enlace para iniciar sesión en {APP_NAME}:</p><p><a href=\"{APP_URL}/magic-link?otp={OTP_ID}&code={OTP}\">Iniciar sesión</a></p><p>O introduce este código: <strong>{OTP}</strong></p><p>El enlace y el código funcionan una sola vez, durante 15 minutos. Si no has pedido iniciar sesión, puedes ignorar este correo.</p>"
|
||||
},
|
||||
"authAlert": {
|
||||
"subject": "Inicio de sesión desde una nueva ubicación",
|
||||
"body": "<p>Hola:</p>\n<p>Hemos detectado un inicio de sesión en tu cuenta de {APP_NAME} desde una nueva ubicación:</p>\n<p><em>{ALERT_INFO}</em></p>\n<p><strong>Si no has sido tú, cambia ahora mismo la contraseña de tu cuenta de {APP_NAME} para retirar el acceso desde todas las demás ubicaciones.</strong></p>\n<p>Si has sido tú, puedes ignorar este correo.</p>\n<p>\n Gracias,<br/>\n El equipo de {APP_NAME}\n</p>"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
{
|
||||
"verificationTemplate": {
|
||||
"subject": "Confirmez votre adresse e-mail pour {APP_NAME}",
|
||||
"body": "<p>Bonjour,</p><p>Confirmez votre adresse e-mail pour {APP_NAME} :</p><p><a href=\"{APP_URL}/verify-email?token={TOKEN}\">Confirmer l’adresse e-mail</a></p><p>Si vous n’avez pas créé de compte, vous pouvez ignorer cet e-mail.</p>"
|
||||
},
|
||||
"resetPasswordTemplate": {
|
||||
"subject": "Réinitialisez votre mot de passe {APP_NAME}",
|
||||
"body": "<p>Bonjour,</p><p>Quelqu’un a demandé à réinitialiser le mot de passe de votre compte {APP_NAME} :</p><p><a href=\"{APP_URL}/reset-password?token={TOKEN}\">Choisir un nouveau mot de passe</a></p><p>Si ce n’était pas vous, vous pouvez ignorer cet e-mail.</p>"
|
||||
},
|
||||
"confirmEmailChangeTemplate": {
|
||||
"subject": "Confirmez votre nouvelle adresse e-mail pour {APP_NAME}",
|
||||
"body": "<p>Bonjour,</p><p>Confirmez votre nouvelle adresse e-mail pour {APP_NAME} :</p><p><a href=\"{APP_URL}/confirm-email-change?token={TOKEN}\">Confirmer la nouvelle adresse</a></p>"
|
||||
},
|
||||
"otp": {
|
||||
"subject": "Connectez-vous à {APP_NAME}",
|
||||
"body": "<p>Bonjour,</p><p>Utilisez ce lien pour vous connecter à {APP_NAME} :</p><p><a href=\"{APP_URL}/magic-link?otp={OTP_ID}&code={OTP}\">Se connecter</a></p><p>Ou saisissez ce code : <strong>{OTP}</strong></p><p>Le lien et le code fonctionnent une seule fois, pendant 15 minutes. Si vous n’avez pas demandé à vous connecter, vous pouvez ignorer cet e-mail.</p>"
|
||||
},
|
||||
"authAlert": {
|
||||
"subject": "Connexion depuis un nouvel emplacement",
|
||||
"body": "<p>Bonjour,</p>\n<p>Nous avons remarqué une connexion à votre compte {APP_NAME} depuis un nouvel emplacement :</p>\n<p><em>{ALERT_INFO}</em></p>\n<p><strong>Si ce n’était pas vous, changez immédiatement le mot de passe de votre compte {APP_NAME} pour retirer l’accès à tous les autres emplacements.</strong></p>\n<p>Si c’était vous, vous pouvez ignorer cet e-mail.</p>\n<p>\n Merci,<br/>\n L’équipe {APP_NAME}\n</p>"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
{
|
||||
"verificationTemplate": {
|
||||
"subject": "Potwierdź swój adres e-mail w {APP_NAME}",
|
||||
"body": "<p>Dzień dobry,</p><p>Potwierdź swój adres e-mail w {APP_NAME}:</p><p><a href=\"{APP_URL}/verify-email?token={TOKEN}\">Potwierdź adres e-mail</a></p><p>Jeśli to nie Ty tworzysz konto, możesz zignorować tę wiadomość.</p>"
|
||||
},
|
||||
"resetPasswordTemplate": {
|
||||
"subject": "Zresetuj hasło do {APP_NAME}",
|
||||
"body": "<p>Dzień dobry,</p><p>Ktoś poprosił o zresetowanie hasła do Twojego konta w {APP_NAME}:</p><p><a href=\"{APP_URL}/reset-password?token={TOKEN}\">Ustaw nowe hasło</a></p><p>Jeśli to nie Ty, możesz zignorować tę wiadomość.</p>"
|
||||
},
|
||||
"confirmEmailChangeTemplate": {
|
||||
"subject": "Potwierdź nowy adres e-mail w {APP_NAME}",
|
||||
"body": "<p>Dzień dobry,</p><p>Potwierdź swój nowy adres e-mail w {APP_NAME}:</p><p><a href=\"{APP_URL}/confirm-email-change?token={TOKEN}\">Potwierdź nowy adres</a></p>"
|
||||
},
|
||||
"otp": {
|
||||
"subject": "Zaloguj się do {APP_NAME}",
|
||||
"body": "<p>Dzień dobry,</p><p>Użyj tego linku, aby zalogować się do {APP_NAME}:</p><p><a href=\"{APP_URL}/magic-link?otp={OTP_ID}&code={OTP}\">Zaloguj się</a></p><p>Albo wpisz ten kod: <strong>{OTP}</strong></p><p>Link i kod działają jeden raz, przez 15 minut. Jeśli nie próbujesz się zalogować, możesz zignorować tę wiadomość.</p>"
|
||||
},
|
||||
"authAlert": {
|
||||
"subject": "Logowanie z nowego miejsca",
|
||||
"body": "<p>Dzień dobry,</p>\n<p>Zauważyliśmy logowanie do Twojego konta w {APP_NAME} z nowego miejsca:</p>\n<p><em>{ALERT_INFO}</em></p>\n<p><strong>Jeśli to nie Ty, od razu zmień hasło do {APP_NAME}, aby odebrać dostęp ze wszystkich innych miejsc.</strong></p>\n<p>Jeśli to Ty, możesz zignorować tę wiadomość.</p>\n<p>\n Dziękujemy,<br/>\n zespół {APP_NAME}\n</p>"
|
||||
}
|
||||
}
|
||||
@@ -18,6 +18,7 @@ import (
|
||||
"docwell/server/internal/access"
|
||||
"docwell/server/internal/apperr"
|
||||
"docwell/server/internal/auth"
|
||||
"docwell/server/internal/authmail"
|
||||
"docwell/server/internal/store/pocketbase"
|
||||
)
|
||||
|
||||
@@ -27,6 +28,8 @@ type Service struct {
|
||||
forget func(userID string)
|
||||
docs Docs
|
||||
mailer Mailer
|
||||
// authMail swaps PocketBase's auth templates to the recipient's language.
|
||||
authMail *authmail.Mailer
|
||||
// maxUpload caps one attachment in bytes (0 = 50 MB).
|
||||
maxUpload int64
|
||||
search Searcher
|
||||
|
||||
@@ -18,6 +18,7 @@ import (
|
||||
"docwell/server/internal/access"
|
||||
"docwell/server/internal/apperr"
|
||||
"docwell/server/internal/auth"
|
||||
"docwell/server/internal/authmail"
|
||||
"docwell/server/internal/i18n"
|
||||
"docwell/server/internal/mail"
|
||||
"docwell/server/internal/store/pocketbase"
|
||||
@@ -45,6 +46,10 @@ type Mailer struct {
|
||||
// UseMail enables invite emails.
|
||||
func (s *Service) UseMail(m Mailer) { s.mailer = m }
|
||||
|
||||
// UseAuthMail has PocketBase's password-reset emails written in the
|
||||
// recipient's language.
|
||||
func (s *Service) UseAuthMail(m *authmail.Mailer) { s.authMail = m }
|
||||
|
||||
type Invite struct {
|
||||
ID string `json:"id"`
|
||||
Email string `json:"email"`
|
||||
@@ -549,5 +554,12 @@ func (s *Service) SendPasswordReset(ctx context.Context, c access.Caller, id str
|
||||
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)
|
||||
send := func() error {
|
||||
return s.pb.Do(ctx, http.MethodPost, "/api/collections/users/request-password-reset", map[string]string{"email": t.Email}, nil)
|
||||
}
|
||||
if s.authMail == nil {
|
||||
return send()
|
||||
}
|
||||
// In the language of the person it goes to, not the manager's.
|
||||
return s.authMail.Send(ctx, userLang(t.Locale), send)
|
||||
}
|
||||
Reference in new issue
Block a user