jwt.js 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849
  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. jwtGQLAnon: ({schema, rootValue={},secret, createContext, graphiql=true, anonJwtSub={id: "anon"}}) =>
  31. async (req, res, gql) => {
  32. let decoded = jwtCheck(req, secret) || {sub: anonJwtSub}
  33. let context = await createContext(decoded.sub)
  34. context.jwt = decoded.sub
  35. return {
  36. schema,
  37. rootValue,
  38. graphiql,
  39. context
  40. };
  41. },
  42. jwtCheck,
  43. }