views:

104

answers:

4

I am currently building a Rails app, and trying to figure out the best way to authenticate that a user owns whatever data object they are trying to edit.

I already have an authentication system in place (restful-authentication), and I'm using a simple before_filter to make sure a user is logged in before they can reach certain areas of the website.

However, I'm not sure the best way to handle a user trying to edit a specific piece of data - for example lets say users on my site can own Books, and they can edit the properties of the book (title, author, pages, etc), but they should only be able to do this for Books that -they- own.

In my 'edit' method on the books controller I would have a find that only retrieved books owned by the current_user. However, if another user knew the id of the book, they could type in http://website.com/book/7/edit , and the controller would verify that they are logged in, then show the edit page for that book (seems to bypass the controller).

What is the best way to handle this? Is it more of a Rails convention routing issue that I don't understand (being able to go straight to the edit page), or should I be adding in a before_find, before_save, before_update, after_find etc callbacks to my model?

+1  A: 

this will give access to anyone who changes the value in the address bar

@book = Book.find(params[:id])

but if you go through the association of the logged on user rails (ActiveRecord) will automatically update the sql query

@book = current_user.books.find(params[:id])

of course this assumes that your books table has a user_id column

house9
+1  A: 

You may need an authorization plugin. I had some experience use this plugin a while back. This article also has an overview:

toby
+1  A: 

check out the following gems:

  • cancan
  • devise
  • authlogic

and don't miss Ryan's great railscasts on the above

ohho
I didn't realize this was something that would call for a plugin - thanks for the tips. I believe I'm going to go with the cancan plugin.
Zachary
I would advice that you go for authlogic. :)
Shripad K
+1  A: 

You might also take a look at Declarative Authorization

zetetic