This repository has been archived by the owner on Mar 19, 2024. It is now read-only.
/
Helper.go
86 lines (71 loc) · 2.45 KB
/
Helper.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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
package webhooks
import (
"errors"
"github.com/Ingenico-ePayments/connect-sdk-go"
"github.com/Ingenico-ePayments/connect-sdk-go/communicator"
"github.com/Ingenico-ePayments/connect-sdk-go/communicator/communication"
"github.com/Ingenico-ePayments/connect-sdk-go/domain/webhooks"
"github.com/Ingenico-ePayments/connect-sdk-go/webhooks/validation"
)
var (
// ErrNilMarshaller occurs when the provided marshaller is nil
ErrNilMarshaller = errors.New("nil marshaller")
// ErrNilSecretKeyStore occurs when the provided secretKeyStore is nil
// Deprecated: use validation.ErrNilSecretKeyStore instead
ErrNilSecretKeyStore = validation.ErrNilSecretKeyStore
)
// Helper is the Ingenico ePayments platform webhooks helper. Immutable and thread-safe.
type Helper struct {
marshaller communicator.Marshaller
signatureValidator *validation.SignatureValidator
}
// Unmarshal unmarshalls the given body and validates it using the requestHeaders
//
// Can return any of the following errors:
// SignatureValidationError if the body could not be validated successfully
// APIVersionMismatchError if the resulting event has an API version that this version of the SDK does not support
func (h *Helper) Unmarshal(body string, requestHeaders []communication.Header) (*webhooks.Event, error) {
err := h.signatureValidator.Validate(body, requestHeaders)
if err != nil {
if _, ok := err.(*validation.SignatureValidationError); ok {
// Return the right type but with the same error message
sve, _ := NewSignatureValidationError(err.Error())
return nil, sve
}
return nil, err
}
event, err := webhooks.NewEvent()
if err != nil {
return nil, err
}
err = h.marshaller.Unmarshal(body, event)
if err != nil {
return nil, err
}
err = validateAPIVersion(event)
if err != nil {
return nil, err
}
return event, nil
}
// NewHelper creates an Helper with the given marshaller and secretKeyStore
func NewHelper(marshaller communicator.Marshaller, secretKeyStore SecretKeyStore) (*Helper, error) {
if marshaller == nil {
return nil, ErrNilMarshaller
}
signatureValidator, err := validation.NewSignatureValidator(secretKeyStore)
if err != nil {
return nil, err
}
return &Helper{marshaller, signatureValidator}, nil
}
func validateAPIVersion(event *webhooks.Event) error {
if *event.APIVersion != connectsdk.APIVersion {
ame, err := NewAPIVersionMismatchError(*event.APIVersion, connectsdk.APIVersion)
if err != nil {
return err
}
return ame
}
return nil
}