-
-
Notifications
You must be signed in to change notification settings - Fork 164
/
GoTrueApi.ts
554 lines (531 loc) · 16.4 KB
/
GoTrueApi.ts
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
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
import { Fetch, get, post, put, remove } from './lib/fetch'
import { Session, Provider, UserAttributes, CookieOptions, User } from './lib/types'
import { COOKIE_OPTIONS } from './lib/constants'
import { setCookie, deleteCookie } from './lib/cookies'
import { expiresAt } from './lib/helpers'
import type { ApiError } from './lib/types'
export default class GoTrueApi {
protected url: string
protected headers: {
[key: string]: string
}
protected cookieOptions: CookieOptions
protected fetch?: Fetch
constructor({
url = '',
headers = {},
cookieOptions,
fetch,
}: {
url: string
headers?: {
[key: string]: string
}
cookieOptions?: CookieOptions
fetch?: Fetch
}) {
this.url = url
this.headers = headers
this.cookieOptions = { ...COOKIE_OPTIONS, ...cookieOptions }
this.fetch = fetch
}
/**
* Creates a new user.
*
* This function should only be called on a server. Never expose your `service_role` key in the browser.
*
* @param attributes The data you want to create the user with.
* @param jwt A valid JWT. Must be a full-access API key (e.g. service_role key).
*/
async createUser(
attributes: UserAttributes
): Promise<{ data: null; error: ApiError } | { data: User; error: null }> {
try {
const data: any = await post(this.fetch, `${this.url}/admin/users`, attributes, {
headers: this.headers,
})
return { data, error: null }
} catch (e) {
return { data: null, error: e as ApiError }
}
}
/**
* Get a list of users.
*
* This function should only be called on a server. Never expose your `service_role` key in the browser.
*/
async listUsers(): Promise<{ data: null; error: ApiError } | { data: User[]; error: null }> {
try {
const data: any = await get(this.fetch, `${this.url}/admin/users`, {
headers: this.headers,
})
return { data: data.users, error: null }
} catch (e) {
return { data: null, error: e as ApiError }
}
}
/**
* Creates a new user using their email address.
* @param email The email address of the user.
* @param password The password of the user.
* @param redirectTo A URL or mobile address to send the user to after they are confirmed.
* @param data Optional user metadata.
*
* @returns A logged-in session if the server has "autoconfirm" ON
* @returns A user if the server has "autoconfirm" OFF
*/
async signUpWithEmail(
email: string,
password: string,
options: {
redirectTo?: string
data?: object
} = {}
): Promise<{ data: Session | User | null; error: ApiError | null }> {
try {
const headers = { ...this.headers }
let queryString = ''
if (options.redirectTo) {
queryString = '?redirect_to=' + encodeURIComponent(options.redirectTo)
}
const data = await post(
this.fetch,
`${this.url}/signup${queryString}`,
{ email, password, data: options.data },
{ headers }
)
const session = { ...data }
if (session.expires_in) session.expires_at = expiresAt(data.expires_in)
return { data: session, error: null }
} catch (e) {
return { data: null, error: e as ApiError }
}
}
/**
* Logs in an existing user using their email address.
* @param email The email address of the user.
* @param password The password of the user.
* @param redirectTo A URL or mobile address to send the user to after they are confirmed.
*/
async signInWithEmail(
email: string,
password: string,
options: {
redirectTo?: string
} = {}
): Promise<{ data: Session | null; error: ApiError | null }> {
try {
const headers = { ...this.headers }
let queryString = '?grant_type=password'
if (options.redirectTo) {
queryString += '&redirect_to=' + encodeURIComponent(options.redirectTo)
}
const data = await post(
this.fetch,
`${this.url}/token${queryString}`,
{ email, password },
{ headers }
)
const session = { ...data }
if (session.expires_in) session.expires_at = expiresAt(data.expires_in)
return { data: session, error: null }
} catch (e) {
return { data: null, error: e as ApiError }
}
}
/**
* Signs up a new user using their phone number and a password.
* @param phone The phone number of the user.
* @param password The password of the user.
* @param data Optional user metadata.
*/
async signUpWithPhone(
phone: string,
password: string,
options: {
data?: object
} = {}
): Promise<{ data: Session | User | null; error: ApiError | null }> {
try {
const headers = { ...this.headers }
const data = await post(
this.fetch,
`${this.url}/signup`,
{ phone, password, data: options.data },
{ headers }
)
const session = { ...data }
if (session.expires_in) session.expires_at = expiresAt(data.expires_in)
return { data: session, error: null }
} catch (e) {
return { data: null, error: e as ApiError }
}
}
/**
* Logs in an existing user using their phone number and password.
* @param phone The phone number of the user.
* @param password The password of the user.
*/
async signInWithPhone(
phone: string,
password: string
): Promise<{ data: Session | null; error: ApiError | null }> {
try {
const headers = { ...this.headers }
const queryString = '?grant_type=password'
const data = await post(
this.fetch,
`${this.url}/token${queryString}`,
{ phone, password },
{ headers }
)
const session = { ...data }
if (session.expires_in) session.expires_at = expiresAt(data.expires_in)
return { data: session, error: null }
} catch (e) {
return { data: null, error: e as ApiError }
}
}
/**
* Sends a magic login link to an email address.
* @param email The email address of the user.
* @param redirectTo A URL or mobile address to send the user to after they are confirmed.
*/
async sendMagicLinkEmail(
email: string,
options: {
redirectTo?: string
} = {}
): Promise<{ data: {} | null; error: ApiError | null }> {
try {
const headers = { ...this.headers }
let queryString = ''
if (options.redirectTo) {
queryString += '?redirect_to=' + encodeURIComponent(options.redirectTo)
}
const data = await post(
this.fetch,
`${this.url}/magiclink${queryString}`,
{ email },
{ headers }
)
return { data, error: null }
} catch (e) {
return { data: null, error: e as ApiError }
}
}
/**
* Sends a mobile OTP via SMS. Will register the account if it doesn't already exist
* @param phone The user's phone number WITH international prefix
*/
async sendMobileOTP(phone: string): Promise<{ data: {} | null; error: ApiError | null }> {
try {
const headers = { ...this.headers }
const data = await post(this.fetch, `${this.url}/otp`, { phone }, { headers })
return { data, error: null }
} catch (e) {
return { data: null, error: e as ApiError }
}
}
/**
* Send User supplied Mobile OTP to be verified
* @param phone The user's phone number WITH international prefix
* @param token token that user was sent to their mobile phone
* @param redirectTo A URL or mobile address to send the user to after they are confirmed.
*/
async verifyMobileOTP(
phone: string,
token: string,
options: {
redirectTo?: string
} = {}
): Promise<{ data: Session | User | null; error: ApiError | null }> {
try {
const headers = { ...this.headers }
const data = await post(
this.fetch,
`${this.url}/verify`,
{ phone, token, type: 'sms', redirect_to: options.redirectTo },
{ headers }
)
return { data, error: null }
} catch (e) {
return { data: null, error: e as ApiError }
}
}
/**
* Sends an invite link to an email address.
* @param email The email address of the user.
* @param redirectTo A URL or mobile address to send the user to after they are confirmed.
* @param data Optional user metadata
*/
async inviteUserByEmail(
email: string,
options: {
redirectTo?: string
data?: object
} = {}
): Promise<{ data: User | null; error: ApiError | null }> {
try {
const headers = { ...this.headers }
let queryString = ''
if (options.redirectTo) {
queryString += '?redirect_to=' + encodeURIComponent(options.redirectTo)
}
const data = await post(
this.fetch,
`${this.url}/invite${queryString}`,
{ email, data: options.data },
{ headers }
)
return { data, error: null }
} catch (e) {
return { data: null, error: e as ApiError }
}
}
/**
* Sends a reset request to an email address.
* @param email The email address of the user.
* @param redirectTo A URL or mobile address to send the user to after they are confirmed.
*/
async resetPasswordForEmail(
email: string,
options: {
redirectTo?: string
} = {}
): Promise<{ data: {} | null; error: ApiError | null }> {
try {
const headers = { ...this.headers }
let queryString = ''
if (options.redirectTo) {
queryString += '?redirect_to=' + encodeURIComponent(options.redirectTo)
}
const data = await post(
this.fetch,
`${this.url}/recover${queryString}`,
{ email },
{ headers }
)
return { data, error: null }
} catch (e) {
return { data: null, error: e as ApiError }
}
}
/**
* Create a temporary object with all configured headers and
* adds the Authorization token to be used on request methods
* @param jwt A valid, logged-in JWT.
*/
private _createRequestHeaders(jwt: string) {
const headers = { ...this.headers }
headers['Authorization'] = `Bearer ${jwt}`
return headers
}
/**
* Removes a logged-in session.
* @param jwt A valid, logged-in JWT.
*/
async signOut(jwt: string): Promise<{ error: ApiError | null }> {
try {
await post(
this.fetch,
`${this.url}/logout`,
{},
{ headers: this._createRequestHeaders(jwt), noResolveJson: true }
)
return { error: null }
} catch (e) {
return { error: e as ApiError }
}
}
/**
* Generates the relevant login URL for a third-party provider.
* @param provider One of the providers supported by GoTrue.
* @param redirectTo A URL or mobile address to send the user to after they are confirmed.
* @param scopes A space-separated list of scopes granted to the OAuth application.
*/
getUrlForProvider(
provider: Provider,
options: {
redirectTo?: string
scopes?: string
}
) {
const urlParams: string[] = [`provider=${encodeURIComponent(provider)}`]
if (options?.redirectTo) {
urlParams.push(`redirect_to=${encodeURIComponent(options.redirectTo)}`)
}
if (options?.scopes) {
urlParams.push(`scopes=${encodeURIComponent(options.scopes)}`)
}
return `${this.url}/authorize?${urlParams.join('&')}`
}
/**
* Gets the user details.
* @param jwt A valid, logged-in JWT.
*/
async getUser(
jwt: string
): Promise<{ user: User | null; data: User | null; error: ApiError | null }> {
try {
const data: any = await get(this.fetch, `${this.url}/user`, {
headers: this._createRequestHeaders(jwt),
})
return { user: data, data, error: null }
} catch (e) {
return { user: null, data: null, error: e as ApiError }
}
}
/**
* Updates the user data.
* @param jwt A valid, logged-in JWT.
* @param attributes The data you want to update.
*/
async updateUser(
jwt: string,
attributes: UserAttributes
): Promise<{ user: User | null; data: User | null; error: ApiError | null }> {
try {
const data: any = await put(this.fetch, `${this.url}/user`, attributes, {
headers: this._createRequestHeaders(jwt),
})
return { user: data, data, error: null }
} catch (e) {
return { user: null, data: null, error: e as ApiError }
}
}
/**
* Delete a user. Requires a `service_role` key.
*
* This function should only be called on a server. Never expose your `service_role` key in the browser.
*
* @param uid The user uid you want to remove.
* @param jwt A valid JWT. Must be a full-access API key (e.g. service_role key).
*/
async deleteUser(
uid: string,
jwt: string
): Promise<{ user: User | null; data: User | null; error: ApiError | null }> {
try {
const data: any = await remove(
this.fetch,
`${this.url}/admin/users/${uid}`,
{},
{
headers: this._createRequestHeaders(jwt),
}
)
return { user: data, data, error: null }
} catch (e) {
return { user: null, data: null, error: e as ApiError }
}
}
/**
* Generates a new JWT.
* @param refreshToken A valid refresh token that was returned on login.
*/
async refreshAccessToken(
refreshToken: string
): Promise<{ data: Session | null; error: ApiError | null }> {
try {
const data: any = await post(
this.fetch,
`${this.url}/token?grant_type=refresh_token`,
{ refresh_token: refreshToken },
{ headers: this.headers }
)
const session = { ...data }
if (session.expires_in) session.expires_at = expiresAt(data.expires_in)
return { data: session, error: null }
} catch (e) {
return { data: null, error: e as ApiError }
}
}
/**
* Set/delete the auth cookie based on the AuthChangeEvent.
* Works for Next.js & Express (requires cookie-parser middleware).
*/
setAuthCookie(req: any, res: any) {
if (req.method !== 'POST') {
res.setHeader('Allow', 'POST')
res.status(405).end('Method Not Allowed')
}
const { event, session } = req.body
if (!event) throw new Error('Auth event missing!')
if (event === 'SIGNED_IN') {
if (!session) throw new Error('Auth session missing!')
setCookie(req, res, {
name: this.cookieOptions.name!,
value: session.access_token,
domain: this.cookieOptions.domain,
maxAge: this.cookieOptions.lifetime!,
path: this.cookieOptions.path,
sameSite: this.cookieOptions.sameSite,
})
}
if (event === 'SIGNED_OUT') deleteCookie(req, res, this.cookieOptions.name!)
res.status(200).json({})
}
/**
* Get user by reading the cookie from the request.
* Works for Next.js & Express (requires cookie-parser middleware).
*/
async getUserByCookie(req: any): Promise<{
token: string | null
user: User | null
data: User | null
error: ApiError | null
}> {
try {
if (!req.cookies) {
throw new Error(
'Not able to parse cookies! When using Express make sure the cookie-parser middleware is in use!'
)
}
if (!req.cookies[this.cookieOptions.name!]) {
throw new Error('No cookie found!')
}
const token = req.cookies[this.cookieOptions.name!]
const { user, error } = await this.getUser(token)
if (error) throw error
return { token, user, data: user, error: null }
} catch (e) {
return { token: null, user: null, data: null, error: e as ApiError }
}
}
/**
* Generates links to be sent via email or other.
* @param type The link type ("signup" or "magiclink" or "recovery" or "invite").
* @param email The user's email.
* @param password User password. For signup only.
* @param data Optional user metadata. For signup only.
* @param redirectTo The link type ("signup" or "magiclink" or "recovery" or "invite").
*/
async generateLink(
type: 'signup' | 'magiclink' | 'recovery' | 'invite',
email: string,
options: {
password?: string
data?: object
redirectTo?: string
} = {}
): Promise<{ data: Session | User | null; error: ApiError | null }> {
try {
const data: any = await post(
this.fetch,
`${this.url}/admin/generate_link`,
{
type,
email,
password: options.password,
data: options.data,
redirect_to: options.redirectTo,
},
{ headers: this.headers }
)
return { data, error: null }
} catch (e) {
return { data: null, error: e as ApiError }
}
}
}