I sat up a GraphQL subscription server and I realized I need to authenticate a user from getting the subscription. I read official document about Subscription, but It doesn’t mention about a specific way of verifying a token. Here is my code.
const { ApolloServer } = require('apollo-server');
const { resolvers, typeDefs } = require('./schema');
...
const getUser = token => {
if (token) {
try {
return jwt.verify(token, process.env.JWT_SECRET);
} catch (err) {
throw new Error('Session invalid');
}
}
};
const validateToken = authToken => {
// ... validate token and return a Promise, rejects in case of an error
};
const findUser = authToken => {
return tokenValidationResult => {
// ... finds user by auth token and return a Promise, rejects in case of an error
};
};
const server = new ApolloServer({
typeDefs,
resolvers,
context: async ({ req }) => {
const token = req.headers.authorization;
const user = getUser(token);
return { models, user };
},
subscriptions: {
onConnect: (connectionParams, webSocket) => {
if (connectionParams.authToken) {
return validateToken(connectionParams.authToken)
.then(findUser(connectionParams.authToken))
.then(user => {
return {
currentUser: user,
};
});
}
throw new Error('Missing auth token!');
},
},
});
...
My question is how to implement validateToken and findUser correctly? I tried code like getUser in findUser, but I am not sure this is the right way. What kind of aproach I need to take?