Skip to content

Instantly share code, notes, and snippets.

@pontusab
Last active August 22, 2018 07:40
Show Gist options
  • Save pontusab/7b3f97bfadd4fdf99f0db579a84d8a7d to your computer and use it in GitHub Desktop.
Save pontusab/7b3f97bfadd4fdf99f0db579a84d8a7d to your computer and use it in GitHub Desktop.
// Client
import { setContext } from 'apollo-link-context'
export default setContext(async (_, { headers }) => ({
headers: {
...headers,
authorization: `Bearer ${localStorage.getItem('token')}`,
},
}))
const { APP_SECRET } = process.env
export function getUser(req) {
const Authorization = req.headers.authorization || ''
if (Authorization) {
const token = Authorization.replace('Bearer ', '')
try {
// Get what you need from JWT (role etc) and pass to context
const { id } = jwt.verify(token, APP_SECRET) as {
id: string
}
return { id }
} catch {
throw new AuthError()
}
}
// No user authenticated
return null
}
currentUser: (root, args, ctx, info) => {
if (ctx.role !== 'admin') {
throw new Error("not admin");
}
return {
data: 'blah'
}
},
const server = new ApolloServer({
schema,
context: ({ req }) => ({
user: getUser(req), // Add user to context to use in resolvers
services,
db,
}),
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment