From bf7cef54b1a82994929a20bfb849becf2b5d0961 Mon Sep 17 00:00:00 2001 From: Lennart Fleischmann Date: Fri, 12 Jul 2024 12:52:07 +0200 Subject: [PATCH] feat: add webhook env var decoder --- backend/config/webhook_config.go | 21 +++++++++++++++++++++ backend/config/webhook_config_test.go | 18 ++++++++++++++++++ backend/docs/Config.md | 4 ++++ 3 files changed, 43 insertions(+) create mode 100644 backend/config/webhook_config_test.go diff --git a/backend/config/webhook_config.go b/backend/config/webhook_config.go index fad155505..b2621c0a8 100644 --- a/backend/config/webhook_config.go +++ b/backend/config/webhook_config.go @@ -1,9 +1,11 @@ package config import ( + "encoding/json" "fmt" "github.com/teamhanko/hanko/backend/webhooks/events" "net/url" + "strings" ) type WebhookSettings struct { @@ -27,6 +29,25 @@ func (ws *WebhookSettings) Validate() error { type Webhooks []Webhook +// Decode is an implementation of the envconfig.Decoder interface. +// Assumes that environment variables (for the WEBHOOKS_HOOKS key) have the following format: +// {"callback":"http://app.com/usercb","events":["user"]};{"callback":"http://app.com/emailcb","events":["email.send"]} +func (wd *Webhooks) Decode(value string) error { + webhooks := Webhooks{} + hooks := strings.Split(value, ";") + for _, hook := range hooks { + webhook := Webhook{} + err := json.Unmarshal([]byte(hook), &webhook) + if err != nil { + return fmt.Errorf("invalid map json: %w", err) + } + webhooks = append(webhooks, webhook) + + } + *wd = webhooks + return nil +} + type Webhook struct { Callback string `yaml:"callback" json:"callback,omitempty" koanf:"callback"` Events events.Events `yaml:"events" json:"events,omitempty" koanf:"events"` diff --git a/backend/config/webhook_config_test.go b/backend/config/webhook_config_test.go new file mode 100644 index 000000000..606b93e2e --- /dev/null +++ b/backend/config/webhook_config_test.go @@ -0,0 +1,18 @@ +package config + +import ( + "github.com/stretchr/testify/assert" + "testing" +) + +func TestWebhooks_Decode(t *testing.T) { + webhooks := Webhooks{} + value := "{\"callback\":\"http://app.com/usercb\",\"events\":[\"user\"]};{\"callback\":\"http://app.com/callback\",\"events\":[\"email.send\"]}" + err := webhooks.Decode(value) + + assert.NoError(t, err) + assert.Len(t, webhooks, 2, "has 2 elements") + for _, webhook := range webhooks { + assert.IsType(t, Webhook{}, webhook) + } +} diff --git a/backend/docs/Config.md b/backend/docs/Config.md index d1ff17060..3b38fab85 100644 --- a/backend/docs/Config.md +++ b/backend/docs/Config.md @@ -1016,6 +1016,10 @@ webhooks: # # Callback - Endpoint URL to which the change data will be sent # + # NOTE: When using environment variables hooks must be defined as in the following example: + # + # WEBHOOKS_HOOKS={"callback":"http://app.com/usercb","events":["user"]};{"callback":"http://app.com/emailcb","events":["email.send"]} + # - callback: "" ## #