-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.go
177 lines (144 loc) · 4.4 KB
/
client.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
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
package auth0
import (
"bytes"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"time"
"github.com/pkg/errors"
)
// Client runs Auth0 Management API methods whilst maintaining a fresh token
type Client struct {
ClientID string
ClientSecret string
Audience string
Domain string
token *Token
valid bool
Debug bool
}
// NewClient returns a Client usable for executing authenticated Auth0 Management API methods
func NewClient(clientID, clientSecret, audience, domain string) (*Client, error) {
token, err := GetToken(clientID, clientSecret, audience, domain)
if err != nil {
return nil, errors.Wrap(err, "Error intializing new Auth0 client")
}
c := &Client{
ClientID: clientID,
ClientSecret: clientSecret,
Audience: audience,
Domain: domain,
token: token,
valid: true,
}
c.startTokenRefresher()
return c, nil
}
// startTokenRefresher uses the reported token expiry time to automatically refresh the
// token 5 seconds before it expires.
//
// If the GetToken calls produces an error, we set the Client valid flag to false so the
// next call can try to refresh the token or error. That's about all we do for retry logic
// at this time ¯\_(ツ)_/¯
func (c *Client) startTokenRefresher() {
refresher := time.NewTicker(time.Second * time.Duration(c.token.ExpiresIn-5))
go func() {
for _ = range refresher.C {
token, err := GetToken(c.ClientID, c.ClientSecret, c.Audience, c.Domain)
if err != nil {
fmt.Printf("Error refreshing Auth0 token: %s", err.Error())
// set the client status to valid such that the next time someone
// tries to use it, they will get an error.
c.valid = false
return
}
c.token = token
}
}()
}
// POST sends a POST request to the specified Auth0 Management API using the client token.
//
// The `input` and `output` interfaces are JSON marshalled/unmarshalled.
func (c *Client) POST(endpoint string, input interface{}, output interface{}) error {
b, err := c.request("POST", endpoint, nil, input)
if err != nil {
return err
}
return json.Unmarshal(b, &output)
}
// GET sends a GET request to the specified Auth0 Management API using the client token.
//
// The `params` map will be added to the query string and the `output` interface is JSON umarshalled.
func (c *Client) GET(endpoint string, params map[string]string, output interface{}) error {
b, err := c.request("GET", endpoint, params, nil)
if err != nil {
return err
}
return json.Unmarshal(b, &output)
}
// the low-level request function sets the headers properly
func (c *Client) request(method, endpoint string, params map[string]string, body interface{}) ([]byte, error) {
// Ensure we have a valid client
if !c.valid {
return nil, errors.New("Auth0 client is not valid, try creating a new one with NewClient method")
}
// Construct the URL
url := fmt.Sprintf("%s%s", c.Audience, endpoint)
if c.Debug {
fmt.Printf("ENDPOINT: %s\n", url)
}
// Marshal the payload (if we have one)
var payloadReader io.Reader
if body != nil {
b, err := json.Marshal(body)
if err != nil {
return nil, errors.Wrap(err, "Error marshalling request payload")
}
if c.Debug {
fmt.Printf("REQUEST: %s\n", string(b))
}
payloadReader = bytes.NewReader(b)
}
// Build the request
req, err := http.NewRequest(method, url, payloadReader)
if err != nil {
return nil, errors.Wrap(err, "Error building request")
}
// Add the authorization header and content header
req.Header.Add("Content-Type", "application/json")
req.Header.Add("Authorization", "Bearer "+c.token.AccessToken)
// Add query params if there are any
if len(params) > 0 {
q := req.URL.Query()
for k, v := range params {
q.Add(k, v)
}
req.URL.RawQuery = q.Encode()
}
res, err := http.DefaultClient.Do(req)
if err != nil {
return nil, errors.Wrap(err, "Error executing request")
}
defer res.Body.Close()
resBody, err := ioutil.ReadAll(res.Body)
if err != nil {
return nil, errors.Wrap(err, "Error reading response body")
}
if c.Debug {
fmt.Printf("RESPONSE: %s\n", string(resBody))
}
if !(res.StatusCode >= 200 && res.StatusCode < 300) {
var e struct {
StatusCode int
Error string
Message string
ErrorCode string
}
json.Unmarshal(resBody, &e)
err = fmt.Errorf("%v %s: %s; %s", e.StatusCode, e.Error, e.ErrorCode, e.Message)
return nil, errors.Wrap(err, "Auth0 response contains error")
}
return resBody, nil
}