forked from bold-commerce/go-shopify
-
Notifications
You must be signed in to change notification settings - Fork 1
/
oauth.go
150 lines (123 loc) · 4.14 KB
/
oauth.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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
package goshopify
import (
"bytes"
"crypto/hmac"
"crypto/sha256"
"encoding/base64"
"encoding/hex"
"errors"
"fmt"
"io/ioutil"
"net/http"
"net/url"
)
const shopifyChecksumHeader = "X-Shopify-Hmac-Sha256"
var accessTokenRelPath = "admin/oauth/access_token"
// Returns a Shopify oauth authorization url for the given shopname and state.
//
// State is a unique value that can be used to check the authenticity during a
// callback from Shopify.
func (app App) AuthorizeUrl(shopName string, state string) string {
shopUrl, _ := url.Parse(ShopBaseUrl(shopName))
shopUrl.Path = "/admin/oauth/authorize"
query := shopUrl.Query()
query.Set("client_id", app.ApiKey)
query.Set("redirect_uri", app.RedirectUrl)
query.Set("scope", app.Scope)
query.Set("state", state)
shopUrl.RawQuery = query.Encode()
return shopUrl.String()
}
func (app App) GetAccessToken(shopName string, code string) (string, error) {
type Token struct {
Token string `json:"access_token"`
}
data := struct {
ClientId string `json:"client_id"`
ClientSecret string `json:"client_secret"`
Code string `json:"code"`
}{
ClientId: app.ApiKey,
ClientSecret: app.ApiSecret,
Code: code,
}
client := app.Client
if client == nil {
client = NewClient(app, shopName, "")
}
req, err := client.NewRequest("POST", accessTokenRelPath, data, nil)
if err != nil {
return "", err
}
token := new(Token)
err = client.Do(req, token)
return token.Token, err
}
// Verify a message against a message HMAC
func (app App) VerifyMessage(message, messageMAC string) bool {
mac := hmac.New(sha256.New, []byte(app.ApiSecret))
mac.Write([]byte(message))
expectedMAC := mac.Sum(nil)
// shopify HMAC is in hex so it needs to be decoded
actualMac, _ := hex.DecodeString(messageMAC)
return hmac.Equal(actualMac, expectedMAC)
}
// Verifying URL callback parameters.
func (app App) VerifyAuthorizationURL(u *url.URL) (bool, error) {
q := u.Query()
messageMAC := q.Get("hmac")
// Remove hmac and signature and leave the rest of the parameters alone.
q.Del("hmac")
q.Del("signature")
message, err := url.QueryUnescape(q.Encode())
return app.VerifyMessage(message, messageMAC), err
}
// Verifies a webhook http request, sent by Shopify.
// The body of the request is still readable after invoking the method.
func (app App) VerifyWebhookRequest(httpRequest *http.Request) bool {
shopifySha256 := httpRequest.Header.Get(shopifyChecksumHeader)
actualMac := []byte(shopifySha256)
mac := hmac.New(sha256.New, []byte(app.ApiSecret))
requestBody, _ := ioutil.ReadAll(httpRequest.Body)
httpRequest.Body = ioutil.NopCloser(bytes.NewBuffer(requestBody))
mac.Write(requestBody)
macSum := mac.Sum(nil)
expectedMac := []byte(base64.StdEncoding.EncodeToString(macSum))
return hmac.Equal(actualMac, expectedMac)
}
// Verifies a webhook http request, sent by Shopify.
// The body of the request is still readable after invoking the method.
// This method has more verbose error output which is useful for debugging.
func (app App) VerifyWebhookRequestVerbose(httpRequest *http.Request) (bool, error) {
if app.ApiSecret == "" {
return false, errors.New("ApiSecret is empty")
}
shopifySha256 := httpRequest.Header.Get(shopifyChecksumHeader)
if shopifySha256 == "" {
return false, fmt.Errorf("header %s not set", shopifyChecksumHeader)
}
decodedReceivedHMAC, err := base64.StdEncoding.DecodeString(shopifySha256)
if err != nil {
return false, err
}
if len(decodedReceivedHMAC) != 32 {
return false, fmt.Errorf("received HMAC is not of length 32, it is of length %d", len(decodedReceivedHMAC))
}
mac := hmac.New(sha256.New, []byte(app.ApiSecret))
requestBody, err := ioutil.ReadAll(httpRequest.Body)
if err != nil {
return false, err
}
httpRequest.Body = ioutil.NopCloser(bytes.NewBuffer(requestBody))
if len(requestBody) == 0 {
return false, errors.New("request body is empty")
}
// Sha256 write doesn't actually return an error
mac.Write(requestBody)
computedHMAC := mac.Sum(nil)
HMACSame := hmac.Equal(decodedReceivedHMAC, computedHMAC)
if !HMACSame {
return HMACSame, fmt.Errorf("expected hash %x does not equal %x", computedHMAC, decodedReceivedHMAC)
}
return HMACSame, nil
}