-
Notifications
You must be signed in to change notification settings - Fork 20
/
clerk.go
281 lines (229 loc) · 6.5 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
package clerk
import (
"bytes"
"encoding/json"
"errors"
"io"
"io/ioutil"
"net/http"
"net/url"
"strings"
"time"
)
const (
ProdUrl = "https://api.clerk.dev/v1/"
ClientsUrl = "clients"
ClientsVerifyUrl = ClientsUrl + "/verify"
EmailsUrl = "emails"
SessionsUrl = "sessions"
SMSUrl = "sms_messages"
TemplatesUrl = "templates"
UsersUrl = "users"
WebhooksUrl = "webhooks"
JWTTemplatesUrl = "jwt_templates"
)
var (
defaultHTTPClient = &http.Client{Timeout: time.Second * 5}
)
type Client interface {
NewRequest(method string, 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)
Clients() *ClientsService
Emails() *EmailService
JWKS() *JWKSService
JWTTemplates() *JWTTemplatesService
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
clients *ClientsService
emails *EmailService
jwks *JWKSService
jwtTemplates *JWTTemplatesService
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.clients = (*ClientsService)(commonService)
client.emails = (*EmailService)(commonService)
client.jwks = (*JWKSService)(commonService)
client.jwtTemplates = (*JWTTemplatesService)(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 string, 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 string, 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 string, 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
}
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) Clients() *ClientsService {
return c.clients
}
func (c *client) Emails() *EmailService {
return c.emails
}
func (c *client) JWKS() *JWKSService {
return c.jwks
}
func (c *client) JWTTemplates() *JWTTemplatesService {
return c.jwtTemplates
}
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
}