Adam12344
Adam12344

Reputation: 1053

Protect actions with Devise in Rails

If I have a controller like the one below, what's the best way to protect my show action? The way it currently is setup any user can view the Note of another user with just the id.

class NotesController < ApplicationController
    before_action :authenticate_user!

    def index
        @notes = Note.where(user_id: current_user)
    end

    def show
        @note = Note.find(params[:id])
    end

    def new
        @note = current_user.notes.build
    end

end

Upvotes: 0

Views: 127

Answers (2)

BenKoshy
BenKoshy

Reputation: 35731

Authentication is one thing, but authorisation is quite another.Right now, (if i understand you correctly) if any user is logged in they can view someone else's credentials etc. you don't want that. that's understandable.

You will have to implement CanCanCan - or some such gem. It's not too difficult to read through - in about an 30-45 minutes you can role it out and set permissions to whatever you want.

https://github.com/CanCanCommunity/cancancan

http://railscasts.com/episodes/192-authorization-with-cancan

Please note that CanCan is obsolete and is no longer maintained.

If you need help with CanCanCan you can always repost, but it's really straightforward.

Upvotes: 0

Emu
Emu

Reputation: 5905

Method: 1

def show
   @note = Note.find(params[:id])
   redirect_to anywhere_you_want, notice: "can't see others note" if @note.user != current_user 
end

Method: 2

create a before_action like:

before_action :authenticate_note_user, only: [:show]
private
def authenticate_note_user
   @note = Note.find(params[:id])
   redirect_to anywhere_you_want, notice: "can't see others note" if @note.user != current_user
end

Upvotes: 3

Related Questions