forked from ewarehousing-solutions/bigcommerce-api-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient_request.go
50 lines (47 loc) · 1.36 KB
/
client_request.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
package bigcommerce
import (
"crypto/hmac"
"crypto/sha256"
"encoding/base64"
"encoding/hex"
"encoding/json"
"fmt"
"net/url"
"strings"
)
// GetClientRequest returns a ClientRequest object from the BigCommerce API
// Call it with r.URL.Query() - will return BigCommerce Client Request or error
func (bc *App) GetClientRequest(requestURLQuery url.Values) (*ClientRequest, error) {
s := requestURLQuery.Get("signed_payload")
decoded, err := bc.CheckSignature(s)
if err != nil {
return nil, err
}
var clrq ClientRequest
err = json.Unmarshal(decoded, &clrq)
if err != nil {
return nil, err
}
return &clrq, nil
}
// CheckSignature checks the signature of the request whith SHA256 HMAC
func (bc *App) CheckSignature(signedPayload string) ([]byte, error) {
ss := strings.Split(signedPayload, ".")
if signedPayload == "" {
return nil, fmt.Errorf("no signed payload")
}
decoded, err := base64.StdEncoding.DecodeString(ss[0])
if err != nil {
return nil, fmt.Errorf("can't decode signed payload %v", err)
}
decodedSig, err := base64.StdEncoding.DecodeString(ss[1])
if err != nil {
return nil, fmt.Errorf("can't decode signature %v", err)
}
hms := hmac.New(sha256.New, []byte(bc.AppClientSecret))
hms.Write(decoded)
if !hmac.Equal([]byte(hex.EncodeToString(hms.Sum(nil))), decodedSig) {
return nil, fmt.Errorf("signature mismatch")
}
return decoded, nil
}