Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails & Devise: How to authenticate specific user?

I'm using Devise for the first time with rails, and I'm having trouble with one thing: I used the provided authenticate_user! method in my user's controller to restrict access to pages like so: before_filter :authenticate_user!, :only => [:edit, :show, :update, :create, :destroy]

But this allows any signed in user to access any other users :edit action, which I want to restrict to only that user. How would I do that?

like image 578
Ankit Soni Avatar asked Feb 24 '23 11:02

Ankit Soni


2 Answers

In your edit method, you need to do a check to see if the user owns the record:

def edit
   @record = Record.find(params[:id])
   if @record.user == current_user
      @record.update_attributes(params[:record])
   else
      redirect_to root_path
   end
end
like image 69
Dex Avatar answered Mar 04 '23 07:03

Dex


You should look into Authorization such as CanCan. Or alternatively create a new method like so:

# Create an admin boolean column for your user table.

def authenticate_admin!
  authenticate_user! and current_user.admin?
end
like image 25
Zach Inglis Avatar answered Mar 04 '23 08:03

Zach Inglis