Middleware authorization

Asked by At

I'm setting up authorization in the server, and the code should deliver token to Middleware but, context.user should return the value of token but it should return null. How to fix it?

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 Answers