Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Example of GraphQL::Pro pundit_integration with node field
require "bundler/inline"
gemfile do
gem "pundit", "2.1.0"
gem "graphql", "1.12.5"
source "https://gems.graphql.pro" do
gem "graphql-pro", "1.17.6"
end
end
class Schema < GraphQL::Schema
class BaseObject < GraphQL::Schema::Object
include GraphQL::Pro::PunditIntegration::ObjectIntegration
end
class UserPolicy
def initialize(user, object)
@user = user
@object = object
end
# A user object can only be viewed if the current user
# _is_ that same user
def view?
@user == @object[:handle]
end
end
class User < BaseObject
implements GraphQL::Types::Relay::Node
field :handle, String, null: false
pundit_role :view
# Since I'm using `Hash`es to represent users,
# I have to manually identify the `UserPolicy`.
pundit_policy_class UserPolicy
end
class Query < BaseObject
pundit_role nil
add_field(GraphQL::Types::Relay::NodeField)
end
query(Query)
orphan_types(User)
# The `id` _is_ the handle, it's not really an ID
def self.object_from_id(id, ctx)
{ handle: id, id: id }
end
# There's only one type in this schema, so assume everything is a User
def self.resolve_type(type, obj, ctx)
User
end
end
query_str = "{ node(id: \"matz\") { ... on User { handle } } }"
# No `current_user`, unauthorized:
pp Schema.execute(query_str).to_h
# {"data"=>{"node"=>nil}}
# Mismatched `current_user`, unauthorized:
pp Schema.execute(query_str, context: { current_user: "dhh" }).to_h
# {"data"=>{"node"=>nil}}
# Matching `current_user`, authorized:
pp Schema.execute(query_str, context: { current_user: "matz" }).to_h
# {"data"=>{"node"=>{"handle"=>"matz"}}}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment