Coding Aloud – Restricting your users to edit other’s profile

restful_authentication plugin made its way to my projects as the “de-facto” authentication system in my Ruby on Rails projects like w2task or gistate.com. I would not insist on how to install it, as it is well explained on its home page at github.

What I want to show is that in particular instances we may not like that one user can access and modify other user’s profile. For example if I try to edit my profile, the URL will end in something like users/2/edit and if I would change it to users/1/edit then I am able to modify this user – most often an undesirable fact.

Here is my workaround:

app/controllers/users_controller.rb
  # ...
  def edit
    if params[:id].to_i == self.current_user.id
      @user = User.find(params[:id])
    else
      flash[:error] = "Not allowed!"
      redirect_back_or_default('/')
    end
  end
  # ...

That’s pretty much everything I need to change.

What is your preferred solution? Are you doing these tests into a – perhaps – before_filter?

One Response to “Coding Aloud – Restricting your users to edit other’s profile

Leave a Reply

Twitter Comments message