Search code examples
ruby-on-railsactiverecorddeviseruby-on-rails-4

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


Solution

  • 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