-
Notifications
You must be signed in to change notification settings - Fork 4
/
onelogin.go
295 lines (243 loc) · 6.99 KB
/
onelogin.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
package onelogin
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/url"
"reflect"
"sync"
"github.com/google/go-querystring/query"
)
const (
baseURL = "https://api.%s.onelogin.com/"
)
type service struct {
client *Client
}
// A Client interacts with OneLogin.
type Client struct {
client *http.Client
BaseURL *url.URL
clientID string
clientSecret string
subdomain string
// User agent used when communicating with the OneLogin api.
UserAgent string
common service // Reuse a single struct instead of allocating one for each service on the heap.
oauthToken *oauthToken
Oauth *OauthService
User *UserService
Role *RoleService
Group *GroupService
// SAMLService *SAMLService
// EventService *EventService
sync.Mutex
}
// New returns a new OneLogin client.
func New(clientID, clientSecret, shard, subdomain string) *Client {
c := &Client{
client: http.DefaultClient,
clientID: clientID,
clientSecret: clientSecret,
subdomain: subdomain,
}
c.common.client = c
c.BaseURL, _ = url.Parse(buildURL(baseURL, shard))
c.Oauth = (*OauthService)(&c.common)
c.User = (*UserService)(&c.common)
c.Role = (*RoleService)(&c.common)
c.Group = (*GroupService)(&c.common)
return c
}
type urlQuery struct {
AfterCursor string `url:"after_cursor,omitempty"`
}
// addOptions adds the parameters in opt as URL query parameters to s. opt
// must be a struct whose fields may contain "url" tags.
func addOptions(s string, opt interface{}) (string, error) {
v := reflect.ValueOf(opt)
if v.Kind() == reflect.Ptr && v.IsNil() {
return s, nil
}
u, err := url.Parse(s)
if err != nil {
return s, err
}
qs, err := query.Values(opt)
if err != nil {
return s, err
}
u.RawQuery = qs.Encode()
return u.String(), nil
}
// AddAuthorization injects the Authorization header to the request.
// If the client doesn't has an oauthToken, a new token is issed.
// If the token is expired, it is automatically refreshed.
func (c *Client) AddAuthorization(ctx context.Context, req *http.Request) error {
c.Lock()
defer c.Unlock()
if c.oauthToken == nil {
var err error
c.oauthToken, err = c.Oauth.getToken(ctx)
if err != nil {
return err
}
}
if c.oauthToken.isExpired() {
if err := c.oauthToken.refresh(ctx); err != nil {
return err
}
}
req.Header.Set("Authorization", fmt.Sprintf("bearer:%s", c.oauthToken.AccessToken))
return nil
}
// Do sends an API request and returns the API response. The API response is
// JSON decoded and stored in the value pointed to by v, or returned as an
// error if an API error has occurred. If v implements the io.Writer
// interface, the raw response body will be written to v, without attempting to
// first decode it.
//
// The provided ctx must be non-nil. If it is canceled or times out,
// ctx.Err() will be returned.
func (c *Client) Do(ctx context.Context, req *http.Request, v interface{}) (*Response, error) {
req = req.WithContext(ctx)
resp, err := c.client.Do(req)
if err != nil {
// If we got an error, and the context has been canceled,
// the context's error is probably more useful.
select {
case <-ctx.Done():
return nil, ctx.Err()
default:
}
return nil, err
}
defer func() {
// Drain up to 512 bytes and close the body to let the Transport reuse the connection.
_, _ = io.CopyN(ioutil.Discard, resp.Body, 512)
_ = resp.Body.Close()
}()
response := newResponse(resp)
err = CheckResponse(resp)
if err != nil {
// even though there was an error, we still return the response
// in case the caller wants to inspect it further.
return response, err
}
if v != nil {
if w, ok := v.(io.Writer); ok {
io.Copy(w, resp.Body)
} else {
var m responseMessage
err = json.NewDecoder(resp.Body).Decode(&m)
if err == io.EOF {
err = nil // ignore EOF errors caused by empty response body.
}
err = json.Unmarshal(m.Data, v)
if m.Pagination != nil {
response.PaginationAfterCursor = m.Pagination.AfterCursor
response.PaginationBeforeCursor = m.Pagination.BeforeCursor
}
}
}
return response, err
}
func newResponse(resp *http.Response) *Response {
return &Response{Response: resp}
}
// NewRequest instantiate a new http.Request from a method, url and body.
// The body (if provided) is automatically Marshalled into JSON.
func (c *Client) NewRequest(method, urlStr string, body interface{}) (*http.Request, error) {
rel, err := url.Parse(urlStr)
if err != nil {
return nil, err
}
u := c.BaseURL.ResolveReference(rel)
var buf io.ReadWriter
if body != nil {
buf = new(bytes.Buffer)
err := json.NewEncoder(buf).Encode(body)
if err != nil {
return nil, err
}
}
req, err := http.NewRequest(method, u.String(), buf)
if err != nil {
return nil, err
}
if body != nil {
req.Header.Set("Content-Type", "application/json")
}
req.Header.Set("Accept", "application/json")
if c.UserAgent != "" {
req.Header.Set("User-Agent", c.UserAgent)
}
return req, nil
}
type responseMessage struct {
Status struct {
Code int64 `json:"code"`
Type string `json:"type"`
Message string `json:"message"`
} `json:"status"`
Pagination *struct {
BeforeCursor *string `json:"before_cursor"`
AfterCursor *string `json:"after_cursor"`
} `json:"pagination"`
Data json.RawMessage `json:"data"`
}
// CheckResponse checks the *http.Response.
// HTTP status codes ranging from 200 to 299 are considered are successes.
// Otherwise an error happen, and the error gets unmarshalled and returned into the error.
func CheckResponse(r *http.Response) error {
if c := r.StatusCode; 200 <= c && c <= 299 {
return nil
}
errorResponse := &ErrorResponse{Response: r}
data, err := ioutil.ReadAll(r.Body)
if err == nil && data != nil {
var m responseMessage
_ = json.Unmarshal(data, &m)
errorResponse.Code = m.Status.Code
errorResponse.Type = m.Status.Type
errorResponse.Message = m.Status.Message
}
// TODO: handle the different errors here, such as MFA, Rate limit, etc...
return errorResponse
}
// Response embeds a *http.Response as well as some Paginations values.
type Response struct {
*http.Response
PaginationAfterCursor *string
PaginationBeforeCursor *string
}
// An ErrorResponse reports an error caused by an API request.
// Onelogin always returns Code, Type and a Message associated to the error.
// Example:
// {
// "status": {
// "error": true,
// "code": 400,
// "type": "bad request",
// "message": "Content Type is not specified or specified incorrectly.
// Content-Type header must be set to application/json"
// }
// }
type ErrorResponse struct {
Response *http.Response // HTTP response that caused this error
Code int64
Type string
Message string
}
func (r *ErrorResponse) Error() string {
return fmt.Sprintf("%v %v: OneLogin responsed with code %d, type %v and message %v",
r.Response.Request.Method, r.Response.Request.URL,
r.Response.StatusCode, r.Type, r.Message)
}
func buildURL(baseURL string, args ...interface{}) string {
return fmt.Sprintf(baseURL, args...)
}