This repository has been archived by the owner on Apr 9, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 18
/
stormpath.go
300 lines (249 loc) · 8.47 KB
/
stormpath.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
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
package stormpath
import (
"bytes"
"crypto/tls"
"encoding/json"
"errors"
"fmt"
"net/http"
"net/http/httputil"
"net/url"
"strings"
"sync"
"time"
"io/ioutil"
uuid "github.com/nu7hatch/gouuid"
)
//Version is the current SDK Version
const version = "0.1.0-beta.23"
const (
Enabled = "ENABLED"
Disabled = "DISABLED"
Unverified = "UNVERIFIED"
ApplicationJSON = "application/json"
ApplicationFormURLencoded = "application/x-www-form-urlencoded"
TextPlain = "text/plain"
TextHTML = "text/html"
ContentTypeHeader = "Content-Type"
AcceptHeader = "Accept"
UserAgentHeader = "User-Agent"
)
var client *Client
var buffPool = sync.Pool{
New: func() interface{} {
return &bytes.Buffer{}
},
}
//Client is low level REST client for any Stormpath request,
//it holds the credentials, an the actual http client, and the cache.
//The Cache can be initialize in nil and the client would simply ignore it
//and don't cache any response.
type Client struct {
ClientConfiguration ClientConfiguration
HTTPClient *http.Client
Cache Cache
WebSDKToken string
}
//Init initializes the underlying client that communicates with Stormpath
func Init(clientConfiguration ClientConfiguration, cache Cache) {
InitLog()
tr := &http.Transport{
TLSClientConfig: &tls.Config{},
DisableCompression: true,
}
httpClient := &http.Client{Transport: tr}
httpClient.CheckRedirect = checkRedirect
client = &Client{clientConfiguration, httpClient, nil, ""}
if clientConfiguration.CacheManagerEnabled && cache == nil {
client.Cache = NewLocalCache(clientConfiguration.CacheTTL, clientConfiguration.CacheTTI)
} else if clientConfiguration.CacheManagerEnabled && cache != nil {
client.Cache = cache
}
}
//GetClient returns the configured client
func GetClient() *Client {
return client
}
func (client *Client) postURLEncodedForm(urlStr string, body string, result interface{}) error {
return client.execute(http.MethodPost, urlStr, []byte(body), result, ApplicationFormURLencoded)
}
func (client *Client) post(urlStr string, body interface{}, result interface{}) error {
return client.execute(http.MethodPost, urlStr, body, result, ApplicationJSON)
}
func (client *Client) get(urlStr string, result interface{}) error {
return client.execute(http.MethodGet, urlStr, emptyPayload(), result, ApplicationJSON)
}
func (client *Client) delete(urlStr string) error {
return client.do(client.newRequest(http.MethodDelete, urlStr, emptyPayload(), ApplicationJSON))
}
func (client *Client) execute(method string, urlStr string, body interface{}, result interface{}, contentType string) error {
return client.doWithResult(client.newRequest(method, urlStr, body, contentType), result)
}
func buildRelativeURL(parts ...string) string {
p := append([]string{client.ClientConfiguration.BaseURL}, parts...)
return buildAbsoluteURL(p...)
}
func buildAbsoluteURL(parts ...string) string {
buffer := bytes.NewBufferString("")
for i, part := range parts {
buffer.WriteString(part)
if !strings.HasSuffix(part, "/") && i+1 < len(parts) {
buffer.WriteString("/")
}
}
return buffer.String()
}
func (client *Client) newRequest(method string, urlStr string, body interface{}, contentType string) *http.Request {
var encodedBody []byte
if contentType != ApplicationJSON || method == http.MethodGet || method == http.MethodDelete {
//If content type is not application/json then it is application/x-www-form-urlencoded in which case the body should the encoded params as a []byte
//Fixes issue #23 if the method is GET then body should also be just the bytes instead of doing a JSON marshaling
encodedBody = body.([]byte)
} else {
if _, ok := body.([]byte); !ok {
encodedBody, _ = json.Marshal(body)
}
}
req, _ := http.NewRequest(method, urlStr, bytes.NewReader(encodedBody))
req.Header.Set(UserAgentHeader, strings.TrimSpace(fmt.Sprintf("stormpath-sdk-go/%s %s", version, client.WebSDKToken)))
req.Header.Set(AcceptHeader, ApplicationJSON)
req.Header.Set(ContentTypeHeader, contentType)
uuid, _ := uuid.NewV4()
nonce := uuid.String()
Authenticate(req, encodedBody, time.Now().In(time.UTC), client.ClientConfiguration.APIKeyID, client.ClientConfiguration.APIKeySecret, nonce)
return req
}
//buildExpandParam coverts a slice of expand attributes to a url.Values with
//only one value "expand=attr1,attr2,etc"
func buildExpandParam(expandAttributes []string) url.Values {
stringBuffer := bytes.NewBufferString("")
first := true
for _, expandAttribute := range expandAttributes {
if !first {
stringBuffer.WriteString(",")
}
stringBuffer.WriteString(expandAttribute)
first = false
}
values := url.Values{}
expandValue := stringBuffer.String()
//Should not include the expand query param if the value is empty
if expandValue != "" {
values.Add("expand", expandValue)
}
return values
}
func requestParams(values ...url.Values) string {
buff := buffPool.Get().(*bytes.Buffer)
buff.Reset()
defer buffPool.Put(buff)
first := true
for _, v := range values {
encodedValues := v.Encode()
if buff.Len() > 0 && !first && encodedValues != "" {
buff.WriteByte('&')
}
buff.WriteString(encodedValues)
first = false
}
encodedParams := buff.String()
if encodedParams != "" {
return "?" + encodedParams
}
return ""
}
func emptyPayload() []byte {
return []byte{}
}
//doWithResult executes the given StormpathRequest and serialize the response body into the given expected result,
//it returns an error if any occurred while executing the request or serializing the response
func (client *Client) doWithResult(request *http.Request, result interface{}) error {
var jsonData []byte
var err error
key := request.URL.String()
if client.Cache != nil && request.Method == http.MethodGet && client.Cache.Exists(key) {
jsonData = client.Cache.Get(key)
}
if len(jsonData) == 0 {
response, err := client.execRequest(request)
if err != nil {
return err
}
jsonData, err = ioutil.ReadAll(response.Body)
if err != nil {
return err
}
}
if result != nil {
err = json.NewDecoder(bytes.NewBuffer(jsonData)).Decode(result)
}
if client.Cache != nil && err == nil && result != nil {
switch request.Method {
case http.MethodPost, http.MethodDelete:
client.Cache.Del(key)
break
case http.MethodGet:
c, ok := result.(Cacheable)
if ok &&
c.IsCacheable() &&
!strings.Contains(key, "passwordResetTokens") &&
!strings.Contains(key, "authTokens") {
client.Cache.Set(key, jsonData)
}
}
}
return err
}
//do executes the StormpathRequest without expecting a response body as a result,
//it returns an error if any occurred while executing the request
func (client *Client) do(request *http.Request) error {
_, err := client.execRequest(request)
return err
}
//execRequest executes a request, it would return a byte slice with the raw resoponse data and an error if any occurred
func (client *Client) execRequest(req *http.Request) (*http.Response, error) {
if logLevel == "DEBUG" {
//Print request
dump, _ := httputil.DumpRequest(req, true)
Logger.Printf("[DEBUG] Stormpath request\n%s", dump)
}
resp, err := client.HTTPClient.Do(req)
if logLevel == "DEBUG" {
//Print response
dump, _ := httputil.DumpResponse(resp, true)
Logger.Printf("[DEBUG] Stormpath response\n%s", dump)
}
return resp, handleResponseError(req, resp, err)
}
func checkRedirect(req *http.Request, via []*http.Request) error {
//Go client defautl behavior is to bail after 10 redirects
if len(via) > 10 {
return errors.New("stopped after 10 redirects")
}
//No redirect do nothing
if len(via) == 0 {
// No redirects
return nil
}
// Re-Authenticate the redirect request
uuid, _ := uuid.NewV4()
nonce := uuid.String()
//In Go 1.8 the authorization header remains in the redirect request causing auth errors
req.Header.Del(AuthorizationHeader)
//We can use an empty payload cause the only redirect is for the current tenant
//this could change in the future
Authenticate(req, emptyPayload(), time.Now().In(time.UTC), client.ClientConfiguration.APIKeyID, client.ClientConfiguration.APIKeySecret, nonce)
return nil
}
func cleanCustomData(customData map[string]interface{}) map[string]interface{} {
// delete illegal keys from data
// http://docs.stormpath.com/rest/product-guide/#custom-data
keys := []string{
"href", "createdAt", "modifiedAt", "meta",
"spMeta", "spmeta", "ionmeta", "ionMeta",
}
for i := range keys {
delete(customData, keys[i])
}
return customData
}