/
useRedwoodAuthContext.ts
60 lines (53 loc) · 1.49 KB
/
useRedwoodAuthContext.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
import { Plugin } from 'graphql-yoga'
import {
AuthContextPayload,
getAuthenticationContext,
Decoder,
} from '@redwoodjs/api'
// import { AuthenticationError } from '../errors'
import {
RedwoodGraphQLContext,
GraphQLHandlerOptions,
} from '../functions/types'
/**
* Envelop plugin for injecting the current user into the GraphQL Context,
* based on custom getCurrentUser function.
*/
export const useRedwoodAuthContext = (
getCurrentUser: GraphQLHandlerOptions['getCurrentUser'],
authDecoder?: Decoder | Decoder[]
): Plugin<RedwoodGraphQLContext> => {
return {
async onContextBuilding({ context, extendContext }) {
const { requestContext } = context
let authContext: AuthContextPayload | undefined = undefined
try {
authContext = await getAuthenticationContext({
authDecoder,
event: context.event,
context: requestContext,
})
} catch (error: any) {
throw new Error(
`Exception in getAuthenticationContext: ${error.message}`
)
}
try {
if (authContext) {
const currentUser = getCurrentUser
? await getCurrentUser(
authContext[0],
authContext[1],
authContext[2]
)
: null
if (currentUser) {
extendContext({ currentUser })
}
}
} catch (error: any) {
throw new Error(`Exception in getCurrentUser: ${error.message}`)
}
},
}
}