中间件授权

时间:2019-05-13 13:34:58

标签: node.js mongodb graphql apollo-server

我正在服务器中设置授权,代码应将令牌传递到Middleware,但是context.user应该返回令牌的值,但应该返回null。 如何解决?

const apollo = new ApolloServer({
  typeDefs: schema,
  resolvers,
  playground: true,
  introspection: true,
  context: async ({ req, connection  }) => {
    if (connection) {
      return connection.context;
    } else {
      const token = req.headers.authorization || '';
      const language = req.headers.language || 'ar';
      const user = token ? await _getUser(token.replace("Bearer ","")) : null;

      return { user, language };
    }
  },
});

async function _getUser(token) {
  return new Promise((resolve, reject) => {
    User.findOne({token: token}, (err, user) => {
      resolve(user);
    }).populate('role').exec();
  })
}

0 个答案:

没有答案