Global context - of course.
Ok, so here is the code if you want to put something into your context (like auth accessToken) and then update Netlify Identity userMetadata:
- In graphql, import
getAuthenticationContext
from dist api - Add custom context function to set
authContext
// api/src/functions/graphql.js
import {
createGraphQLHandler,
makeMergedSchema,
makeServices,
} from '@redwoodjs/api'
import { getAuthenticationContext } from '@redwoodjs/api/dist/auth'
import schemas from 'src/graphql/**/*.{js,ts}'
import services from 'src/services/**/*.{js,ts}'
import { getCurrentUser } from 'src/lib/auth'
import { db } from 'src/lib/db'
export const handler = createGraphQLHandler({
context: async ({ event, context }) => {
const authContext = await getAuthenticationContext({ event, context })
return authContext
},
getCurrentUser,
schema: makeMergedSchema({
schemas,
services: makeServices({ services }),
}),
db,
})
- In your service,
context
is global so can get the accessToken ascontext[1].token
export const updateUserMetadata = async ({ input }) => {
requireAuth()
const { body } = await got.put(
'https://YOUR_APP.netlify.app/.netlify/identity/user',
{
responseType: 'json',
json: {
data: {
...input,
},
},
headers: {
authorization: `Bearer ${context[1].token}`,
},
}
)
return (context.currentUser.user_metadata = body.user_metadata)
}
- in your getCurrentUser, since you have updated the user metadata but the decoded token is still the old (it has not refreshed even though Netlify has new data)
export const getCurrentUser = async (decoded) => {
return (
context.currentUser || { ...decoded, roles: parseJWT({ decoded }).roles }
)
}
Might need to refresh token from web side that can access client using
getToken: async () => {
const user = await client.currentUser()
return user?.jwt() || null
},
?