Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/65.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 是否可以将权威授权与graphql一起使用_Ruby On Rails_Graphql_Pundit - Fatal编程技术网

Ruby on rails 是否可以将权威授权与graphql一起使用

Ruby on rails 是否可以将权威授权与graphql一起使用,ruby-on-rails,graphql,pundit,Ruby On Rails,Graphql,Pundit,我想这样做: authorize record, :some_action 解析graphql字段或变异时(例如变异) 运行上述程序时,将显示此错误: NoMethodError-GraphQL::Relay::Variation无法定义“授权” 通常你写 include Pundit 在您的控制器中,但将其添加到GraphqlController不会有任何区别 如何使graphql了解pundit及其方法?之所以包含pundit不起作用,是因为当您包含模块时,会将包含添加到类中,autho

我想这样做:

authorize record, :some_action
解析graphql字段或变异时(例如变异)

运行上述程序时,将显示此错误: NoMethodError-GraphQL::Relay::Variation无法定义“授权”

通常你写

include Pundit
在您的控制器中,但将其添加到GraphqlController不会有任何区别


如何使graphql了解pundit及其方法?

之所以
包含pundit
不起作用,是因为当您包含模块时,会将包含添加到类中,
authorize
方法无论如何都不会起作用,因为它意味着要包含在控制器中,并基于此做出假设

但是手动初始化策略非常容易:

class ApplicationPolicy
  attr_reader :user, :record

  def initialize(user, record)
    @user = user
    @record = record
  end
end
您可以通过调用策略上的相应方法进行授权:

unless LinkPolicy.new(ctx[:current_user], @link).create?
  raise Pundit::NotAuthorizedError, "not allowed to create? this #{@link.inspect}"
end

我在这篇博文中找到了一个有点圆滑的解决方案

建议您在graphqlcontroller中添加include Pundit,然后将控制器作为上下文添加,如下所示:

context = {
  current_user: current_user,
  pundit: self
}
然后在解析字段和突变时,authorize方法如下所示:

ctx[:pundit].authorize @link, :create?

Pundit知道该用户是上下文中的当前用户,并抛出相应的错误。

使用更高版本的graphql ruby(我在撰写本文时使用的是1.9.17),您可以在变体中定义一个
authorized?
方法,并包括以下内容

Pundit.authorize context[:current_user], @link, :create?
有关权威
授权
类方法的详细信息,请参阅

有关graphql ruby的
authorized?
方法的详细信息,请参阅

Pundit.authorize context[:current_user], @link, :create?