Skip to content

Instantly share code, notes, and snippets.

@wagenet
Created May 6, 2021 21:25
Show Gist options
  • Save wagenet/35fccb574922e97a91d9807514cf4d8c to your computer and use it in GitHub Desktop.
Save wagenet/35fccb574922e97a91d9807514cf4d8c to your computer and use it in GitHub Desktop.
Graphiti + Pundit
# frozen_string_literal: true
class ApplicationPolicy
attr_reader :user, :record
def initialize(user, record)
@user = user
@record = record
end
# We limit this with the scope instead
# def index?
# false
# end
# You can show all records that are in your policy scope
def show?
Pundit.policy_scope!(user, record.class).include?(record)
end
def create?
false
end
def new?
create?
end
def update?
false
end
def edit?
update?
end
def destroy?
false
end
class Scope
attr_reader :user, :scope
def initialize(user, scope)
@user = user
@scope = scope
end
# This method is called by Pundit. If there is a User, it calls
# `resolve_for_user` otherwise it calls `resolve_for_public`
def resolve
user ? resolve_for_user(user).or(resolve_for_public) : resolve_for_public
end
def resolve_for_public
scope.none
end
# This method should be overridden by subclasses of scope, to
# resolve the scope for a particular user. The `resolve` method
# already handles the unauthenticated case and the Vandal case, so
# implementations of `resolve_for_user` only need to handle the
# authenticated User case.
def resolve_for_user(_user)
raise "not implemented resolve_scope in #{self.class}"
end
end
end
# frozen_string_literal: true
class ApplicationResource < Graphiti::Resource
include Pundit
before_save(only: :create) { |record| authorize(record, :create?) }
before_save(only: :update) do |record|
# This can get called for associations that don't make changes, so we also need to check for changes
# https://github.com/graphiti-api/graphiti/issues/165
authorize(record, :update?) if record.changed?
end
before_destroy { |record| authorize(record, :destroy?) }
def base_scope
policy_scope(model)
end
private
def current_user
context.try(:current_user)
end
end
@victormatheusdev
Copy link

how about show action on resource?

@wagenet
Copy link
Author

wagenet commented Jun 28, 2021

@victormaths I'm not sure what you're asking, can you elaborate?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment