-
Notifications
You must be signed in to change notification settings - Fork 5
/
event.go
55 lines (48 loc) · 1.3 KB
/
event.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
package webhook // import "github.com/veonik/squircy2/webhook"
import (
"crypto/hmac"
"crypto/sha1"
"encoding/hex"
"errors"
"fmt"
"strings"
"github.com/veonik/squircy2/event"
)
type WebhookEvent struct {
Body []byte
ContentType string
Signature string
Webhook *Webhook
}
// Process a webhook event
func (e *WebhookEvent) Process(evt event.EventManager) error {
if err := e.CheckPayloadSignature(); err != nil {
return err
}
d := map[string]interface{}{
"Body": string(e.Body),
"ContentType": e.ContentType,
"Signature": e.Signature,
"Webhook": e.Webhook.ID,
}
evt.Trigger(event.EventType(fmt.Sprintf("hook.%d", e.Webhook.ID)), d)
evt.Trigger(event.EventType("hook.WILDCARD"), d)
return nil
}
// CheckPayloadSignature calculates and verifies SHA1 signature of the given payload
func (e *WebhookEvent) CheckPayloadSignature() error {
if strings.HasPrefix(e.Signature, "sha1=") {
signature := e.Signature[5:]
mac := hmac.New(sha1.New, []byte(e.Webhook.Key))
_, err := mac.Write(e.Body)
if err != nil {
return err
}
expectedMAC := hex.EncodeToString(mac.Sum(nil))
if !hmac.Equal([]byte(signature), []byte(expectedMAC)) {
return errors.New("webhook: signature does not match")
}
return nil
}
return errors.New("webhook: only sha1 signature handled")
}