2017-09-15 72 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並引發適當的錯誤。