Created
May 22, 2024 21:22
-
-
Save rmosolgo/b6551342e46afc69a6b4dd295694406d to your computer and use it in GitHub Desktop.
GraphQL-Pro CanCan integration example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require "bundler/inline" | |
gemfile do | |
gem "graphql", "2.3.4" | |
gem "graphql-pro", "1.27.5" | |
gem "cancancan", "3.5.0" | |
end | |
class Ability | |
include CanCan::Ability | |
def initialize(viewer) | |
can :check_balance, User do |user| | |
can_check_balance = user == viewer || viewer.superuser | |
puts "Can check_balance? #{can_check_balance} (#{user == viewer}, #{viewer.superuser})" | |
can_check_balance | |
end | |
end | |
end | |
User = Struct.new("User", :superuser, :account_balance) | |
class MySchema < GraphQL::Schema | |
class BaseField < GraphQL::Schema::Field | |
include GraphQL::Pro::CanCanIntegration::FieldIntegration | |
can_can_action(nil) # default to no auth | |
end | |
class BaseObject < GraphQL::Schema::Object | |
include GraphQL::Pro::CanCanIntegration::ObjectIntegration | |
field_class(BaseField) | |
can_can_action(nil) # default to no auth | |
end | |
class User < BaseObject | |
field :account_balance, Int, can_can_action: :check_balance | |
end | |
class Query < BaseObject | |
field :user, User | |
def user | |
::User.new(false, 100) | |
end | |
field :current_user, User | |
def current_user | |
context[:current_user] | |
end | |
end | |
query(Query) | |
end | |
query_str = "{ user { accountBalance } }" | |
pp MySchema.execute(query_str, context: { current_user: User.new(true, 0) }).to_h | |
# Can check_balance? true (false, true) | |
# {"data"=>{"user"=>{"accountBalance"=>100}}} | |
pp MySchema.execute(query_str, context: { current_user: User.new(false, 0) }).to_h | |
# Can check_balance? false (false, false) | |
# {"data"=>{"user"=>{"accountBalance"=>nil}}} | |
pp MySchema.execute("{ currentUser { accountBalance } }", context: { current_user: User.new(false, 55) }).to_h | |
# Can check_balance? true (true, false) | |
# {"data"=>{"currentUser"=>{"accountBalance"=>55}}} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment