forked from TimmyGuy/bigcommerce-api-go
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathauth_context.go
57 lines (50 loc) · 1.26 KB
/
auth_context.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
package bigcommerce
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"net/url"
"strings"
)
// GetAuthContext returns an AuthContext object from the BigCommerce API
// Call it with r.URL.Query() - will return BigCommerce Auth Context or error
func (bc *App) GetAuthContext(requestURLQuery url.Values) (*AuthContext, error) {
req := AuthTokenRequest{
ClientID: bc.AppClientID,
ClientSecret: bc.AppClientSecret,
RedirectURI: "https://" + bc.Hostname + "/auth",
GrantType: "authorization_code",
Code: requestURLQuery.Get("code"),
Scope: requestURLQuery.Get("scope"),
Context: requestURLQuery.Get("context"),
}
reqb, err := json.Marshal(req)
if err != nil {
return nil, err
}
res, err := bc.HTTPClient.Post("https://login.bigcommerce.com/oauth2/token",
"application/json",
bytes.NewReader(reqb),
)
if err != nil {
return nil, err
}
bytes, err := ioutil.ReadAll(res.Body)
if err != nil {
return nil, err
}
res.Body.Close()
if strings.Contains(string(bytes), "invalid_") {
return nil, fmt.Errorf("%s", string(bytes))
}
var ac AuthContext
err = json.Unmarshal(bytes, &ac)
if err != nil {
return nil, err
}
if ac.Error != "" {
return nil, fmt.Errorf("AuthContext error: %s", ac.Error)
}
return &ac, nil
}