/
client.go
74 lines (61 loc) · 1.74 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
package dashboard
import (
"errors"
"fmt"
"strings"
"github.com/TykTechnologies/tyk-sync/clients/objects"
"github.com/levigross/grequests"
"github.com/ongoingio/urljoin"
)
type Client struct {
url string
secret string
isCloud bool
InsecureSkipVerify bool
OrgID string
allowUnsafeOAS bool
}
const (
endpointAPIs string = "/api/apis"
endpointOASAPIs string = "/api/apis/oas"
endpointPolicies string = "/api/portal/policies"
endpointCerts string = "/api/certs"
endpointUsers string = "/api/users"
)
var (
UseUpdateError error = errors.New("Object seems to exist (same ID, API ID, Listen Path or Slug), use update()")
UsePolUpdateError error = errors.New("Object seems to exist (same ID, Explicit ID), use update()")
UseCreateError error = errors.New("Object does not exist, use create()")
)
func NewDashboardClient(url, secret, orgID string, allowUnsafeOAS bool) (*Client, error) {
client := &Client{
url: url,
secret: secret,
isCloud: strings.Contains(url, "tyk.io"),
allowUnsafeOAS: allowUnsafeOAS,
}
if orgID == "" {
fullPath := urljoin.Join(url, endpointUsers)
ro := &grequests.RequestOptions{
Params: map[string]string{"p": "-2"},
Headers: map[string]string{
"Authorization": secret,
},
}
resp, err := grequests.Get(fullPath, ro)
if err != nil {
return client, err
}
if resp.StatusCode != 200 {
return client, fmt.Errorf("Error getting users from dashboard: %v for %v", resp.String(), fullPath)
}
users := objects.UsersResponse{}
if err := resp.JSON(&users); err != nil {
return client, err
}
if len(users.Users) > 0 {
client.OrgID = users.Users[0].OrgID
}
}
return client, nil
}