Search code examples
ruby-on-rails-4pundit

Rails Pundit Authorization not performed


I'm getting an "Pundit::PolicyScopingNotPerformedError" when calling a GET request to the show method of this controller. Any help appreciated.

Controller:

class DashboardsController < ApplicationController
  before_action :authorize_dashboard_for_customer, only: :show
  after_action :verify_authorized, except: :index
  after_action :verify_policy_scoped, only: :show

  expose(:dashboards) {
    Customer.find(params[:customer_id]).dashboards
  }

  expose(:dashboard) {
    Dashboard.find(params[:id])
  }

  expose(:customer) {
    Customer.find(params[:customer_id])
  }

  def index
  end

  def show
  end



  private

  def authorize_dashboard_for_customer
    authorize dashboard, :show?
  end  
end

Here is the Pundit Policy:

class DashboardPolicy < ApplicationPolicy

  def index?
    show?
  end

  def show?
    customer = user.try(:customer)
    return false if customer.blank?

    @record.customers.present? && @record.customers.include?(customer) || user.role == 'admin'
  end
end

I've read other posts about this, but still not seeing what I'm doing wrong here. I'm still fuzzy on what resolving a policy scope is doing, but in this case I can see from debug statements that it's hitting the policy, so I'm not sure what the issue is.


Solution

  • In your controller you're checking to make sure the policy scope is called with after_action :verify_policy_scoped, only: :show but you aren't calling anything for the scope in your action.

    You can use Scopes to restrict the results based on the logged in users permissions. For instance an admin user on an index screen would likely see all the results, but a non-admin could maybe only see certain records. IMO you shouldn't need scopes on a show so you should be able to remove the verify_policy_scoped.