Reputation: 600
Setup:
From user.rb:
acts_as_user :roles => [ :guest, :user, :entity_admin, :admin, :super_admin ]
Those are stored in a roles_mask field in the user table (values map to 1, 2, 4, 8, 16).
On the Admin and Super_admin levels, things work fine, but it's defined as wide open, so that's expected:
manage[:all]
On the user level, it's restricted to items that the user owns:
# app/abilities/users.rb
Canard::Abilities.for(:user) do
can [:read], :all
can [:manage], Collection do |collection|
collection.try(:user) == @user
end
can [:manage], Item, :collection => { user_id: user.id }
can [:manage], Wishlist do |wishlist|
wishlist.try(:user) == @user
end
can [:manage], WishlistItem do |wi|
wi.try(:user) == @user
end
end
I've also tried the simpler declaration:
can [:manage], Collection, user_id: @user.id
to no avail.
In the controllers, things are loaded and authorized accordingly:
# app/controllers/collections_controller.rb:6
load_and_authorize_resource :collection, except: [:index, :show, :create]
# app/controllers/items_controller.rb:6-7
load_and_authorize_resource :collection
load_and_authorize_resource :item, through: :collection
#app/controllers/collections_controller Finder method from before_action
private
def set_collection
@collection = @user.collections.friendly.find(params[:id]).decorate
end
So I can create a collection, and in console it belongs to the correct user. However, I get a CanCan error when I try to do any edits to it ("You are not authorized to access this page."). Adding an item fails silently.
I'm sure this is user error on my part, but I can't figure it out for the life of me.
Upvotes: 2
Views: 221
Reputation: 504
It would appear that the object being authorized with CanCanCan has been decorated. You can overload can?
and authorize!
in ability.rb with the following:
def can?(action, subject, *extra_args)
subject_arg = subject.is_a?(Draper::Decorator) ? subject.model : subject
super(action, subject_arg, *extra_args)
end
def authorize!(action, subject, *extra_args)
subject_arg = subject.is_a?(Draper::Decorator) ? subject.model : subject
super(action, subject_arg, *extra_args)
end
This will handle any occurrences of passing a decorated object into an ability check.
Upvotes: 2