-
Notifications
You must be signed in to change notification settings - Fork 11
/
jcapi.go
432 lines (340 loc) · 9.12 KB
/
jcapi.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
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
package jcapi
import (
"bytes"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"reflect"
"regexp"
"strings"
"time"
)
const (
responseSize = 256 * 1024
StdUrlBase = "https://console.jumpcloud.com/api"
)
type JCOp uint8
const (
Read JCOp = 1
Insert JCOp = 2
Update JCOp = 3
Delete JCOp = 4
List JCOp = 5
)
type JCAPI struct {
ApiKey string
UrlBase string
}
const (
searchLimit int = 100
searchSkipInterval int = 100
)
const (
BAD_FIELD_NAME = -3
OBJECT_NOT_FOUND = -2
BAD_COMPARISON_TYPE = -1
)
type JCError interface {
Error() string
}
type errorString struct {
s string
}
func (e *errorString) Error() string {
return e.s
}
func NewJCAPI(apiKey string, urlBase string) JCAPI {
return JCAPI{
ApiKey: apiKey,
UrlBase: urlBase,
}
}
func buildJSONStringArray(field string, s []string) string {
returnVal := "["
if s != nil {
afterFirst := false
for _, val := range s {
if afterFirst {
returnVal += ","
}
returnVal += "\"" + val + "\""
afterFirst = true
}
}
returnVal += "]"
return "\"" + field + "\":" + returnVal
}
func buildJSONKeyValuePair(key, value string) string {
return "\"" + key + "\":\"" + value + "\""
}
func buildJSONKeyValueBoolPair(key string, value bool) string {
if value == true {
return "\"" + key + "\":\"true\""
} else {
return "\"" + key + "\":\"false\""
}
}
func getTimeString() string {
t := time.Now()
return t.Format(time.RFC3339)
}
func (jc JCAPI) emailFilter(email string) []byte {
//
// Ideally, this would be generalized to take a map[string]string,
// that doesn't elicit the correct JSON output for the JumpCloud
// filters in json.Marshal()
//
return []byte(fmt.Sprintf("{\"filter\": [{\"email\" : \"%s\"}]}", email))
}
//being lazy; copy paste
func (jc JCAPI) hostnameFilter(hostname string) []byte {
//
// Ideally, this would be generalized to take a map[string]string,
// that doesn't elicit the correct JSON output for the JumpCloud
// filters in json.Marshal()
//
return []byte(fmt.Sprintf("{\"filter\": [{\"hostname\" : \"%s\"}]}", hostname))
}
func (jc JCAPI) setHeader(req *http.Request) {
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Accept", "application/json")
req.Header.Set("x-api-key", jc.ApiKey)
}
func (jc JCAPI) Post(url string, data []byte) (interface{}, JCError) {
return jc.Do(MapJCOpToHTTP(Insert), url, data)
}
func (jc JCAPI) Put(url string, data []byte) (interface{}, JCError) {
return jc.Do(MapJCOpToHTTP(Update), url, data)
}
func (jc JCAPI) Delete(url string) (interface{}, JCError) {
return jc.Do(MapJCOpToHTTP(Delete), url, nil)
}
func (jc JCAPI) Get(url string) (interface{}, JCError) {
return jc.Do(MapJCOpToHTTP(Read), url, nil)
}
func (jc JCAPI) List(url string) (interface{}, JCError) {
return jc.Do(MapJCOpToHTTP(List), url, nil)
}
//
// DEPRECATED: This version of Do() will be replaced by the code in DoBytes()
// in the future, when the jcapi-systemuser issue is corrected to allow for marshalling
// and unmarshalling using the same object.
//
func (jc JCAPI) Do(op, url string, data []byte) (interface{}, JCError) {
var returnVal interface{}
fullUrl := jc.UrlBase + url
client := &http.Client{}
// if there is no data, we should send a nil body, not an empty one:
var body io.Reader
if len(data) > 0 {
body = bytes.NewReader(data)
}
req, err := http.NewRequest(op, fullUrl, body)
if err != nil {
return returnVal, fmt.Errorf("ERROR: Could not build search request: '%s'", err)
}
jc.setHeader(req)
resp, err := client.Do(req)
if err != nil {
return returnVal, fmt.Errorf("ERROR: client.Do() failed, err='%s'", err)
}
defer resp.Body.Close()
if resp.Status != "200 OK" {
return returnVal, fmt.Errorf("JumpCloud HTTP response status='%s'", resp.Status)
}
buffer, err := ioutil.ReadAll(resp.Body)
if err != nil {
return returnVal, fmt.Errorf("ERROR: Could not read the response body, err='%s'", err)
}
err = json.Unmarshal(buffer, &returnVal)
if err != nil {
return returnVal, fmt.Errorf("ERROR: Could not Unmarshal JSON response, err='%s'", err)
}
return returnVal, err
}
func (jc JCAPI) DoBytes(op, urlQuery string, data []byte) ([]byte, JCError) {
fullUrl := jc.UrlBase + urlQuery
client := &http.Client{}
// if there is no data, we should send a nil body, not an empty one:
var body io.Reader
if len(data) > 0 {
body = bytes.NewReader(data)
}
req, err := http.NewRequest(op, fullUrl, body)
if err != nil {
return nil, fmt.Errorf("ERROR: Could not build search request: '%s'", err)
}
jc.setHeader(req)
resp, err := client.Do(req)
if err != nil {
return nil, fmt.Errorf("ERROR: client.Do() failed, err='%s'", err)
}
defer resp.Body.Close()
if resp.Status != "200 OK" {
return nil, fmt.Errorf("JumpCloud HTTP response status='%s'", resp.Status)
}
buffer, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, fmt.Errorf("ERROR: Could not read the response body, err='%s'", err)
}
return buffer, err
}
// Add all the tags of which the user is a part to the JCUser object
func (user *JCUser) AddJCTags(tags []JCTag) {
for _, tag := range tags {
for _, systemUser := range tag.SystemUsers {
if systemUser == user.Id {
user.Tags = append(user.Tags, tag)
}
}
}
}
// Add all the tags of which the system is a part to the JCSystem object
func (system *JCSystem) AddJCTagsToSystem(tags []JCTag) {
for _, tag := range tags {
for _, sys := range tag.Systems {
if sys == system.Id {
system.Tags = append(system.Tags, tag)
}
}
}
}
func MapJCOpToHTTP(op JCOp) string {
var returnVal string
switch op {
case Read:
returnVal = "GET"
case Insert:
returnVal = "POST"
case Update:
returnVal = "PUT"
case Delete:
returnVal = "DELETE"
case List:
returnVal = "LIST"
}
return returnVal
}
//
// Interface Conversion Helper Functions
//
func extractStringArray(input []interface{}) []string {
var returnVal []string
for _, str := range input {
returnVal = append(returnVal, str.(string))
}
return returnVal
}
func getStringOrNil(input interface{}) (s string) {
switch input.(type) {
case string:
s = input.(string)
}
return
}
func getUint16OrNil(input interface{}) (i uint16) {
switch input.(type) {
case uint16:
i = input.(uint16)
}
return
}
func getIntOrNil(input interface{}) (i int) {
switch input.(type) {
case int:
i = input.(int)
}
return
}
func GetTrueOrFalse(input interface{}) bool {
returnVal := false
switch input.(type) {
case string:
temp := strings.ToLower(input.(string))
returnVal = strings.Contains("true", temp) || strings.Contains("yes", temp) || strings.Contains("1", temp)
break
case int:
returnVal = input.(int) != 0
break
case bool:
returnVal = input.(bool)
break
}
return returnVal
}
func FindObject(sourceArray []interface{}, fieldName string, compareData interface{}) (index int) {
if len(sourceArray) == 0 {
return OBJECT_NOT_FOUND
}
//
// Get the specified field name of the first struct
//
s := reflect.ValueOf(sourceArray[0]).FieldByName(fieldName)
// Make sure the requested field name exists in the struct
if s.Kind() == reflect.Invalid {
return BAD_FIELD_NAME
}
// Make sure the compareData type matches that the field specified by fieldName
if s.Type() != reflect.TypeOf(compareData) {
return BAD_COMPARISON_TYPE
}
//
// Walk the array and see if we can find a matching object
//
for fieldIndex, _ := range sourceArray {
s = reflect.ValueOf(sourceArray[fieldIndex]).FieldByName(fieldName)
if reflect.DeepEqual(s.Interface(), compareData) {
return fieldIndex
}
}
return OBJECT_NOT_FOUND
}
func FindObjectByStringRegex(sourceArray []interface{}, fieldName string, regex string) (index int, err error) {
if len(sourceArray) == 0 {
err = fmt.Errorf("Source array is empty. object not found")
return
}
//
// Get the specified field name of the first struct
//
s := reflect.ValueOf(sourceArray[0]).FieldByName(fieldName)
// Make sure the requested field name exists in the struct
if s.Kind() == reflect.Invalid {
err = fmt.Errorf("Field name specified does not exist within the provided array of structs")
return
}
// Make sure the compareData type matches that the field specified by fieldName
if s.Type().Kind() != reflect.String {
err = fmt.Errorf("Type of field name '%s' must be string", fieldName)
return
}
r, err := regexp.Compile(regex)
if err != nil {
err = fmt.Errorf("Could not compile regex for '%s', err='%s'", regex, err.Error())
return
}
//
// Walk the array and see if we can find a matching object
//
for fieldIndex, _ := range sourceArray {
s = reflect.ValueOf(sourceArray[fieldIndex]).FieldByName(fieldName)
// Make sure the requested field name exists in the struct
if s.Kind() == reflect.Invalid {
err = fmt.Errorf("Field name specified does not exist within the object at array index %d", fieldIndex)
return
}
// Make sure the compareData type matches that the field specified by fieldName
if s.Type().Kind() != reflect.String {
err = fmt.Errorf("Type of field name '%s' in object at array index %d must be string", fieldName, fieldIndex)
return
}
if r.Match([]byte(s.String())) {
index = fieldIndex
return
}
}
index = OBJECT_NOT_FOUND
return
}