2017-09-15 67 views
1

我想要做这样的事情:是否有可能使用权威人士授权与graphql

authorize record, :some_action 

在解决graphql场或突变(例如是突变)

module Mutations::CreateLink 
    CreateLink = GraphQL::Relay::Mutation.define do 
    name "CreateLink" 

    input_field :name, types.String 
    input_field :url, types.String 
    input_field :description, types.String 

    return_field :link, Types::LinkType 

    resolve -> (object, inputs, ctx) { 
     Rails::logger.ap ctx[:current_user] 
     Rails::logger.ap inputs[:name] 
     ctx[:current_user] 
     @link = Link.new(name: inputs[:name], url: inputs[:url], description: inputs[:description]) 
     authorize @link, :create? 
     response = { 
      link: @link 
     } 
    } 
    end 
end 

当以上运行此错误如下所示: NoMethodError - GraphQL :: Relay :: Mutation无法定义'授权'

通常情况下,您会编写

include Pundit 

在您的控制器中,但将其添加到GraphqlController没有任何区别。

我该如何让graphql知道pundit及其方法?

回答

1

include 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 
1

我发现这个博客帖子Graphql ruby and authorization with pundit有点华而不实的解决方案

它建议您在graphqlcontroller中添加包含Pundit,然后像上下文那样添加控制器:

context = { 
    current_user: current_user, 
    pundit: self 
} 

然后在authorize方法露出像这样在解决字段和突变:

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

权威人士知道用户如在上下文中使用current_user并引发适当的错误。