forked from r--w/pocketbase
-
Notifications
You must be signed in to change notification settings - Fork 14
/
record.go
453 lines (391 loc) · 13.5 KB
/
record.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
package pocketbase
import (
"encoding/json"
"fmt"
"net/url"
)
type (
AuthMethod struct {
AuthProviders []AuthProvider `json:"authProviders"`
UsernamePassword bool `json:"usernamePassword"`
EmailPassword bool `json:"emailPassword"`
OnlyVerified bool `json:"onlyVerified"`
}
AuthProvider struct {
Name string `json:"name"`
DisplayName string `json:"displayName"`
State string `json:"state"`
AuthURL string `json:"authUrl"`
CodeVerifier string `json:"codeVerifier"`
CodeChallenge string `json:"codeChallenge"`
CodeChallengeMethod string `json:"codeChallengeMethod"`
}
)
// ListAuthMethods returns all available collection auth methods.
func (c *Collection[T]) ListAuthMethods() (AuthMethod, error) {
var response AuthMethod
if err := c.Authorize(); err != nil {
return response, err
}
request := c.client.R().
SetHeader("Content-Type", "application/json")
resp, err := request.Get(c.BaseCollectionPath + "/auth-methods")
if err != nil {
return response, fmt.Errorf("[records] can't send ListAuthMethods request to pocketbase, err %w", err)
}
if resp.IsError() {
return response, fmt.Errorf("[records] pocketbase returned status: %d, msg: %s, err %w",
resp.StatusCode(),
resp.String(),
ErrInvalidResponse,
)
}
if err := json.Unmarshal(resp.Body(), &response); err != nil {
return response, fmt.Errorf("[records] can't unmarshal response, err %w", err)
}
return response, nil
}
type (
AuthWithPasswordResponse struct {
Record Record `json:"record"`
Token string `json:"token"`
}
Record struct {
Avatar string `json:"avatar"`
CollectionID string `json:"collectionId"`
CollectionName string `json:"collectionName"`
Created string `json:"created"`
Email string `json:"email"`
EmailVisibility bool `json:"emailVisibility"`
ID string `json:"id"`
Name string `json:"name"`
Updated string `json:"updated"`
Username string `json:"username"`
Verified bool `json:"verified"`
}
)
// AuthWithPassword authenticate a single auth collection record via its username/email and password.
//
// On success, this method also automatically updates
// the client's AuthStore data and returns:
// - the authentication token via the AuthWithPasswordResponse
// - the authenticated record model
func (c *Collection[T]) AuthWithPassword(username string, password string) (AuthWithPasswordResponse, error) {
var response AuthWithPasswordResponse
if err := c.Authorize(); err != nil {
return response, err
}
request := c.client.R().
SetHeader("Content-Type", "application/json").
SetMultipartFormData(map[string]string{
"identity": username,
"password": password,
})
resp, err := request.Post(c.BaseCollectionPath + "/auth-with-password")
if err != nil {
return response, fmt.Errorf("[records] can't send auth-with-password request to pocketbase, err %w", err)
}
if resp.IsError() {
return response, fmt.Errorf("[records] pocketbase returned status at auth-with-password: %d, msg: %s, err %w",
resp.StatusCode(),
resp.String(),
ErrInvalidResponse,
)
}
if err := json.Unmarshal(resp.Body(), &response); err != nil {
return response, fmt.Errorf("[records] can't unmarshal auth-with-password-response, err %w", err)
}
c.token = response.Token
return response, nil
}
type AuthWithOauth2Response struct {
Token string `json:"token"`
}
// AuthWithOAuth2Code authenticate a single auth collection record with OAuth2 code.
//
// If you don't have an OAuth2 code you may also want to check `authWithOAuth2` method.
//
// On success, this method also automatically updates
// the client's AuthStore data and returns:
// - the authentication token via the model
// - the authenticated record model
// - the OAuth2 account data (eg. name, email, avatar, etc.)
func (c *Collection[T]) AuthWithOAuth2Code(provider string, code string, codeVerifier string, redirectURL string) (AuthWithOauth2Response, error) {
var response AuthWithOauth2Response
if err := c.Authorize(); err != nil {
return response, err
}
request := c.client.R().
SetHeader("Content-Type", "application/json").
SetMultipartFormData(map[string]string{
"provider": provider,
"code": code,
"codeVerifier": codeVerifier,
"redirectUrl": redirectURL,
//"createData": createData,
})
resp, err := request.Post(c.BaseCollectionPath + "/auth-with-oauth2")
if err != nil {
return response, fmt.Errorf("[records] can't send auth-with-oauth2 request to pocketbase, err %w", err)
}
if resp.IsError() {
return response, fmt.Errorf("[records] pocketbase returned status at auth-with-oauth2: %d, msg: %s, err %w",
resp.StatusCode(),
resp.String(),
ErrInvalidResponse,
)
}
if err := json.Unmarshal(resp.Body(), &response); err != nil {
return response, fmt.Errorf("[records] can't unmarshal auth-with-oauth2-response, err %w", err)
}
c.token = response.Token
return response, nil
}
type AuthRefreshResponse struct {
Record struct {
Avatar string `json:"avatar"`
CollectionID string `json:"collectionId"`
CollectionName string `json:"collectionName"`
Created string `json:"created"`
Email string `json:"email"`
EmailVisibility bool `json:"emailVisibility"`
ID string `json:"id"`
Name string `json:"name"`
Updated string `json:"updated"`
Username string `json:"username"`
Verified bool `json:"verified"`
} `json:"record"`
Token string `json:"token"`
}
// AuthRefresh refreshes the current authenticated record instance and
// * returns a new token and record data.
func (c *Collection[T]) AuthRefresh() (AuthRefreshResponse, error) {
var response AuthRefreshResponse
if err := c.Authorize(); err != nil {
return response, err
}
request := c.client.R().
SetHeader("Content-Type", "application/json").
SetAuthToken(c.token)
resp, err := request.Post(c.BaseCollectionPath + "/auth-refresh")
if err != nil {
return response, fmt.Errorf("[records] can't send auth-refresh request to pocketbase, err %w", err)
}
if resp.IsError() {
return response, fmt.Errorf("[records] pocketbase returned status at auth-refresh: %d, msg: %s, err %w",
resp.StatusCode(),
resp.String(),
ErrInvalidResponse,
)
}
if err := json.Unmarshal(resp.Body(), &response); err != nil {
return response, fmt.Errorf("[records] can't unmarshal auth-refresh-response, err %w", err)
}
c.token = response.Token
return response, nil
}
// RequestVerification sends auth record verification email request.
func (c *Collection[T]) RequestVerification(email string) error {
if err := c.Authorize(); err != nil {
return err
}
request := c.client.R().
SetHeader("Content-Type", "application/json").
SetMultipartFormData(map[string]string{
"email": email,
})
resp, err := request.Post(c.BaseCollectionPath + "/request-verification")
if err != nil {
return fmt.Errorf("[records] can't send request-verification request to pocketbase, err %w", err)
}
if resp.IsError() {
return fmt.Errorf("[records] pocketbase returned status at request-verification: %d, msg: %s, err %w",
resp.StatusCode(),
resp.String(),
ErrInvalidResponse,
)
}
return nil
}
// ConfirmVerification confirms auth record email verification request.
//
// If the current `client.authStore.model` matches with the auth record from the token,
// then on success the `client.authStore.model.verified` will be updated to `true`.
func (c *Collection[T]) ConfirmVerification(verificationToken string) error {
if err := c.Authorize(); err != nil {
return err
}
request := c.client.R().
SetHeader("Content-Type", "application/json").
SetMultipartFormData(map[string]string{
"token": verificationToken,
})
resp, err := request.Post(c.BaseCollectionPath + "/confirm-verification")
if err != nil {
return fmt.Errorf("[records] can't send confirm-verification request to pocketbase, err %w", err)
}
if resp.IsError() {
return fmt.Errorf("[records] pocketbase returned status at confirm-verification: %d, msg: %s, err %w",
resp.StatusCode(),
resp.String(),
ErrInvalidResponse,
)
}
return nil
}
// RequestPasswordReset sends auth record password reset request
func (c *Collection[T]) RequestPasswordReset(email string) error {
if err := c.Authorize(); err != nil {
return err
}
request := c.client.R().
SetHeader("Content-Type", "application/json").
SetMultipartFormData(map[string]string{
"email": email,
})
resp, err := request.Post(c.BaseCollectionPath + "/request-password-reset")
if err != nil {
return fmt.Errorf("[records] can't send request-password-reset request to pocketbase, err %w", err)
}
if resp.IsError() {
return fmt.Errorf("[records] pocketbase returned status at request-password-reset: %d, msg: %s, err %w",
resp.StatusCode(),
resp.String(),
ErrInvalidResponse,
)
}
return nil
}
// ConfirmPasswordReset confirms auth record password reset request.
func (c *Collection[T]) ConfirmPasswordReset(passwordResetToken string, password string, passwordConfirm string) error {
if err := c.Authorize(); err != nil {
return err
}
request := c.client.R().
SetHeader("Content-Type", "application/json").
SetMultipartFormData(map[string]string{
"token": passwordResetToken,
"password": password,
"passwordConfirm": passwordConfirm,
})
resp, err := request.Post(c.BaseCollectionPath + "/confirm-password-reset")
if err != nil {
return fmt.Errorf("[records] can't send confirm-password-reset request to pocketbase, err %w", err)
}
if resp.IsError() {
return fmt.Errorf("[records] pocketbase returned status at confirm-password-reset: %d, msg: %s, err %w",
resp.StatusCode(),
resp.String(),
ErrInvalidResponse,
)
}
return nil
}
// RequestEmailChange sends an email change request to the authenticated record model.
func (c *Collection[T]) RequestEmailChange(newEmail string) error {
if err := c.Authorize(); err != nil {
return err
}
request := c.client.R().
SetHeader("Content-Type", "application/json").
SetMultipartFormData(map[string]string{
"newEmail": newEmail,
}).
SetAuthToken(c.token)
resp, err := request.Post(c.BaseCollectionPath + "/request-email-change")
if err != nil {
return fmt.Errorf("[records] can't send request-email-change request to pocketbase, err %w", err)
}
if resp.IsError() {
return fmt.Errorf("[records] pocketbase returned status at request-email-change: %d, msg: %s, err %w",
resp.StatusCode(),
resp.String(),
ErrInvalidResponse,
)
}
return nil
}
// ConfirmEmailChange confirms auth record's new email address.
func (c *Collection[T]) ConfirmEmailChange(emailChangeToken string, password string) error {
if err := c.Authorize(); err != nil {
return err
}
request := c.client.R().
SetHeader("Content-Type", "application/json").
SetMultipartFormData(map[string]string{
"token": emailChangeToken,
"password": password,
}).
SetAuthToken(c.token)
resp, err := request.Post(c.BaseCollectionPath + "/confirm-email-change")
if err != nil {
return fmt.Errorf("[records] can't send confirm-email-change request to pocketbase, err %w", err)
}
if resp.IsError() {
return fmt.Errorf("[records] pocketbase returned status at confirm-email-change: %d, msg: %s, err %w",
resp.StatusCode(),
resp.String(),
ErrInvalidResponse,
)
}
return nil
}
type ExternalAuthRequest struct {
ID string `json:"id"`
Created string `json:"created"`
Updated string `json:"updated"`
RecordID string `json:"recordId"`
CollectionID string `json:"collectionId"`
Provider string `json:"provider"`
ProviderID string `json:"providerId"`
}
// ListExternalAuths lists all linked external auth providers for the specified auth record.
func (c *Collection[T]) ListExternalAuths(recordID string) ([]ExternalAuthRequest, error) {
var response []ExternalAuthRequest
if err := c.Authorize(); err != nil {
return response, err
}
request := c.client.R().
SetHeader("Content-Type", "application/json")
resp, err := request.Get(c.baseCrudPath() + url.QueryEscape(recordID) + "/external-auths")
if err != nil {
return response, fmt.Errorf("[records] can't send list external-auths request to pocketbase, err %w", err)
}
if resp.IsError() {
return response, fmt.Errorf("[records] pocketbase request for list external-auths returned status: %d, msg: %s, err %w",
resp.StatusCode(),
resp.String(),
ErrInvalidResponse,
)
}
if err := json.Unmarshal(resp.Body(), &response); err != nil {
return response, fmt.Errorf("[records] can't unmarshal list external-auths response, err %w", err)
}
return response, nil
}
// UnlinkExternalAuth unlink a single external auth provider from the specified auth record.
func (c *Collection[T]) UnlinkExternalAuth(recordID string, provider string) error {
if err := c.Authorize(); err != nil {
return err
}
request := c.client.R().
SetHeader("Content-Type", "application/json")
resp, err := request.Delete(c.baseCrudPath() + url.QueryEscape(recordID) + "/external-auths/" + url.QueryEscape(provider))
if err != nil {
return fmt.Errorf("[records] can't send unlink-external-auth-request to pocketbase, err %w", err)
}
if resp.IsError() {
return fmt.Errorf("[records] pocketbase returned status at unlink-external-auth-: %d, msg: %s, err %w",
resp.StatusCode(),
resp.String(),
ErrInvalidResponse,
)
}
return nil
}
func (c *Collection[T]) baseCollectionPath() string {
return c.BaseCollectionPath
}
func (c *Collection[T]) baseCrudPath() string {
return c.BaseCollectionPath + "/records/"
}