palkan / action_policy-graphql

Action Policy integration for GraphQL
MIT License
152 stars 9 forks source link

verify_authorized #28

Closed pdfrod closed 3 years ago

pdfrod commented 4 years ago

Is there any equivalent to verify_authorized? This is a must to helps us not forget to verify authorization.

palkan commented 4 years ago

We haven't added a built-in support for that to the gem but used the following in a couple of projects (described in this RailsConf talk:

module ResolverCallbacks
  def self.included(base)
    base.include ActiveSupport::Callbacks
    base.define_callbacks :resolve

    base.resolve_method :resolve_with_callbacks
    base.extend ClassMethods
  end

  def resolve_with_callbacks(**kwargs)
    run_callbacks(:resolve) { resolve(**kwargs) }
  end

  module ClassMethods
    def before_resolve(*args, &block)
      set_callback :resolve, :before, *args, &block
    end

    def after_resolve(*args, &block)
      set_callback :resolve, :after, *args, &block
    end
  end
end
class BaseMutation < GraphQL::Schema::RelayClassicMutation
   include ResolverCallbacks

   after_resolve do
    raise "Unauthorized mutation" unless @authorization_performed
  end

  def authorize!(*)
    @authorization_performed = true
    super
  end

  # Call this method if you don't need to authorize the mutation
  def skip_authorization!
    @authorization_performed = true
  end
end
palkan commented 3 years ago

Closed by https://github.com/palkan/action_policy/commit/ebe90aa8141c98ca5e1547d46679cafafb65f099