Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if current_user is the owner of a resource and allow edit/delete actions

Example:

User A (id=10) has created a photo resource

photo: (id: 1 user_id = 10, url: "http://...")

Now, if User B (id=20) go to this url: /photos/1/edit it can edit photo of user A!!!

Rails+Devise provides something for this by default? It seems it's a very common issue

I just need to allow that any user can edit/delete ONLY resource it has created (where current_user == resource.user)

Using: Rails 4, Devise

Update:

I think CanCan it's something too advanced. I don't need roles or restrict some actions to certain users

like image 640
sparkle Avatar asked Jul 11 '13 13:07

sparkle


2 Answers

In your PhotosController:

before_filter :require_permission, only: :edit

def require_permission
  if current_user != Photo.find(params[:id]).user
    redirect_to root_path
    #Or do something else here
  end
end
like image 95
Erez Rabih Avatar answered Oct 22 '22 01:10

Erez Rabih


You can make use of Rails' associations and write it like this:

def edit
  @photo = current_user.photos.find(params[:id])

  # ... do everything else
end

This will only find a record when the photo with the supplied ID belongs to the current user. If it doesn't, Rails will raise a ActiveRecord::RecordNotFound exception.

Of course, I'm assuming the current_user method is available and your User model contains the statement has_many :photos.

like image 41
Daniel Pietzsch Avatar answered Oct 22 '22 01:10

Daniel Pietzsch