| 1 | package auth |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "encoding/json" |
| 6 | "io" |
| 7 | "net/http" |
| 8 | "net/http/httptest" |
| 9 | "strings" |
| 10 | "testing" |
| 11 | ) |
| 12 | |
| 13 | func TestSendEmail(t *testing.T) { |
| 14 | var got struct { |
| 15 | ClientID string `json:"client_id"` |
| 16 | ClientSecret string `json:"client_secret"` |
| 17 | Username string `json:"username"` |
| 18 | Subject string `json:"subject"` |
| 19 | HTML string `json:"html"` |
| 20 | } |
| 21 | var authz, ctype, accept, ua string |
| 22 | ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 23 | if r.URL.Path != "/api/email" || r.Method != http.MethodPost { |
| 24 | t.Errorf("pad %s %s", r.Method, r.URL.Path) |
| 25 | } |
| 26 | authz = r.Header.Get("Authorization") |
| 27 | ctype = r.Header.Get("Content-Type") |
| 28 | accept = r.Header.Get("Accept") |
| 29 | ua = r.Header.Get("User-Agent") |
| 30 | raw, _ := io.ReadAll(r.Body) |
| 31 | if err := json.Unmarshal(raw, &got); err != nil { |
| 32 | t.Error(err) |
| 33 | } |
| 34 | w.Header().Set("Content-Type", "application/json") |
| 35 | _, _ = w.Write([]byte(`{"ok":true}`)) |
| 36 | })) |
| 37 | t.Cleanup(ts.Close) |
| 38 | client := NewTimFalken(ts.URL, "bluegit.test", "site-secret", "BlueGitAccountClient/0.1") |
| 39 | if err := client.SendEmail(context.Background(), "tim", "Pipeline failed", "<p>hallo</p>"); err != nil { |
| 40 | t.Fatal(err) |
| 41 | } |
| 42 | if authz != "" { |
| 43 | t.Fatal("mail gebruikt geen bearer-token") |
| 44 | } |
| 45 | if ctype != "application/json" || accept != "application/json" || ua != "BlueGitAccountClient/0.1" { |
| 46 | t.Fatalf("headers %s %s %s", ctype, accept, ua) |
| 47 | } |
| 48 | if got.ClientID != "bluegit.test" || got.ClientSecret != "site-secret" || got.Username != "tim" || got.Subject != "Pipeline failed" || got.HTML != "<p>hallo</p>" { |
| 49 | t.Fatalf("body klopt niet: id=%s user=%s subject=%s html=%s secret-ok=%v", got.ClientID, got.Username, got.Subject, got.HTML, got.ClientSecret == "site-secret") |
| 50 | } |
| 51 | |
| 52 | client.Secret = "" |
| 53 | if err := client.SendEmail(context.Background(), "tim", "x", "<p>x</p>"); err == nil { |
| 54 | t.Fatal("zonder geheim hoort mail te weigeren") |
| 55 | } |
| 56 | |
| 57 | denied := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 58 | w.Header().Set("Content-Type", "application/json") |
| 59 | w.WriteHeader(http.StatusForbidden) |
| 60 | _, _ = w.Write([]byte(`{"error":"This user has turned off email from this site.","code":"email_opted_out"}`)) |
| 61 | })) |
| 62 | t.Cleanup(denied.Close) |
| 63 | client = NewTimFalken(denied.URL, "bluegit.test", "site-secret", "BlueGitAccountClient/0.1") |
| 64 | err := client.SendEmail(context.Background(), "tim", "x", "<p>x</p>") |
| 65 | if err == nil || !strings.Contains(err.Error(), "turned off") { |
| 66 | t.Fatal(err) |
| 67 | } |
| 68 | } |