Last active
August 22, 2018 07:40
-
-
Save pontusab/7b3f97bfadd4fdf99f0db579a84d8a7d to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Client | |
import { setContext } from 'apollo-link-context' | |
export default setContext(async (_, { headers }) => ({ | |
headers: { | |
...headers, | |
authorization: `Bearer ${localStorage.getItem('token')}`, | |
}, | |
})) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
currentUser: (root, args, ctx, info) => { | |
if (ctx.role !== 'admin') { | |
throw new Error("not admin"); | |
} | |
return { | |
data: 'blah' | |
} | |
}, |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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