jwt.js 1.0 KB

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