Browse Source

jwt two resolvers in module

Ivan Asmer 4 years ago
parent
commit
f598404af6
2 changed files with 26 additions and 31 deletions
  1. 0 31
      index.js
  2. 26 0
      jwt.js

+ 0 - 31
index.js

@@ -253,9 +253,6 @@ function mmExpandSchema(gqlSchema){
     schema = mmExpandSchema(schema)
     console.log(printSchema(schema))
 
-    //console.log(schema._typeMap.User.__proto__)
-    //console.log(schema._typeMap.OrderInput.getFields())
-
     var app = express();
     app.use(express.static('public'));
 
@@ -312,34 +309,6 @@ function mmExpandSchema(gqlSchema){
 
     app.use('/graphql', express_graphql(jwtGQL({anonSchema, anonResolvers, schema, createContext: getModels, graphiql: true, secret: jwtSecret})))
 
-    //app.use('/graphql', express_graphql(async (req, res, gql) => { 
-        //const authorization = req.headers.authorization 
-        
-        //if (authorization && authorization.startsWith('Bearer ')){
-            //console.log('token provided')
-            //const token = authorization.substr("Bearer ".length)
-            //const decoded = jwt.verify(token, jwtSecret)
-            //if (decoded){
-                //console.log('token verified', decoded)
-
-                //let slicedModels  = await getModels(decoded.sub.id)
-
-                //return {
-                    //schema: schema,
-                    //rootValue: {},
-                    //graphiql: true, 
-                    //context: {jwt: decoded.sub,
-                              //models: slicedModels}
-                //}
-            //}
-        //}
-        //return {
-            //schema: anonSchema,
-            //rootValue: anonResolvers,
-            //graphiql: true, 
-        //}
-    //}))
-
     app.listen(4000, () => console.log('Express GraphQL Server Now Running On localhost:4000/graphql'));
 })()
 

+ 26 - 0
jwt.js

@@ -0,0 +1,26 @@
+const jwt         = require('jsonwebtoken')
+module.exports = ({anonSchema, anonResolvers={}, schema, rootValue={},secret, createContext, graphiql=true}) => 
+    async (req, res, gql) => { 
+        const authorization = req.headers.authorization 
+        
+        if (authorization && authorization.startsWith('Bearer ')){
+            const token = authorization.substr("Bearer ".length)
+            const decoded = jwt.verify(token, secret)
+            if (decoded){
+                let context  = await createContext(decoded.sub)
+                context.jwt  = decoded.sub
+
+                return {
+                    schema,
+                    rootValue, 
+                    graphiql,
+                    context
+                }
+            }
+        }
+        return {
+            schema: anonSchema,
+            rootValue: anonResolvers,
+            graphiql, 
+        }
+    }