| 1 | package auth |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "context" |
| 6 | "encoding/json" |
| 7 | "fmt" |
| 8 | "net/http" |
| 9 | "strings" |
| 10 | ) |
| 11 | |
| 12 | // Mailer stuurt mail via de auth-server, zonder het e-mailadres te zien. |
| 13 | type Mailer interface { |
| 14 | SendEmail(ctx context.Context, username, subject, html string) error |
| 15 | } |
| 16 | |
| 17 | // SendEmail post naar /api/email met de clientgegevens van deze site. |
| 18 | // Het bearer-token van de gebruiker hoort hier niet bij. |
| 19 | func (t *TimFalken) SendEmail(ctx context.Context, username, subject, htmlBody string) error { |
| 20 | if strings.TrimSpace(t.ClientID) == "" || strings.TrimSpace(t.Secret) == "" { |
| 21 | return fmt.Errorf("auth: geen clientgegevens voor mail") |
| 22 | } |
| 23 | payload, err := json.Marshal(map[string]string{ |
| 24 | "client_id": t.ClientID, |
| 25 | "client_secret": t.Secret, |
| 26 | "username": username, |
| 27 | "subject": subject, |
| 28 | "html": htmlBody, |
| 29 | }) |
| 30 | if err != nil { |
| 31 | return err |
| 32 | } |
| 33 | req, err := http.NewRequestWithContext(ctx, http.MethodPost, t.BaseURL+"/api/email", bytes.NewReader(payload)) |
| 34 | if err != nil { |
| 35 | return err |
| 36 | } |
| 37 | req.Header.Set("Content-Type", "application/json") |
| 38 | req.Header.Set("Accept", "application/json") |
| 39 | req.Header.Set("User-Agent", t.UserAgent) |
| 40 | var body struct { |
| 41 | OK bool `json:"ok"` |
| 42 | Error string `json:"error"` |
| 43 | } |
| 44 | if err := t.do(req, &body); err != nil { |
| 45 | return err |
| 46 | } |
| 47 | if !body.OK { |
| 48 | return fmt.Errorf("auth: email geweigerd") |
| 49 | } |
| 50 | return nil |
| 51 | } |