-
Notifications
You must be signed in to change notification settings - Fork 20
/
clerk.go
381 lines (315 loc) · 9.44 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
package clerk
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/url"
"strconv"
"strings"
"time"
)
const version = "1.48.1"
const (
ProdUrl = "https://api.clerk.dev/v1/"
ActorTokensUrl = "actor_tokens"
AllowlistsUrl = "allowlist_identifiers"
BlocklistsUrl = "blocklist_identifiers"
ClientsUrl = "clients"
ClientsVerifyUrl = ClientsUrl + "/verify"
DomainsURL = "domains"
EmailAddressesURL = "email_addresses"
EmailsUrl = "emails"
InvitationsURL = "invitations"
OrganizationsUrl = "organizations"
PhoneNumbersURL = "phone_numbers"
RedirectURLsUrl = "redirect_urls"
SAMLConnectionsUrl = "saml_connections"
SessionsUrl = "sessions"
SMSUrl = "sms_messages"
TemplatesUrl = "templates"
UsersUrl = "users"
UsersCountUrl = UsersUrl + "/count"
WebhooksUrl = "webhooks"
JWTTemplatesUrl = "jwt_templates"
)
var defaultHTTPClient = &http.Client{Timeout: time.Second * 5}
type Client interface {
NewRequest(method, url string, body ...interface{}) (*http.Request, error)
Do(req *http.Request, v interface{}) (*http.Response, error)
DecodeToken(token string) (*TokenClaims, error)
VerifyToken(token string, opts ...VerifyTokenOption) (*SessionClaims, error)
Allowlists() *AllowlistsService
Blocklists() *BlocklistsService
Clients() *ClientsService
Domains() *DomainsService
EmailAddresses() *EmailAddressesService
Emails() *EmailService
ActorTokens() *ActorTokenService
Instances() *InstanceService
JWKS() *JWKSService
JWTTemplates() *JWTTemplatesService
Organizations() *OrganizationsService
PhoneNumbers() *PhoneNumbersService
RedirectURLs() *RedirectURLsService
SAMLConnections() *SAMLConnectionsService
Sessions() *SessionsService
SMS() *SMSService
Templates() *TemplatesService
Users() *UsersService
Webhooks() *WebhooksService
Verification() *VerificationService
Interstitial() ([]byte, error)
APIKey() string
}
type service struct {
client Client
}
type client struct {
client *http.Client
baseURL *url.URL
jwksCache *jwksCache
token string
allowlists *AllowlistsService
blocklists *BlocklistsService
clients *ClientsService
domains *DomainsService
emailAddresses *EmailAddressesService
emails *EmailService
actorTokens *ActorTokenService
instances *InstanceService
jwks *JWKSService
jwtTemplates *JWTTemplatesService
organizations *OrganizationsService
phoneNumbers *PhoneNumbersService
redirectURLs *RedirectURLsService
samlConnections *SAMLConnectionsService
sessions *SessionsService
sms *SMSService
templates *TemplatesService
users *UsersService
webhooks *WebhooksService
verification *VerificationService
}
// NewClient creates a new Clerk client.
// Because the token supplied will be used for all authenticated requests,
// the created client should not be used across different users
func NewClient(token string, options ...ClerkOption) (Client, error) {
if token == "" {
return nil, errors.New("you must provide an API token")
}
defaultBaseURL, err := toURLWithEndingSlash(ProdUrl)
if err != nil {
return nil, err
}
client := &client{
client: defaultHTTPClient,
baseURL: defaultBaseURL,
token: token,
}
for _, option := range options {
if err = option(client); err != nil {
return nil, err
}
}
commonService := &service{client: client}
client.allowlists = (*AllowlistsService)(commonService)
client.blocklists = (*BlocklistsService)(commonService)
client.clients = (*ClientsService)(commonService)
client.domains = (*DomainsService)(commonService)
client.emailAddresses = (*EmailAddressesService)(commonService)
client.emails = (*EmailService)(commonService)
client.actorTokens = (*ActorTokenService)(commonService)
client.instances = (*InstanceService)(commonService)
client.jwks = (*JWKSService)(commonService)
client.jwtTemplates = (*JWTTemplatesService)(commonService)
client.organizations = (*OrganizationsService)(commonService)
client.phoneNumbers = (*PhoneNumbersService)(commonService)
client.redirectURLs = (*RedirectURLsService)(commonService)
client.samlConnections = (*SAMLConnectionsService)(commonService)
client.sessions = (*SessionsService)(commonService)
client.sms = (*SMSService)(commonService)
client.templates = (*TemplatesService)(commonService)
client.users = (*UsersService)(commonService)
client.webhooks = (*WebhooksService)(commonService)
client.verification = (*VerificationService)(commonService)
client.jwksCache = &jwksCache{}
return client, nil
}
// Deprecated: NewClientWithBaseUrl is deprecated. Use the NewClient instead e.g. NewClient(token, WithBaseURL(baseUrl))
func NewClientWithBaseUrl(token, baseUrl string) (Client, error) {
return NewClient(token, WithBaseURL(baseUrl))
}
// Deprecated: NewClientWithCustomHTTP is deprecated. Use the NewClient instead e.g. NewClient(token, WithBaseURL(urlStr), WithHTTPClient(httpClient))
func NewClientWithCustomHTTP(token, urlStr string, httpClient *http.Client) (Client, error) {
return NewClient(token, WithBaseURL(urlStr), WithHTTPClient(httpClient))
}
func toURLWithEndingSlash(u string) (*url.URL, error) {
baseURL, err := url.Parse(u)
if err != nil {
return nil, err
}
if !strings.HasSuffix(baseURL.Path, "/") {
baseURL.Path += "/"
}
return baseURL, err
}
// NewRequest creates an API request.
// A relative URL `url` can be specified which is resolved relative to the baseURL of the client.
// Relative URLs should be specified without a preceding slash.
// The `body` parameter can be used to pass a body to the request. If no body is required, the parameter can be omitted.
func (c *client) NewRequest(method, url string, body ...interface{}) (*http.Request, error) {
fullUrl, err := c.baseURL.Parse(url)
if err != nil {
return nil, err
}
var buf io.ReadWriter
if len(body) > 0 && body[0] != nil {
buf = &bytes.Buffer{}
enc := json.NewEncoder(buf)
enc.SetEscapeHTML(false)
err := enc.Encode(body[0])
if err != nil {
return nil, err
}
}
req, err := http.NewRequest(method, fullUrl.String(), buf)
if err != nil {
return nil, err
}
// Add custom header with the current SDK version
req.Header.Set("X-Clerk-SDK", fmt.Sprintf("go/%s", version))
return req, nil
}
// Do will send the given request using the client `c` on which it is called.
// If the response contains a body, it will be unmarshalled in `v`.
func (c *client) Do(req *http.Request, v interface{}) (*http.Response, error) {
req.Header.Set("Authorization", "Bearer "+c.token)
resp, err := c.client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
err = checkForErrors(resp)
if err != nil {
return resp, err
}
if resp.Body != nil && v != nil {
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return resp, err
}
err = json.Unmarshal(body, &v)
if err != nil {
return resp, err
}
}
return resp, nil
}
func checkForErrors(resp *http.Response) error {
if c := resp.StatusCode; c >= 200 && c < 400 {
return nil
}
errorResponse := &ErrorResponse{Response: resp}
data, err := ioutil.ReadAll(resp.Body)
if err == nil && data != nil {
// it's ok if we cannot unmarshal to Clerk's error response
_ = json.Unmarshal(data, errorResponse)
}
return errorResponse
}
func (c *client) Allowlists() *AllowlistsService {
return c.allowlists
}
func (c *client) Blocklists() *BlocklistsService {
return c.blocklists
}
func (c *client) Clients() *ClientsService {
return c.clients
}
func (c *client) Domains() *DomainsService {
return c.domains
}
func (c *client) EmailAddresses() *EmailAddressesService {
return c.emailAddresses
}
func (c *client) Emails() *EmailService {
return c.emails
}
func (c *client) ActorTokens() *ActorTokenService {
return c.actorTokens
}
func (c *client) Instances() *InstanceService {
return c.instances
}
func (c *client) JWKS() *JWKSService {
return c.jwks
}
func (c *client) JWTTemplates() *JWTTemplatesService {
return c.jwtTemplates
}
func (c *client) Organizations() *OrganizationsService {
return c.organizations
}
func (c *client) PhoneNumbers() *PhoneNumbersService {
return c.phoneNumbers
}
func (c *client) RedirectURLs() *RedirectURLsService {
return c.redirectURLs
}
func (c *client) SAMLConnections() *SAMLConnectionsService {
return c.samlConnections
}
func (c *client) Sessions() *SessionsService {
return c.sessions
}
func (c *client) SMS() *SMSService {
return c.sms
}
func (c *client) Templates() *TemplatesService {
return c.templates
}
func (c *client) Users() *UsersService {
return c.users
}
func (c *client) Webhooks() *WebhooksService {
return c.webhooks
}
func (c *client) Verification() *VerificationService {
return c.verification
}
func (c *client) APIKey() string {
return c.token
}
func (c *client) Interstitial() ([]byte, error) {
req, err := c.NewRequest("GET", "internal/interstitial")
if err != nil {
return nil, err
}
req.Header.Set("Authorization", "Bearer "+c.token)
resp, err := c.client.Do(req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
interstitial, err := ioutil.ReadAll(resp.Body)
if err != nil {
return interstitial, err
}
return interstitial, nil
}
type PaginationParams struct {
Limit *int
Offset *int
}
func addPaginationParams(query url.Values, params PaginationParams) {
if params.Limit != nil {
query.Set("limit", strconv.Itoa(*params.Limit))
}
if params.Offset != nil {
query.Set("offset", strconv.Itoa(*params.Offset))
}
}