graphiti icon indicating copy to clipboard operation
graphiti copied to clipboard

Integration with Pundit

Open ghn opened this issue 1 year ago • 2 comments
trafficstars

Hello,

I know this has partially been reported already https://github.com/graphiti-api/graphiti/issues/171 but I think what proposed @ribordy is kinda nice. I would even imagine one step further like

class DemoResource
  attribute :name, :string, readable: :readable?, writable: :writable?
  attribute :role :string, readable: :readable?, writable: :writable?

  def readable?(attr)
    policy(model_instance).permitted_read_attributes.include?(attr)
  end

  def writable?(attr)
    policy(model_instance).permitted_write_attributes.include?(attr)
  end
end

class DemoPolicy
  def index
    # some logic
  end

  def update
    # some logic
  end

  def permitted_read_attributes = %i[name role]

  def permitted_write_attributes
    if user.admin?
      %i[name role]
    else
      %i[name]
    end
  end
end

That way we can leverage Pundit for what they call "permitted_attributes" too and have the read+write permissions at the same place => in the policy file, where I think it belongs.

Would that make sense?

ghn avatar Oct 08 '24 13:10 ghn

@ghn I think this would be great. Do you have time to work up a PR?

jkeen avatar Mar 18 '25 18:03 jkeen

While I was digging the code to add the feature, I found out that it's already there 😂 only the documentation is not up to date. We can do

class DemoResource
  attribute :name, :string, readable: :readable?
  attribute :role :string, readable: :readable?

  def readable?(object, attr)
    DemoPolicy.new(context.current_user, object).permitted_read_attributes.include?(attr.to_sym)
  end
end

readable? accepts zero, one or two arguments, see: https://github.com/graphiti-api/graphiti/blob/main/lib/graphiti/util/serializer_attributes.rb#L85

However the writable method does not accept any argument yet :(

ghn avatar Apr 13 '25 09:04 ghn