In the products controller we need to make sure that the products accessed belong to the client associated to the current user.
Here's a DRY approach to reach that goal:
class ProductsController < ActiveRecord::Base
before_filter :find_product, :only => [:show, :edit, :update, :destroy]
rescue_from SecurityError,
:with => Proc.new{|e| redirect_to(access_violation_url)}
...
...
private
def find_product
@product = Product.find_by_client(params[:id], current_client_id)
raise SecurityError.new if @product.nil?
end
Before the show, edit, update and destroy methods we are going to call the find_product method. This method will ensure that the product id being passed in belongs to the user who is logged in (by their client id).
If the product is not found, the find_by_client will set @product to nil.
If product.nil? we will raise a SecurityError. This is where the rescue_from class method comes in to play. It will catch that exception and redirect to the access_violation_url.
The access_violation_url is just a named route. In my case it is defined as:
map.access_violation '/security/access_violation',
:controller => "security",
:action => "access_violation"
I created a security controller to process and display the errors to the user. Now I don't have to create an error method/view for each controller class.
By the way, the rescue_from is a Rails 2.0 feature. So, you'll need to upgrade to use this very nice feature.

0 comments:
Post a Comment