-
Notifications
You must be signed in to change notification settings - Fork 20
/
clerk.go
523 lines (456 loc) · 13.7 KB
/
clerk.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
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
// Package clerk provides a way to communicate with the Clerk API.
// Includes types for Clerk API requests, responses and all
// available resources.
package clerk
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"regexp"
"strconv"
"strings"
"sync"
"time"
)
const (
sdkVersion string = "v2.0.0"
clerkAPIVersion string = "2021-02-05"
)
const (
// APIURL is the base URL for the Clerk API.
APIURL string = "https://api.clerk.com/v1"
)
// The Clerk secret key. Configured on a package level.
var secretKey string
// SetKey sets the Clerk API key.
func SetKey(key string) {
secretKey = key
}
// APIResource describes a Clerk API resource and contains fields and
// methods common to all resources.
type APIResource struct {
Response *APIResponse `json:"-"`
}
// Read sets the response on the resource.
func (r *APIResource) Read(response *APIResponse) {
r.Response = response
}
// APIParams implements functionality that's common to all types
// that can be used as API request parameters.
// It is recommended to embed this type to all types that will be
// used for API operation parameters.
type APIParams struct {
}
// ToQuery can be used to transform the params to querystring
// values.
// It is currently a no-op, but is defined so that all types
// that describe API operation parameters implement the Params
// interface.
func (params *APIParams) ToQuery() url.Values {
return nil
}
// ToMultipart can transform the params to a multipart entity.
// It is currently a no-op, but is defined so that all types
// that describe API operation parameters implement the Params
// interface.
func (params *APIParams) ToMultipart() ([]byte, string, error) {
return nil, "", nil
}
// APIResponse describes responses coming from the Clerk API.
// Exposes some commonly used HTTP response fields along with
// the raw data in the response body.
type APIResponse struct {
Header http.Header
Status string // e.g. "200 OK"
StatusCode int // e.g. 200
// TraceID is a unique identifier for tracing the origin of the
// response.
// Useful for debugging purposes.
TraceID string
// RawJSON contains the response body as raw bytes.
RawJSON json.RawMessage
}
// Success returns true for API response status codes in the
// 200-399 range, false otherwise.
func (resp *APIResponse) Success() bool {
return resp.StatusCode < 400
}
// NewAPIResponse creates an APIResponse from the passed http.Response
// and the raw response body.
func NewAPIResponse(resp *http.Response, body json.RawMessage) *APIResponse {
return &APIResponse{
Header: resp.Header,
TraceID: resp.Header.Get("Clerk-Trace-Id"),
Status: resp.Status,
StatusCode: resp.StatusCode,
RawJSON: body,
}
}
// APIRequest describes requests to the Clerk API.
type APIRequest struct {
Method string
Path string
Params Params
isMultipart bool
}
// SetParams sets the APIRequest.Params.
func (req *APIRequest) SetParams(params Params) {
req.Params = params
}
// NewAPIRequest creates an APIRequest with the provided HTTP method
// and path.
func NewAPIRequest(method, path string) *APIRequest {
return &APIRequest{
Method: method,
Path: path,
}
}
// NewMultipartAPIRequest creates an APIRequest with the provided HTTP
// method and path and marks it as multipart. Multipart requests handle
// their params differently.
func NewMultipartAPIRequest(method, path string) *APIRequest {
req := NewAPIRequest(method, path)
req.isMultipart = true
return req
}
// Backend is the primary interface for communicating with the Clerk
// API.
type Backend interface {
// Call makes requests to the Clerk API.
Call(context.Context, *APIRequest, ResponseReader) error
}
// ResponseReader reads Clerk API responses.
type ResponseReader interface {
Read(*APIResponse)
}
// Params can transform themselves to types that can be used as
// request parameters, like query string values or multipart
// data.
type Params interface {
ToQuery() url.Values
ToMultipart() ([]byte, string, error)
}
// CustomRequestHeaders contains predefined values that can be
// used as custom headers in Backend API requests.
type CustomRequestHeaders struct {
Application string
}
// Apply the custom headers to the HTTP request.
func (h *CustomRequestHeaders) apply(req *http.Request) {
if h == nil {
return
}
req.Header.Add("X-Clerk-Application", h.Application)
}
// BackendConfig is used to configure a new Clerk Backend.
type BackendConfig struct {
// HTTPClient is an HTTP client instance that will be used for
// making API requests.
// If it's not set a default HTTP client will be used.
HTTPClient *http.Client
// URL is the base URL to use for API endpoints.
// If it's not set, the default value for the Backend will be used.
URL *string
// Key is the Clerk secret key. If it's not set, the package level
// secretKey will be used.
Key *string
// CustomRequestHeaders allows you to provide predefined custom
// headers that will be added to every HTTP request that the Backend
// does.
CustomRequestHeaders *CustomRequestHeaders
}
// NewBackend returns a default backend implementation with the
// provided configuration.
// Please note that the return type is an interface because the
// Backend is not supposed to be used directly.
func NewBackend(config *BackendConfig) Backend {
if config.HTTPClient == nil {
config.HTTPClient = defaultHTTPClient
}
if config.URL == nil {
config.URL = String(APIURL)
}
if config.Key == nil {
config.Key = String(secretKey)
}
return &defaultBackend{
HTTPClient: config.HTTPClient,
URL: *config.URL,
Key: *config.Key,
CustomRequestHeaders: config.CustomRequestHeaders,
}
}
// GetBackend returns the library's supported backend for the Clerk
// API.
func GetBackend() Backend {
var b Backend
backend.mu.RLock()
b = backend.Backend
backend.mu.RUnlock()
if b != nil {
return b
}
b = NewBackend(&BackendConfig{})
SetBackend(b)
return b
}
// SetBackend sets the Backend that will be used to make requests
// to the Clerk API.
// Use this method if you need to override the default Backend
// configuration.
func SetBackend(b Backend) {
backend.mu.Lock()
defer backend.mu.Unlock()
backend.Backend = b
}
type defaultBackend struct {
HTTPClient *http.Client
URL string
Key string
CustomRequestHeaders *CustomRequestHeaders
}
// Call sends requests to the Clerk API and handles the responses.
func (b *defaultBackend) Call(ctx context.Context, apiReq *APIRequest, setter ResponseReader) error {
req, err := b.newRequest(ctx, apiReq)
if err != nil {
return err
}
err = setRequestBody(req, apiReq)
if err != nil {
return err
}
return b.do(req, setter)
}
func (b *defaultBackend) newRequest(ctx context.Context, apiReq *APIRequest) (*http.Request, error) {
path, err := JoinPath(b.URL, apiReq.Path)
if err != nil {
return nil, err
}
req, err := http.NewRequestWithContext(ctx, apiReq.Method, path, nil)
if err != nil {
return nil, err
}
req.Header.Add("Authorization", fmt.Sprintf("Bearer %s", b.Key))
req.Header.Add("Content-Type", "application/json")
req.Header.Add("User-Agent", fmt.Sprintf("clerk/clerk-sdk-go@%s", sdkVersion))
req.Header.Add("Clerk-API-Version", clerkAPIVersion)
req.Header.Add("X-Clerk-SDK", fmt.Sprintf("go/%s", sdkVersion))
b.CustomRequestHeaders.apply(req)
return req, nil
}
func (b *defaultBackend) do(req *http.Request, setter ResponseReader) error {
resp, err := b.HTTPClient.Do(req)
if err != nil {
return err
}
resBody, err := io.ReadAll(resp.Body)
defer resp.Body.Close()
if err != nil {
return err
}
apiResponse := NewAPIResponse(resp, resBody)
// Looks like something went wrong. Handle the error.
if !apiResponse.Success() {
return handleError(apiResponse, resBody)
}
setter.Read(apiResponse)
if len(resBody) > 0 {
err := json.Unmarshal(resBody, setter)
if err != nil {
return err
}
}
return nil
}
// Sets the APIRequest params in either the request body, or the
// querystring for GET requests.
// If the APIRequest is multipart, the http.Request Content-Type
// is overwritten and the body will be sent as a multipart message.
func setRequestBody(req *http.Request, apiReq *APIRequest) error {
// GET requests don't have a body, but we will pass the params
// in the query string.
if req.Method == http.MethodGet {
setRequestQuery(req, apiReq.Params)
return nil
}
var body []byte
var err error
if apiReq.isMultipart {
var contentType string
body, contentType, err = apiReq.Params.ToMultipart()
if err != nil {
return err
}
req.Header.Set("Content-Type", contentType)
} else {
body, err = json.Marshal(apiReq.Params)
if err != nil {
return err
}
}
req.Body = io.NopCloser(bytes.NewReader(body))
req.GetBody = func() (io.ReadCloser, error) {
return io.NopCloser(bytes.NewReader(body)), nil
}
return nil
}
// Sets the params in the request querystring. Any existing values
// will be preserved, unless overriden. Keys in the params querystring
// always win.
func setRequestQuery(req *http.Request, params Params) {
if params == nil {
return
}
q := req.URL.Query()
paramsQuery := params.ToQuery()
for k, values := range paramsQuery {
for _, v := range values {
q.Add(k, v)
}
}
req.URL.RawQuery = q.Encode()
}
// Error API response handling.
func handleError(resp *APIResponse, body []byte) error {
apiError := &APIErrorResponse{
HTTPStatusCode: resp.StatusCode,
}
apiError.Read(resp)
err := json.Unmarshal(body, apiError)
if err != nil || apiError.Errors == nil {
// This is probably not an expected API error.
// Return the raw server response.
return errors.New(string(body))
}
return apiError
}
// The active Backend
var backend api
// This type is a container for a Backend. Guarantees thread-safe
// access to the current Backend.
type api struct {
Backend Backend
mu sync.RWMutex
}
// defaultHTTPTimeout is the default timeout on the http.Client used
// by the library.
const defaultHTTPTimeout = 5 * time.Second
// The default HTTP client used for communication with the Clerk API.
var defaultHTTPClient = &http.Client{
Timeout: defaultHTTPTimeout,
}
// APIErrorResponse is used for cases where requests to the Clerk
// API result in error responses.
type APIErrorResponse struct {
APIResource
Errors []Error `json:"errors"`
HTTPStatusCode int `json:"status,omitempty"`
TraceID string `json:"clerk_trace_id,omitempty"`
}
// Error returns the marshaled representation of the APIErrorResponse.
func (resp *APIErrorResponse) Error() string {
ret, err := json.Marshal(resp)
if err != nil {
// This shouldn't happen, let's return the raw response
return string(resp.Response.RawJSON)
}
return string(ret)
}
// Error is a representation of a single error that can occur in the
// Clerk API.
type Error struct {
Code string `json:"code"`
Message string `json:"message"`
LongMessage string `json:"long_message"`
Meta json.RawMessage `json:"meta,omitempty"`
}
// ListParams holds fields that are common for list API operations.
type ListParams struct {
Limit *int64 `json:"limit,omitempty"`
Offset *int64 `json:"offset,omitempty"`
}
// ToQuery returns url.Values with the ListParams values in the
// querystring.
func (params ListParams) ToQuery() url.Values {
q := url.Values{}
if params.Limit != nil {
q.Set("limit", strconv.FormatInt(*params.Limit, 10))
}
if params.Offset != nil {
q.Set("offset", strconv.FormatInt(*params.Offset, 10))
}
return q
}
// ClientConfig is used to configure a new Client that can invoke
// API operations.
type ClientConfig struct {
BackendConfig
}
// Clock is an interface that can be used with the library instead
// of the [time] package.
// The interface is useful for testing time sensitive paths or
// feeding the library with an authoritative source of time, like
// an external time generator.
type Clock interface {
Now() time.Time
}
// A default implementation of a Clock, keeping the real time by
// using the [time] package directly.
type defaultClock struct{}
// Now returns the current time.
func (c *defaultClock) Now() time.Time {
return time.Now().UTC()
}
// NewClock returns a default clock implementation which calls
// the [time] package internally.
// Please note that the return type is an interface because the
// Clock is not supposed to be used directly.
func NewClock() Clock {
return &defaultClock{}
}
// Regular expression that matches multiple forward slashes in a row.
var extraForwardslashesRE = regexp.MustCompile("(^/+|([^:])//+)")
// JoinPath returns a URL string with the provided path elements joined
// with the base path.
func JoinPath(base string, elem ...string) (string, error) {
// Concatenate all paths.
var sb strings.Builder
sb.WriteString(base)
for _, el := range elem {
sb.WriteString("/")
sb.WriteString(el)
}
// Trim leading and trailing forward slashes, replace all occurrences of
// multiple forward slashes in a row with one forward slash, preserve the
// protocol's two forward slashes.
// e.g. http://foo.com//bar/ will become http://foo.com/bar
trimRightForwardSlashes := strings.TrimRight(sb.String(), "/")
res := extraForwardslashesRE.ReplaceAllString(trimRightForwardSlashes, "$2/")
// Make sure we have a valid URL.
u, err := url.Parse(res)
if err != nil {
return "", err
}
return u.String(), nil
}
// String returns a pointer to the provided string value.
func String(v string) *string {
return &v
}
// Int64 returns a pointer to the provided int64 value.
func Int64(v int64) *int64 {
return &v
}
// Bool returns a pointer to the provided bool value.
func Bool(v bool) *bool {
return &v
}
// JSONRawMessage returns a pointer to the provided json.RawMessage value.
func JSONRawMessage(v json.RawMessage) *json.RawMessage {
return &v
}