imjp
imjp

Reputation: 6695

Need help with custom authentication

Hey guys I created some custom authentication thanks to railscasts.com but I'm somewhat stuck as I need to restrict my users from editing other users' profiles.

Here's my authenticate_user and current_user methods:

private

def current_user
  @current_user ||= User.find_by_auth_token!(cookies[:auth_token]) if cookies[:auth_token]
end

def authenticate_user!
  if current_user.nil?
    redirect_to login_url, :alert => "You must first log in to access this page"
  end
end

Here's the before_filter in my UsersController:

before_filter :authenticate_user!, :only => [:edit, :update, :destroy]`

EDIT: Fixed it thanks to alock27.

I had to edit my users_controller and modify the edit action as follows:

@user = User.find(params[:id]    
redirect_to root_url unless current_user == @user    

Upvotes: 0

Views: 90

Answers (2)

Géal
Géal

Reputation: 1482

You don't have to provide an id for edit, update and destroy: you already have current_user. Instead of editing @user = User.find(id), edit current_user. Thus, your authentication functions ensure the user will only edit its own profile.

Upvotes: 1

awilkening
awilkening

Reputation: 1062

I think you want this:

Adding security on routes in Rails

you need to find the User by :id and check if current_user = @user

Upvotes: 1

Related Questions