Strapi:GraphQL ctx.state.user在策略内部未定义

时间:2019-03-11 13:17:17

标签: javascript node.js graphql strapi

我尝试设置带有trapi和策略的GraphQL以限制用户访问。普通的API调用在ctx.state.user中为我们提供了用户信息,但是在使用GraphQL时,此对象在api策略中未定义。虽然我可以在api控制器中访问ctx.state.user

'use strict';

/**
 * `hasViewPermissions` policy.
 */

module.exports = async (ctx, next) => {
  console.log(ctx.state.user);// Undefined

  await next();
};

schema.graphql for api

module.exports = {
  resolver: {
      Query: {
          posts: {
              description: 'Return a list of posts',
              policy: [
                  'hasViewPermissions',
              ],
              resolver: 'Posts.find'
          },
      }
  },
};

Node Version: v11.6.0 Strapi: 3.0.0-alpha.24.1

谢谢

2 个答案:

答案 0 :(得分:0)

尝试为策略添加“ plugins.users-permissions.permissions”。

module.exports = {
  resolver: {
      Query: {
          posts: {
              description: 'Return a list of posts',
              policies: [
                  'plugins.users-permissions.permissions', <---
                  'hasViewPermissions',
              ],
              resolver: 'Posts.find'
          },
      }
  },
};

答案 1 :(得分:0)

试试你的控制器或左轮手枪:

if (!ctx.state && ctx.request && ctx.request.header && ctx.request.header.authorization) {
            const { id } = await strapi.plugins["users-permissions"].services.jwt.getToken(ctx);
            ctx.state.user = await strapi.plugins['users-permissions'].services.user.fetchAuthenticatedUser(id);
        }

检查 ctx 是否为 {context}

看: Strapi: GraphQL ctx.state is undefined