Skip to content
This repository has been archived by the owner on Dec 12, 2021. It is now read-only.

cancan user performs create action despite unautherized #1022

Open
hshazly opened this issue Dec 19, 2014 · 1 comment
Open

cancan user performs create action despite unautherized #1022

hshazly opened this issue Dec 19, 2014 · 1 comment

Comments

@hshazly
Copy link

hshazly commented Dec 19, 2014

Hi there,

I'm using the cancan gem to control which action users can perform in a simple blogging app (the current logged in user can't delete other users posts)

In the ability file I'm defining 2 abilities:
can :destroy, Post, :user_id => user.id
can :create, Post, :user_id => user.id

The 1st ability works fine and not users can't delete other users posts, but the the create action doesn't work. I checked user.id and found that it returns the right user.id (that is the unauthorized user), I've also looked at the rails log and find the following transactions:
delete:
Parameters: {"authenticity_token"=>"8p+HAJwMiNVBSX37nmmy0I6Yxz9rx04LlHn8iEt1MQI=", "user_id"=>"2", "id"=>"35"}

User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."id" = 1 LIMIT 1
Post Load (0.3ms) SELECT "posts".* FROM "posts" WHERE "posts"."id" = ? LIMIT 1 [["id", "35"]]
Redirected to http://localhost:3000/

create:
Parameters: {"utf8"=>"✓", "authenticity_token"=>"8p+HAJwMiNVBSX37nmmy0I6Yxz9rx04LlHn8iEt1MQI=", "post"=>{"context"=>"aa"}, "commit"=>"Post", "user_id"=>"2"}

User Load (0.3ms) SELECT "users".* FROM "users" WHERE "users"."id" = 1 LIMIT 1
User Load (8.7ms) SELECT "users".* FROM "users" WHERE "users"."id" = 2 LIMIT 1
(0.1ms) begin transaction
CACHE (0.0ms) SELECT "users".* FROM "users" WHERE "users"."id" = 2 LIMIT 1
SQL (1.0ms) INSERT INTO "posts" ("context", "created_at", "updated_at", "user_id") VALUES (?, ?, ?, ?) ["context", "aa"], ["created_at", Fri, 19 Dec 2014 18:24:55 UTC +00:00], ["updated_at", Fri, 19 Dec 2014 18:24:55 UTC +00:00], ["user_id", 2] commit transaction
Redirected to http://localhost:3000/users/2

So does anyone have any idea what went wrong?

@hshazly
Copy link
Author

hshazly commented Dec 19, 2014

Ok I seemed to figured out why, In the docs it says that:
As of 1.4 these builder actions will initialize the resource with the attributes in the hash conditions.

So that's why it was adding the record.
I solved it by adding this line in the controller action create before saving the record:
authorize! :create, @post if current_user.id != params[:user_id]

Thanks

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant