-
Notifications
You must be signed in to change notification settings - Fork 0
/
payload.go
68 lines (56 loc) · 1.66 KB
/
payload.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
56
57
58
59
60
61
62
63
64
65
66
67
68
package gometawebhooks
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
)
const (
HeaderSignatureName = "X-Hub-Signature-256"
)
var (
ErrMissingHubSignatureHeader = errors.New("missing signature value")
ErrHMACVerificationFailed = errors.New("HMAC verification failed")
ErrParsingPayload = errors.New("parsing payload")
ErrInvalidPayload = errors.New("invalid payload")
)
func (hooks Webhooks) ParsePayload(body []byte) (Event, error) {
var event Event
if err := json.Unmarshal(body, &event); err != nil {
return event, wrapErr(err, ErrParsingPayload)
}
return event, nil
}
func (hooks Webhooks) ValidatePayload(body []byte) error {
if validationSchema == nil {
return ErrMissingSchema
}
var pl interface{}
if err := json.Unmarshal(body, &pl); err != nil {
return wrapErr(err, ErrParsingPayload)
}
if err := validationSchema.Validate(pl); err != nil {
return wrapErr(err, ErrInvalidPayload)
}
return nil
}
func (hooks Webhooks) VerifyPayload(body []byte, headers map[string]string) error {
// If we have a Secret set, we should check the MAC
// https://developers.facebook.com/docs/messenger-platform/webhooks#validate-payloads
if len(hooks.secret) == 0 {
return nil
}
signature := headers[hooks.headerSigName]
if len(signature) == 0 {
return fmt.Errorf("missing %s Header: %w", hooks.headerSigName, ErrMissingHubSignatureHeader)
}
mac := hmac.New(sha256.New, []byte(hooks.secret))
mac.Write(body)
expectedMAC := hex.EncodeToString(mac.Sum(nil))
if len(signature) <= 8 || !hmac.Equal([]byte(signature[7:]), []byte(expectedMAC)) {
return ErrHMACVerificationFailed
}
return nil
}