module Pundit::Resource

Protected Instance Methods

authorize_create_or_update() click to toggle source
# File lib/pundit/resource.rb, line 51
def authorize_create_or_update
  action = _model.new_record? ? :create : :update
  not_authorized!(action) unless can :"#{action}?"
end
authorize_destroy() click to toggle source
# File lib/pundit/resource.rb, line 56
def authorize_destroy
  not_authorized! :destroy unless can :destroy?
end
can(method) click to toggle source
# File lib/pundit/resource.rb, line 36
def can(method)
  run_callbacks :policy_authorize do
    context[:policy_used]&.call
    policy.public_send(method)
  end
end
current_user() click to toggle source
# File lib/pundit/resource.rb, line 43
def current_user
  context&.[](:current_user)
end
policy() click to toggle source
# File lib/pundit/resource.rb, line 47
def policy
  Pundit.policy!(current_user, _model)
end
records_for(association_name, options={}) click to toggle source
# File lib/pundit/resource.rb, line 60
def records_for(association_name, options={})
  relationships = self.class._relationships.
    values.
    select { |r| r.relation_name(context: @context) == association_name }.
    uniq(&:class)

  unless relationships.count == 1
    raise "Can't infer relationship type for #{association_name}"
  end

  relationship = relationships.first

  case relationship
  when JSONAPI::Relationship::ToMany
    records = _model.public_send(association_name)
    policy_scope = Pundit.policy_scope!(
      context[:current_user],
      records
    )
    records.merge(policy_scope)
  when JSONAPI::Relationship::ToOne
    record = _model.public_send(association_name)

    # Don't rely on policy.show? being defined since it isn't used for
    # show actions directly and should always have the same behaviour.
    if record && show?(Pundit.policy!(context[:current_user], record), record.id)
      record
    else
      nil
    end
  end
end

Private Instance Methods

not_authorized!(action) click to toggle source
# File lib/pundit/resource.rb, line 95
def not_authorized!(action)
  options = { query: action, record: _model, policy: policy }
  raise Pundit::NotAuthorizedError, options
end
show?(policy, record_id) click to toggle source
# File lib/pundit/resource.rb, line 100
def show?(policy, record_id)
  policy.scope.where(id: record_id).exists?
end