Skip to content

Commit

Permalink
feat: add webhook env var decoder
Browse files Browse the repository at this point in the history
  • Loading branch information
lfleischmann authored Jul 12, 2024
1 parent 0c9e2f5 commit a0aaf53
Show file tree
Hide file tree
Showing 3 changed files with 43 additions and 0 deletions.
21 changes: 21 additions & 0 deletions backend/config/webhook_config.go
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
package config

import (
"encoding/json"
"fmt"
"github.com/teamhanko/hanko/backend/webhooks/events"
"net/url"
"strings"
)

type WebhookSettings struct {
Expand All @@ -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"`
Expand Down
18 changes: 18 additions & 0 deletions backend/config/webhook_config_test.go
Original file line number Diff line number Diff line change
@@ -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)
}
}
4 changes: 4 additions & 0 deletions backend/docs/Config.md
Original file line number Diff line number Diff line change
Expand Up @@ -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: "<YOUR WEBHOOK ENDPOINT URL>"
##
#
Expand Down

0 comments on commit a0aaf53

Please sign in to comment.