如何对graphql解析器实施防护

时间:2019-05-11 05:59:29

标签: javascript node.js reactjs express graphql

我是graphql的新手,正在尝试将身份验证/授权系统集成到我的项目中。我在Medium上找到了一个示例,但是我不了解警卫如何与解析器进行通信。如果有人知道,我将不胜感激。

import { ApolloServer } from 'apollo-server';
import gql from 'graphql-tag';
import { tradeTokenForUser } from './auth-helpers';

const HEADER_NAME = 'authorization';

const typeDefs = gql`
  type Query {
     me: User
     serverTime: String
  }
  type User {
     id: ID!
     username: String!
  }
`;

const resolvers = {
   Query: {
      me: authenticated((root, args, context) => context.currentUser), 
      serverTime: () => new Date(),
   },
   User: {
      id: user => user._id,
      username: user => user.username,
   },
};

const server = new ApolloServer({
   typeDefs,
   resolvers,
   context: async ({ req }) => {
      let authToken = null;
      let currentUser = null;

       try {
          authToken = req.headers[HEADER_NAME];

          if (authToken) {
               currentUser = await tradeTokenForUser(authToken);
          }
       } catch (e) {
          console.warn(`Unable to authenticate using auth token: ${authToken}`);
       }

      return {
          authToken,
          currentUser,
      };
   },
});

server.listen().then(({ url }) => {
  console.log(`  Server ready at ${url}`);
});
export const authenticated = next => (root, args, context, info) => {
  if (!context.currentUser) {
      throw new Error(`Unauthenticated!`);
  }

  return next(root, args, context, info);
};

我不明白“下一个”参数的作用,为什么当调用此防护措施时作为参数必须返回一个值?

1 个答案:

答案 0 :(得分:0)

authenticated是使代码DRY的高阶函数。 next是用作谓语的回调。

这是一种DRYer书写方式:

...
me: (root, args, context) => {
  if (!context.currentUser) {
      throw new Error(`Unauthenticated!`);
  }

  return context.currentUser;
)
...