Rails, Cancancan, Devise, author

I'm working on a Rails app with cancancan and devise. I have a controller that receives three different petitions for any action contained on it (It's a RESTful-based controller) depending on the models the HTTP method is intended to work with. This controller manages Product model, OrderProducts model and BusinessProducts model. I handle this using an if statement on each RESTFUL method as show below. My question is, is there a way to define authorizations for each model inside every action for this ProductController using Cancancan?

As you know, the ability class allows me to authorize the product model, however, as we have more cases involved in the same controller, we cannot handle all them with the same rules defined in ability class for product model. Thanks a lot in advance for your help!!!

params[:order_product] and params[:business_products] are flags which are defined in config/routes.rb

products_controller.rb

class ProductsController < ApplicationController

load_and_authorize_resource

def index
if params[:order_product]
  @order = Order.find(params[:order_id])
  @order.products.reload
  render json: @order.products.with_price

elsif params[:business_product]
  @business = Business.find(params[:business_id])
  @business.products.reload
  render json: @business.products.with_price
else
  render json: @products
end
end

Upvotes: 0

Views: 167

Answers (1)

Sean Huber
Sean Huber

Reputation: 3985

If you want to use conditional authorization in a controller action, I would advise doing it manually instead of using load_and_authorize_resource. For example:

class ProductsController < ApplicationController

  def index
    if params[:order_product]
      @order = Order.find(params[:order_id])
      authorize! :read, @order
      @order.products.reload
      render json: @order.products.with_price
    elsif params[:business_product]
      @business = Business.find(params[:business_id])
      authorize! :read, @business
      @business.products.reload
      render json: @business.products.with_price
    else
      authorize! :read, Product
      render json: @products
    end
  end

end

reference: https://github.com/ryanb/cancan/wiki/authorizing-controller-actions

Upvotes: 2

Related Questions