Как создать пользовательские директивы для защиты моего API GraphQL? - PullRequest
0 голосов
/ 01 октября 2018

Я хочу использовать пользовательские директивы для защиты моего API GraphQL.В частности, для конкретных полей GraphQL я хочу проверить, есть ли у пользователей полномочия запрашивать эти поля, когда запрос попадает на мой сервер GraphQL.

Следующие ссылки представляют собой статьи, в которых приведены примеры достижения этой цели.

Однако оба примера достигают этого, сначала создав свою схему с помощью языка определения схемы GraphQL.(ниже приведен фрагмент репо для Link 2 ), демонстрирующий, как можно использовать пользовательские директивы для проверки, есть ли у пользователей полномочия для запроса определенных полей (например, «рейтинг»).

require('dotenv').config();
const express = require('express');
const graphqlHTTP = require('express-graphql');
const {
  makeExecutableSchema
} = require('graphql-tools');

const {directiveResolvers} = require('./directives');
const {allProductsBySupplier, addProduct, product, suppliers} = require('./resolvers');

require('./auth');

const app = express();

const port = 8080;
const typeDefs = `
  directive @isAuthenticated on QUERY | FIELD
  directive @hasScope(scope: [String]) on QUERY | FIELD
  type Product {
    id: ID!
    supplierId: ID!
    sku: String
    qty: Int
    price: Int
    parrot: String
    rating: Int @hasScope(scope: ["read:rating"])
  }
  type Supplier {
    id: ID!
    name: String!
  }
  input ProductInput {
    supplierId: ID!
    sku: String!
    qty: Int!
    price: Int!
    parrot: String!
    rating: Int!
  }
  type Query {
    allProductsBySupplier: [Product] @isAuthenticated
    product: Product @isAuthenticated
    suppliers: [Supplier]
  }
  type Mutation {
    addProduct(input: ProductInput!): Product @hasScope(scope: ["add:product"])
  }
`;

const resolvers = {
  Query: {
    allProductsBySupplier,
    product,
    suppliers
  },
  Mutation: {
    addProduct
  }
};

const schema = makeExecutableSchema({
  typeDefs,
  resolvers,
  directiveResolvers
});

app.use(
  '/graphql',
  graphqlHTTP({
    schema,
    graphiql: true
  })
);

app.listen(port);

console.log(`server running on localhost:${port}`);

Я создал свой API без использования языка определения схемы GraphQL, как показано ниже.Следующий фрагмент был извлечен из официальных документов graphql .

var express = require('express');
var graphqlHTTP = require('express-graphql');
var graphql = require('graphql');

// Maps id to User object
var fakeDatabase = {
  'a': {
    id: 'a',
    name: 'alice',
  },
  'b': {
    id: 'b',
    name: 'bob',
  },
};

// Define the User type
var userType = new graphql.GraphQLObjectType({
  name: 'User',
  fields: {
    id: { type: graphql.GraphQLString },
    name: { type: graphql.GraphQLString },
  }
});

// Define the Query type
var queryType = new graphql.GraphQLObjectType({
  name: 'Query',
  fields: {
    user: {
      type: userType,
      // `args` describes the arguments that the `user` query accepts
      args: {
        id: { type: graphql.GraphQLString }
      },
      resolve: function (_, {id}) {
        return fakeDatabase[id];
      }
    }
  }
});

var schema = new graphql.GraphQLSchema({query: queryType});

var app = express();
app.use('/graphql', graphqlHTTP({
  schema: schema,
  graphiql: true,
}));
app.listen(4000);
console.log('Running a GraphQL API server at localhost:4000/graphql');

Как создать пользовательские директивы, чтобы проверить, есть ли у пользователей полномочия запрашивать определенные поля, если я создалмоя схема без использования языка определения схемы GraphQL?

...