From 7f09338b600ba8dce5eb3f16a609f632a77cc480 Mon Sep 17 00:00:00 2001 From: tajniak81 <13187254+tajniak81@users.noreply.github.com> Date: Tue, 17 Nov 2026 11:39:58 +0100 Subject: [PATCH] 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 --- CHANGELOG.md | 10 ++ Database/README.md | 5 +- Server/cmd/docwell-server/main.go | 4 + Server/internal/auth/auth.go | 25 ++- Server/internal/auth/auth_test.go | 46 +++++ Server/internal/authmail/authmail.go | 192 +++++++++++++++++++++ Server/internal/authmail/authmail_test.go | 188 ++++++++++++++++++++ Server/internal/authmail/templates/de.json | 22 +++ Server/internal/authmail/templates/es.json | 22 +++ Server/internal/authmail/templates/fr.json | 22 +++ Server/internal/authmail/templates/pl.json | 22 +++ Server/internal/directory/directory.go | 3 + Server/internal/directory/invites.go | 14 +- 13 files changed, 570 insertions(+), 5 deletions(-) create mode 100644 Server/internal/authmail/authmail.go create mode 100644 Server/internal/authmail/authmail_test.go create mode 100644 Server/internal/authmail/templates/de.json create mode 100644 Server/internal/authmail/templates/es.json create mode 100644 Server/internal/authmail/templates/fr.json create mode 100644 Server/internal/authmail/templates/pl.json diff --git a/CHANGELOG.md b/CHANGELOG.md index f0594b4..260e520 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -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 diff --git a/Database/README.md b/Database/README.md index 1725ed3..a264cec 100644 --- a/Database/README.md +++ b/Database/README.md @@ -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: diff --git a/Server/cmd/docwell-server/main.go b/Server/cmd/docwell-server/main.go index 6c1777c..44bd875 100644 --- a/Server/cmd/docwell-server/main.go +++ b/Server/cmd/docwell-server/main.go @@ -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 diff --git a/Server/internal/auth/auth.go b/Server/internal/auth/auth.go index 3fbd3ef..31bd47f 100644 --- a/Server/internal/auth/auth.go +++ b/Server/internal/auth/auth.go @@ -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. diff --git a/Server/internal/auth/auth_test.go b/Server/internal/auth/auth_test.go index f1c3821..c2e61c2 100644 --- a/Server/internal/auth/auth_test.go +++ b/Server/internal/auth/auth_test.go @@ -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) + } +} diff --git a/Server/internal/authmail/authmail.go b/Server/internal/authmail/authmail.go new file mode 100644 index 0000000..68460e8 --- /dev/null +++ b/Server/internal/authmail/authmail.go @@ -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/.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/.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) +} diff --git a/Server/internal/authmail/authmail_test.go b/Server/internal/authmail/authmail_test.go new file mode 100644 index 0000000..dbeeb94 --- /dev/null +++ b/Server/internal/authmail/authmail_test.go @@ -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) + } +} diff --git a/Server/internal/authmail/templates/de.json b/Server/internal/authmail/templates/de.json new file mode 100644 index 0000000..5a41438 --- /dev/null +++ b/Server/internal/authmail/templates/de.json @@ -0,0 +1,22 @@ +{ + "verificationTemplate": { + "subject": "Bestätige deine E-Mail-Adresse für {APP_NAME}", + "body": "

Hallo,

bitte bestätige deine E-Mail-Adresse für {APP_NAME}:

E-Mail-Adresse bestätigen

Wenn du kein Konto angelegt hast, kannst du diese E-Mail ignorieren.

" + }, + "resetPasswordTemplate": { + "subject": "Setze dein Passwort für {APP_NAME} zurück", + "body": "

Hallo,

jemand möchte das Passwort deines Kontos bei {APP_NAME} zurücksetzen:

Neues Passwort wählen

Wenn du das nicht warst, kannst du diese E-Mail ignorieren.

" + }, + "confirmEmailChangeTemplate": { + "subject": "Bestätige deine neue E-Mail-Adresse für {APP_NAME}", + "body": "

Hallo,

bitte bestätige deine neue E-Mail-Adresse für {APP_NAME}:

Neue E-Mail-Adresse bestätigen

" + }, + "otp": { + "subject": "Bei {APP_NAME} anmelden", + "body": "

Hallo,

mit diesem Link meldest du dich bei {APP_NAME} an:

Anmelden

Oder gib diesen Code ein: {OTP}

Link und Code funktionieren einmal, 15 Minuten lang. Wenn du dich nicht anmelden wolltest, kannst du diese E-Mail ignorieren.

" + }, + "authAlert": { + "subject": "Anmeldung von einem neuen Ort", + "body": "

Hallo,

\n

wir haben eine Anmeldung bei deinem Konto bei {APP_NAME} von einem neuen Ort bemerkt:

\n

{ALERT_INFO}

\n

Wenn du das nicht warst, ändere sofort dein Passwort für {APP_NAME}, um allen anderen Orten den Zugriff zu entziehen.

\n

Wenn du das warst, kannst du diese E-Mail ignorieren.

\n

\n Danke,
\n dein {APP_NAME}-Team\n

" + } +} diff --git a/Server/internal/authmail/templates/es.json b/Server/internal/authmail/templates/es.json new file mode 100644 index 0000000..a910f8c --- /dev/null +++ b/Server/internal/authmail/templates/es.json @@ -0,0 +1,22 @@ +{ + "verificationTemplate": { + "subject": "Verifica tu correo de {APP_NAME}", + "body": "

Hola:

Confirma tu dirección de correo para {APP_NAME}:

Verificar correo

Si no has creado una cuenta, puedes ignorar este correo.

" + }, + "resetPasswordTemplate": { + "subject": "Restablece tu contraseña de {APP_NAME}", + "body": "

Hola:

Alguien ha pedido restablecer la contraseña de tu cuenta de {APP_NAME}:

Elegir una contraseña nueva

Si no has sido tú, puedes ignorar este correo.

" + }, + "confirmEmailChangeTemplate": { + "subject": "Confirma tu nueva dirección de correo de {APP_NAME}", + "body": "

Hola:

Confirma tu nueva dirección de correo para {APP_NAME}:

Confirmar nuevo correo

" + }, + "otp": { + "subject": "Inicia sesión en {APP_NAME}", + "body": "

Hola:

Usa este enlace para iniciar sesión en {APP_NAME}:

Iniciar sesión

O introduce este código: {OTP}

El enlace y el código funcionan una sola vez, durante 15 minutos. Si no has pedido iniciar sesión, puedes ignorar este correo.

" + }, + "authAlert": { + "subject": "Inicio de sesión desde una nueva ubicación", + "body": "

Hola:

\n

Hemos detectado un inicio de sesión en tu cuenta de {APP_NAME} desde una nueva ubicación:

\n

{ALERT_INFO}

\n

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.

\n

Si has sido tú, puedes ignorar este correo.

\n

\n Gracias,
\n El equipo de {APP_NAME}\n

" + } +} diff --git a/Server/internal/authmail/templates/fr.json b/Server/internal/authmail/templates/fr.json new file mode 100644 index 0000000..06d3741 --- /dev/null +++ b/Server/internal/authmail/templates/fr.json @@ -0,0 +1,22 @@ +{ + "verificationTemplate": { + "subject": "Confirmez votre adresse e-mail pour {APP_NAME}", + "body": "

Bonjour,

Confirmez votre adresse e-mail pour {APP_NAME} :

Confirmer l’adresse e-mail

Si vous n’avez pas créé de compte, vous pouvez ignorer cet e-mail.

" + }, + "resetPasswordTemplate": { + "subject": "Réinitialisez votre mot de passe {APP_NAME}", + "body": "

Bonjour,

Quelqu’un a demandé à réinitialiser le mot de passe de votre compte {APP_NAME} :

Choisir un nouveau mot de passe

Si ce n’était pas vous, vous pouvez ignorer cet e-mail.

" + }, + "confirmEmailChangeTemplate": { + "subject": "Confirmez votre nouvelle adresse e-mail pour {APP_NAME}", + "body": "

Bonjour,

Confirmez votre nouvelle adresse e-mail pour {APP_NAME} :

Confirmer la nouvelle adresse

" + }, + "otp": { + "subject": "Connectez-vous à {APP_NAME}", + "body": "

Bonjour,

Utilisez ce lien pour vous connecter à {APP_NAME} :

Se connecter

Ou saisissez ce code : {OTP}

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.

" + }, + "authAlert": { + "subject": "Connexion depuis un nouvel emplacement", + "body": "

Bonjour,

\n

Nous avons remarqué une connexion à votre compte {APP_NAME} depuis un nouvel emplacement :

\n

{ALERT_INFO}

\n

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.

\n

Si c’était vous, vous pouvez ignorer cet e-mail.

\n

\n Merci,
\n L’équipe {APP_NAME}\n

" + } +} diff --git a/Server/internal/authmail/templates/pl.json b/Server/internal/authmail/templates/pl.json new file mode 100644 index 0000000..bc1ceb6 --- /dev/null +++ b/Server/internal/authmail/templates/pl.json @@ -0,0 +1,22 @@ +{ + "verificationTemplate": { + "subject": "Potwierdź swój adres e-mail w {APP_NAME}", + "body": "

Dzień dobry,

Potwierdź swój adres e-mail w {APP_NAME}:

Potwierdź adres e-mail

Jeśli to nie Ty tworzysz konto, możesz zignorować tę wiadomość.

" + }, + "resetPasswordTemplate": { + "subject": "Zresetuj hasło do {APP_NAME}", + "body": "

Dzień dobry,

Ktoś poprosił o zresetowanie hasła do Twojego konta w {APP_NAME}:

Ustaw nowe hasło

Jeśli to nie Ty, możesz zignorować tę wiadomość.

" + }, + "confirmEmailChangeTemplate": { + "subject": "Potwierdź nowy adres e-mail w {APP_NAME}", + "body": "

Dzień dobry,

Potwierdź swój nowy adres e-mail w {APP_NAME}:

Potwierdź nowy adres

" + }, + "otp": { + "subject": "Zaloguj się do {APP_NAME}", + "body": "

Dzień dobry,

Użyj tego linku, aby zalogować się do {APP_NAME}:

Zaloguj się

Albo wpisz ten kod: {OTP}

Link i kod działają jeden raz, przez 15 minut. Jeśli nie próbujesz się zalogować, możesz zignorować tę wiadomość.

" + }, + "authAlert": { + "subject": "Logowanie z nowego miejsca", + "body": "

Dzień dobry,

\n

Zauważyliśmy logowanie do Twojego konta w {APP_NAME} z nowego miejsca:

\n

{ALERT_INFO}

\n

Jeśli to nie Ty, od razu zmień hasło do {APP_NAME}, aby odebrać dostęp ze wszystkich innych miejsc.

\n

Jeśli to Ty, możesz zignorować tę wiadomość.

\n

\n Dziękujemy,
\n zespół {APP_NAME}\n

" + } +} diff --git a/Server/internal/directory/directory.go b/Server/internal/directory/directory.go index ab22de6..aa2e202 100644 --- a/Server/internal/directory/directory.go +++ b/Server/internal/directory/directory.go @@ -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 diff --git a/Server/internal/directory/invites.go b/Server/internal/directory/invites.go index 8266853..068de55 100644 --- a/Server/internal/directory/invites.go +++ b/Server/internal/directory/invites.go @@ -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) }