forked from jarias/stormpath-sdk-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
stormpath.go
251 lines (205 loc) · 6.57 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
package stormpath
import (
"bytes"
"crypto/tls"
"encoding/json"
"errors"
"fmt"
"net/http"
"net/http/httputil"
"net/url"
"runtime"
"time"
uuid "github.com/nu7hatch/gouuid"
)
//BaseURL defines the Stormpath API base URL
var BaseURL = "https://api.stormpath.com/v1/"
//Version is the current SDK Version
const version = "0.1.0-beta.11"
var client *Client
//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 {
Credentials Credentials
HTTPClient *http.Client
Cache Cache
}
//Init initializes the underlying client that communicates with Stormpath
func Init(credentials Credentials, cache Cache) {
tr := &http.Transport{
TLSClientConfig: &tls.Config{},
DisableCompression: true,
}
httpClient := &http.Client{Transport: tr}
httpClient.CheckRedirect = checkRedirect
client = &Client{credentials, httpClient, cache}
initLog()
}
//InitWithCustomHTTPClient initializes the underlying client that communicates with Stormpath with a custom http.Client
func InitWithCustomHTTPClient(credentials Credentials, cache Cache, httpClient *http.Client) {
httpClient.CheckRedirect = checkRedirect
client = &Client{credentials, httpClient, cache}
initLog()
}
func (client *Client) post(urlStr string, body interface{}, result interface{}) error {
return client.execute("POST", urlStr, body, result)
}
func (client *Client) get(urlStr string, body interface{}, result interface{}) error {
return client.execute("GET", urlStr, body, result)
}
func (client *Client) delete(urlStr string, body interface{}) error {
return client.do(client.newRequest("DELETE", urlStr, body))
}
func (client *Client) execute(method string, urlStr string, body interface{}, result interface{}) error {
return client.doWithResult(client.newRequest(method, urlStr, body), result)
}
func buildRelativeURL(parts ...string) string {
buffer := bytes.NewBufferString(BaseURL)
for i, part := range parts {
buffer.WriteString(part)
if i+1 < len(parts) {
buffer.WriteString("/")
}
}
return buffer.String()
}
func buildAbsoluteURL(parts ...string) string {
buffer := bytes.NewBufferString("")
for i, part := range parts {
buffer.WriteString(part)
if i+1 < len(parts) {
buffer.WriteString("/")
}
}
return buffer.String()
}
func (client *Client) newRequest(method string, urlStr string, body interface{}) *http.Request {
jsonBody, _ := json.Marshal(body)
req, _ := http.NewRequest(method, urlStr, bytes.NewReader(jsonBody))
req.Header.Set("User-Agent", fmt.Sprintf("jarias/stormpath-sdk-go/%s (%s; %s)", version, runtime.GOOS, runtime.GOARCH))
req.Header.Set("Accept", "application/json")
req.Header.Set("Content-Type", "application/json")
uuid, _ := uuid.NewV4()
nonce := uuid.String()
Authenticate(req, jsonBody, time.Now().In(time.UTC), client.Credentials, 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 {
params := url.Values{}
for _, v := range values {
params = appendParams(params, v)
}
encodedParams := params.Encode()
if encodedParams != "" {
return "?" + encodedParams
}
return ""
}
func appendParams(params url.Values, toAppend url.Values) url.Values {
for k, v := range toAppend {
params[k] = v
}
return params
}
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 err error
var response *http.Response
key := request.URL.String()
if client.Cache != nil && request.Method == "GET" && client.Cache.Exists(key) {
err = client.Cache.Get(key, result)
} else {
response, err = client.execRequest(request)
if err != nil {
return err
}
err = json.NewDecoder(response.Body).Decode(result)
}
if client.Cache != nil && err == nil {
switch request.Method {
case "POST", "DELETE", "PUT":
client.Cache.Del(key)
break
case "GET":
cacheResource(key, result, client.Cache)
}
}
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(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()
//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.Credentials, 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
}