-
Notifications
You must be signed in to change notification settings - Fork 1
/
client.go
227 lines (202 loc) · 6.87 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
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
package zcc
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"html"
"io"
"net/http"
"net/url"
"time"
"github.com/google/go-querystring/query"
"github.com/google/uuid"
"github.com/zscaler/zscaler-sdk-go/v2/logger"
"github.com/zscaler/zscaler-sdk-go/v2/utils"
)
type Client struct {
Config *Config
}
// NewClient returns a new client for the specified apiKey.
func NewClient(config *Config) (c *Client) {
if config == nil {
config, _ = NewConfig("", "", "", "")
}
c = &Client{Config: config}
return
}
func (client *Client) NewRequestDo(method, url string, options, body, v interface{}) (*http.Response, error) {
return client.newRequestDoCustom(method, url, options, body, v)
}
func (client *Client) authenticate() error {
client.Config.Lock()
defer client.Config.Unlock()
if client.Config.AuthToken == nil || client.Config.AuthToken.AccessToken == "" || utils.IsTokenExpired(client.Config.AuthToken.AccessToken) {
if client.Config.ClientID == "" || client.Config.ClientSecret == "" {
client.Config.Logger.Printf("[ERROR] No client credentials were provided. Please set %s and %s environment variables.\n", ZCC_CLIENT_ID, ZCC_CLIENT_SECRET)
return errors.New("no client credentials were provided")
}
client.Config.Logger.Printf("[TRACE] Getting access token for %s=%s\n", ZCC_CLIENT_ID, client.Config.ClientID)
authReq := AuthRequest{}
authReq.APIKey = client.Config.ClientID
authReq.SecretKey = client.Config.ClientSecret
data, err := json.Marshal(authReq)
if err != nil {
client.Config.Logger.Printf("[ERROR] Failed to signin the user %s=%s, err: %v\n", ZCC_CLIENT_ID, client.Config.ClientID, err)
return fmt.Errorf("[ERROR] Failed to signin the user %s=%s, err: %v", ZCC_CLIENT_ID, client.Config.ClientID, err)
}
req, err := http.NewRequest("POST", client.Config.BaseURL.String()+"/auth/v1/login", bytes.NewBuffer(data))
if err != nil {
client.Config.Logger.Printf("[ERROR] Failed to signin the user %s=%s, err: %v\n", ZCC_CLIENT_ID, client.Config.ClientID, err)
return fmt.Errorf("[ERROR] Failed to signin the user %s=%s, err: %v", ZCC_CLIENT_ID, client.Config.ClientID, err)
}
req.Header.Add("Content-Type", "application/json")
if client.Config.UserAgent != "" {
req.Header.Add("User-Agent", client.Config.UserAgent)
}
resp, err := client.Config.GetHTTPClient().Do(req)
if err != nil {
client.Config.Logger.Printf("[ERROR] Failed to signin the user %s=%s, err: %v\n", ZCC_CLIENT_ID, client.Config.ClientID, err)
return fmt.Errorf("[ERROR] Failed to signin the user %s=%s, err: %v", ZCC_CLIENT_ID, client.Config.ClientID, err)
}
defer resp.Body.Close()
respBody, err := io.ReadAll(resp.Body)
if err != nil {
client.Config.Logger.Printf("[ERROR] Failed to signin the user %s=%s, err: %v\n", ZCC_CLIENT_ID, client.Config.ClientID, err)
return fmt.Errorf("[ERROR] Failed to signin the user %s=%s, err: %v", ZCC_CLIENT_ID, client.Config.ClientID, err)
}
if resp.StatusCode >= 300 {
client.Config.Logger.Printf("[ERROR] Failed to signin the user %s=%s, got http status:%dn response body:%s\n", ZCC_CLIENT_ID, client.Config.ClientID, resp.StatusCode, respBody)
return fmt.Errorf("[ERROR] Failed to signin the user %s=%s, got http status:%d, response body:%s", ZCC_CLIENT_ID, client.Config.ClientID, resp.StatusCode, respBody)
}
var a AuthToken
err = json.Unmarshal(respBody, &a)
if err != nil {
client.Config.Logger.Printf("[ERROR] Failed to signin the user %s=%s, err: %v\n", ZCC_CLIENT_ID, client.Config.ClientID, err)
return fmt.Errorf("[ERROR] Failed to signin the user %s=%s, err: %v", ZCC_CLIENT_ID, client.Config.ClientID, err)
}
// we need keep auth token for future http request
client.Config.AuthToken = &a
}
return nil
}
func (client *Client) newRequestDoCustom(method, urlStr string, options, body, v interface{}) (*http.Response, error) {
err := client.authenticate()
if err != nil {
return nil, err
}
req, err := client.newRequest(method, urlStr, options, body)
if err != nil {
return nil, err
}
start := time.Now()
reqID := uuid.NewString()
logger.LogRequest(client.Config.Logger, req, reqID, nil, true)
resp, err := client.do(req, v, start, reqID)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode == http.StatusUnauthorized || resp.StatusCode == http.StatusForbidden {
err := client.authenticate()
if err != nil {
return nil, err
}
resp, err := client.do(req, v, start, reqID)
if err != nil {
return nil, err
}
resp.Body.Close()
return resp, nil
}
return resp, err
}
// Generating the Http request.
func (client *Client) newRequest(method, urlPath string, options, body interface{}) (*http.Request, error) {
if client.Config.AuthToken == nil || client.Config.AuthToken.AccessToken == "" {
client.Config.Logger.Printf("[ERROR] Failed to signin the user %s=%s\n", ZCC_CLIENT_ID, client.Config.ClientID)
return nil, fmt.Errorf("failed to signin the user %s=%s", ZCC_CLIENT_ID, client.Config.ClientID)
}
var buf io.ReadWriter
if body != nil {
buf = new(bytes.Buffer)
err := json.NewEncoder(buf).Encode(body)
if err != nil {
return nil, err
}
}
// Join the path to the base-url
u := *client.Config.BaseURL
unescaped, err := url.PathUnescape(urlPath)
if err != nil {
return nil, err
}
// Set the encoded path data
u.RawPath = u.Path + urlPath
u.Path += unescaped
// Set the query parameters
if options != nil {
q, err := query.Values(options)
if err != nil {
return nil, err
}
u.RawQuery = q.Encode()
}
req, err := http.NewRequest(method, u.String(), buf)
if err != nil {
return nil, err
}
req.Header.Set("auth-token", client.Config.AuthToken.AccessToken)
req.Header.Add("Content-Type", "application/json")
if client.Config.UserAgent != "" {
req.Header.Add("User-Agent", client.Config.UserAgent)
}
return req, nil
}
func (client *Client) do(req *http.Request, v interface{}, start time.Time, reqID string) (*http.Response, error) {
resp, err := client.Config.GetHTTPClient().Do(req)
if err != nil {
return nil, err
}
if err := checkErrorInResponse(resp); err != nil {
return resp, err
}
if v != nil {
if err := decodeJSON(resp, v); err != nil {
return resp, err
}
}
logger.LogResponse(client.Config.Logger, resp, start, reqID)
unescapeHTML(v)
return resp, nil
}
func decodeJSON(res *http.Response, v interface{}) error {
return json.NewDecoder(res.Body).Decode(&v)
}
func unescapeHTML(entity interface{}) {
if entity == nil {
return
}
data, err := json.Marshal(entity)
if err != nil {
return
}
var mapData map[string]interface{}
err = json.Unmarshal(data, &mapData)
if err != nil {
return
}
for _, field := range []string{"name", "description"} {
if v, ok := mapData[field]; ok && v != nil {
str, ok := v.(string)
if ok {
mapData[field] = html.UnescapeString(html.UnescapeString(str))
}
}
}
data, err = json.Marshal(mapData)
if err != nil {
return
}
_ = json.Unmarshal(data, entity)
}