How do you use CanCan 2.0 to authorize deletion of a mongoid embedded document? #790

Open
cameronkendall opened this Issue Dec 9, 2012 · 2 comments

Comments

Projects
None yet
3 participants

I currently have a User collection, and within that collection there is a Friend embedded document. I want to setup authorization so only the users that are connected can delete a friend. This equates to deleting a Friend embedded document in the User document. I am currently getting a Mongoid DocumentNotFound error when I call the destroy action (and I'm not even able to reach the debugging Rails logger info output) because it looks like CanCan is trying to find the friend in the Friend collection which doesn't exist because it is a Mongoid embedded document in the User document.

class User
include Mongoid::Document
include Mongoid::Timestamps::Created
field :first_name, type: String
field :email, type: String
embeds_many :friends, cascade_callbacks: true
end

class Friend
include Mongoid::Document
include Mongoid::Timestamps::Created
field :friend_user_id, type: Moped::BSON::ObjectId
field :first_name, type: String
embedded_in :user
end

class Ability
include CanCan::Ability
def initialize(user)
if user
can [:edit, :update], :users, :id => user.id
can [:index, :create], :friends
can [:accept_friend, :destroy], :friends, :friend_user_id => user.id
end
end

class FriendsController < ApplicationController
load_and_authorize_resource
def destroy
Rails.logger.info "TEST" # I never get to here.
respond_to do |format|
format.html {}
end
end
end

rutte commented Dec 11, 2012

You are not using the classs in your ability initialize method.
It should be:
class Ability
include CanCan::Ability
def initialize(user)
if user
can [:edit, :update], User, :id => user._id
can [:index, :create], Friend
can [:accept_friend, :destroy], Friend, :friend_user_id => user._id
end
end

Not sure if the ._id is needed, maybe .id works too.

xhoy commented Apr 10, 2014

Dear submitter, Since cancan/raynB hasn't been active for more than 6 months and no body else then ryam himself has commit permissions the cancan project is on a stand still.
Since cancan has several issues including missing support for rails 4 cancan is moving forward to cancancan. More details on: #994

If your feel that your pull request or bug is still applicable (and hasn't been merged in to cancan) it would be really appreciated if you would resubmit it to cancancan (https://github.com/cancancommunity/cancancan)

We hope to see you on the other side!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment