jwt.js 886 B

1234567891011121314151617181920212223242526
  1. const jwt = require('jsonwebtoken')
  2. module.exports = ({anonSchema, anonResolvers={}, schema, rootValue={},secret, createContext, graphiql=true}) =>
  3. async (req, res, gql) => {
  4. const authorization = req.headers.authorization
  5. if (authorization && authorization.startsWith('Bearer ')){
  6. const token = authorization.substr("Bearer ".length)
  7. const decoded = jwt.verify(token, secret)
  8. if (decoded){
  9. let context = await createContext(decoded.sub)
  10. context.jwt = decoded.sub
  11. return {
  12. schema,
  13. rootValue,
  14. graphiql,
  15. context
  16. }
  17. }
  18. }
  19. return {
  20. schema: anonSchema,
  21. rootValue: anonResolvers,
  22. graphiql,
  23. }
  24. }