Rails user authorization
I am currently building a Rails application and am trying to find the best way to authenticate that the user owns whatever data object they are trying to edit.
I already have a (restful-authentication) authentication system and I use a simple before_filter to make sure the user is logged in before they can reach certain areas of the website.
However, I'm not sure what the best way to handle a user trying to edit a certain piece of data, for example, is to say that users on my site can own books and they can edit the properties of a book (title, author, pages, etc.). but they only have to do it for books that are on their own.
In my "edit" method on the book controller, I would have a find that only fetched the books owned by current_user. However, if the other user knew the book ID, they could enter http://website.com/book/7/edit and the controller will check that they are signed in, then show the edit page for that book (it seems that it is not working).
What's the best way to handle this? Is this more of a Rails convention routing issue that I don't understand (can I go straight to the edit page), or do I need to add the previous before_find, before_save, before_update, after_find, etc. callbacks to my model.
a source to share
check out the following gems:
- cancan
- Are developing
- authlogic
and don't miss the Ryan great railscasts in the above
a source to share
this will give access to everyone who changes the value in the address bar
@book = Book.find(params[:id])
but if you go through the registered users association (ActiveRecord) the SQL query will be automatically refreshed
@book = current_user.books.find(params[:id])
of course this assumes your books table has a user_id column
a source to share
You may need an authorization plugin. I had some experience using this plugin a while ago. This article also has an overview:
a source to share
<%if current_user %>
<% if current_user.id == wishlist.user_id %>
<div id="text3"><%= link_to 'Edit', edit_wishlist_path(@wishlist) %></div><br />
<%end%>
<%end%>
Is this what you were hoping for?
a source to share