/
AuthProvider.tsx
438 lines (394 loc) · 11.7 KB
/
AuthProvider.tsx
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
import React, {
ReactNode,
useCallback,
useEffect,
useMemo,
useState,
} from 'react'
import { createAuthClient } from './authClients'
import type {
AuthClient,
SupportedAuthTypes,
SupportedAuthConfig,
SupportedAuthClients,
SupportedUserMetadata,
} from './authClients'
import type { WebAuthnClientType } from './webAuthn'
export interface CurrentUser {
roles?: Array<string> | string
}
export interface AuthContextInterface {
/* Determining your current authentication state */
loading: boolean
isAuthenticated: boolean
/* The current user's data from the `getCurrentUser` function on the api side */
currentUser: null | CurrentUser
/* The user's metadata from the auth provider */
userMetadata: null | SupportedUserMetadata
logIn(options?: unknown): Promise<any>
logOut(options?: unknown): Promise<any>
signUp(options?: unknown): Promise<any>
/**
* Clients should always return null or string
* It is expected that they catch any errors internally
*/
getToken(): Promise<null | string>
/**
* Fetches the "currentUser" from the api side,
* but does not update the current user state.
**/
getCurrentUser(): Promise<null | CurrentUser>
/**
* Checks if the "currentUser" from the api side
* is assigned a role or one of a list of roles.
* If the user is assigned any of the provided list of roles,
* the hasRole is considered to be true.
**/
hasRole(rolesToCheck: string | string[]): boolean
/**
* Redetermine authentication state and update the state.
*/
reauthenticate(): Promise<void>
forgotPassword(username: string): Promise<any>
resetPassword(options?: unknown): Promise<any>
validateResetToken(resetToken: string | null): Promise<any>
/**
* A reference to the client that you passed into the `AuthProvider`,
* which is useful if we do not support some specific functionality.
*/
client?: SupportedAuthClients
type?: SupportedAuthTypes
hasError: boolean
error?: Error
}
export const AuthContext = React.createContext<AuthContextInterface>({
loading: true,
isAuthenticated: false,
userMetadata: null,
currentUser: null,
logIn: () => Promise.resolve(),
logOut: () => Promise.resolve(),
signUp: () => Promise.resolve(),
getToken: () => Promise.resolve(null),
getCurrentUser: () => Promise.resolve(null),
hasRole: () => true,
reauthenticate: () => Promise.resolve(),
forgotPassword: () => Promise.resolve(),
resetPassword: () => Promise.resolve(),
validateResetToken: () => Promise.resolve(),
hasError: false,
})
const AuthUpdateListener = ({
rwClient,
reauthenticate,
}: {
rwClient?: AuthClient
reauthenticate: () => Promise<void>
}) => {
rwClient?.useListenForUpdates?.({ reauthenticate })
return null
}
type AuthProviderProps =
| {
client: SupportedAuthClients
type: Omit<SupportedAuthTypes, 'clerk' | 'dbAuth'>
config?: never
skipFetchCurrentUser?: boolean
children?: ReactNode | undefined
}
| {
client?: never
type: 'clerk'
config?: never
skipFetchCurrentUser?: boolean
children?: ReactNode | undefined
}
| {
client?: WebAuthnClientType
type: 'dbAuth'
config?: SupportedAuthConfig
skipFetchCurrentUser?: boolean
children?: ReactNode | undefined
}
type AuthProviderState = {
loading: boolean
isAuthenticated: boolean
userMetadata: null | Record<string, any>
currentUser: null | CurrentUser
hasError: boolean
error?: Error
}
const defaultAuthProviderState: AuthProviderState = {
loading: true,
isAuthenticated: false,
userMetadata: null,
currentUser: null,
hasError: false,
}
/**
* @example
* ```js
* const client = new Auth0Client(options)
* // ...
* <AuthProvider client={client} type="auth0" skipFetchCurrentUser={true}>
* {children}
* </AuthProvider>
* ```
*/
export const AuthProvider = (props: AuthProviderProps) => {
const skipFetchCurrentUser = props.skipFetchCurrentUser || false
const [hasRestoredState, setHasRestoredState] = useState(false)
const [authProviderState, setAuthProviderState] = useState(
defaultAuthProviderState
)
const [rwClient, setRwClient] = useState<AuthClient>()
const rwClientPromise: Promise<AuthClient> = useMemo(async () => {
// If ever we rebuild the rwClient, we need to re-restore the state.
// This is not desired behavior, but may happen if for some reason the host app's
// auth configuration changes mid-flight.
setHasRestoredState(false)
const client = await createAuthClient(
props.client as SupportedAuthClients,
props.type as SupportedAuthTypes,
props.config as SupportedAuthConfig
)
setRwClient(client)
return client
}, [props.client, props.type, props.config])
/**
* Clients should always return null or token string.
* It is expected that they catch any errors internally.
* This catch is a last resort effort in case any errors are
* missed or slip through.
*/
const getToken = useCallback(async () => {
const client = await rwClientPromise
try {
const token = await client.getToken()
return token
} catch (e) {
console.error('Caught internal:', e)
return null
}
}, [rwClientPromise])
const getCurrentUser = useCallback(async (): Promise<
Record<string, unknown>
> => {
const client = await rwClientPromise
// Always get a fresh token, rather than use the one in state
const token = await getToken()
const response = await global.fetch(global.RWJS_API_GRAPHQL_URL, {
method: 'POST',
// TODO: how can user configure this? inherit same `config` options given to auth client?
credentials: 'include',
headers: {
'content-type': 'application/json',
'auth-provider': client.type,
authorization: `Bearer ${token}`,
},
body: JSON.stringify({
query:
'query __REDWOOD__AUTH_GET_CURRENT_USER { redwood { currentUser } }',
}),
})
if (response.ok) {
const { data } = await response.json()
return data?.redwood?.currentUser
} else {
throw new Error(
`Could not fetch current user: ${response.statusText} (${response.status})`
)
}
}, [rwClientPromise, getToken])
const reauthenticate = useCallback(async () => {
const client = await rwClientPromise
const notAuthenticatedState: AuthProviderState = {
isAuthenticated: false,
currentUser: null,
userMetadata: null,
loading: false,
hasError: false,
}
try {
const userMetadata = await client.getUserMetadata()
if (!userMetadata) {
setAuthProviderState(notAuthenticatedState)
} else {
await getToken()
const currentUser = skipFetchCurrentUser ? null : await getCurrentUser()
setAuthProviderState((oldState) => ({
...oldState,
userMetadata,
currentUser,
isAuthenticated: true,
loading: false,
}))
}
} catch (e: any) {
setAuthProviderState({
...notAuthenticatedState,
hasError: true,
error: e as Error,
})
}
}, [
getToken,
rwClientPromise,
setAuthProviderState,
skipFetchCurrentUser,
getCurrentUser,
])
/**
* @example
* ```js
* hasRole("editor")
* hasRole(["editor"])
* hasRole(["editor", "author"])
* ```
*
* Checks if the "currentUser" from the api side
* is assigned a role or one of a list of roles.
* If the user is assigned any of the provided list of roles,
* the hasRole is considered to be true.
*/
const hasRole = useCallback(
(rolesToCheck: string | string[]): boolean => {
const currentUser = authProviderState.currentUser
if (currentUser?.roles) {
if (typeof rolesToCheck === 'string') {
if (typeof currentUser.roles === 'string') {
// rolesToCheck is a string, currentUser.roles is a string
return currentUser.roles === rolesToCheck
} else if (Array.isArray(currentUser.roles)) {
// rolesToCheck is a string, currentUser.roles is an array
return currentUser.roles?.some(
(allowedRole) => rolesToCheck === allowedRole
)
}
}
if (Array.isArray(rolesToCheck)) {
if (Array.isArray(currentUser.roles)) {
// rolesToCheck is an array, currentUser.roles is an array
return currentUser.roles?.some((allowedRole) =>
rolesToCheck.includes(allowedRole)
)
} else if (typeof currentUser.roles === 'string') {
// rolesToCheck is an array, currentUser.roles is a string
return rolesToCheck.some(
(allowedRole) => currentUser?.roles === allowedRole
)
}
}
}
return false
},
[authProviderState.currentUser]
)
const logIn = useCallback(
async (options?: any) => {
setAuthProviderState(defaultAuthProviderState)
const client = await rwClientPromise
const loginOutput = await client.login(options)
await reauthenticate()
return loginOutput
},
[rwClientPromise, reauthenticate]
)
const logOut = useCallback(
async (options?: any) => {
const client = await rwClientPromise
await client.logout(options)
setAuthProviderState({
userMetadata: null,
currentUser: null,
isAuthenticated: false,
hasError: false,
error: undefined,
loading: false,
})
},
[rwClientPromise]
)
const signUp = useCallback(
async (options?: any) => {
const client = await rwClientPromise
const signupOutput = await client.signup(options)
await reauthenticate()
return signupOutput
},
[rwClientPromise, reauthenticate]
)
const forgotPassword = useCallback(
async (username: string) => {
const client = await rwClientPromise
if (client.forgotPassword) {
return await client.forgotPassword(username)
} else {
throw new Error(
`Auth client ${client.type} does not implement this function`
)
}
},
[rwClientPromise]
)
const resetPassword = useCallback(
async (options?: any) => {
const client = await rwClientPromise
if (client.resetPassword) {
return await client.resetPassword(options)
} else {
throw new Error(
`Auth client ${client.type} does not implement this function`
)
}
},
[rwClientPromise]
)
const validateResetToken = useCallback(
async (resetToken: string | null) => {
const client = await rwClientPromise
if (client.validateResetToken) {
return await client.validateResetToken(resetToken)
} else {
throw new Error(
`Auth client ${client.type} does not implement this function`
)
}
},
[rwClientPromise]
)
/** Whenever the rwClient is ready to go, restore auth and reauthenticate */
useEffect(() => {
if (rwClient && !hasRestoredState) {
setHasRestoredState(true)
const doRestoreState = async () => {
await rwClient.restoreAuthState?.()
reauthenticate()
}
doRestoreState()
}
}, [rwClient, reauthenticate, hasRestoredState])
const { client, type, children } = props
return (
<AuthContext.Provider
value={{
...authProviderState,
logIn,
logOut,
signUp,
getToken,
getCurrentUser,
hasRole,
reauthenticate,
forgotPassword,
resetPassword,
validateResetToken,
client,
type: type as SupportedAuthTypes,
}}
>
{children}
<AuthUpdateListener rwClient={rwClient} reauthenticate={reauthenticate} />
</AuthContext.Provider>
)
}