How do I prevent access to records that belong to a different user
How do I prevent accessing a specific set of records based on a session variable?
i.e. I have a table of items with a user_id key, how do I filter access to the items based on user_id. I don't want someone to be able to access /items/3/edit unless that item has their user id ag开发者_如何学编程ainst it (based on session var)
update: I am using the answer suggested by @fl00r with one change, using find_by_id() rather than find() as it returns a nil and can be handled quite nice:
@item = current_user.items.find_by_id([params[:id]]) || item_not_found
where item_not_found is handled in the application controller and just raises a routing error.
Restrict access by fetching items through your current_user
object (User
should :has_many => :items
)
# ItemsController
def edit
@item = current_user.items.find(params[:id])
...
end
where current_user
is kind of User.find(session[:user_id])
UPD
Useful Railscast: http://railscasts.com/episodes/178-seven-security-tips, TIP #5
You can check access in show/edit/update method:
def edit
@item = Item.find(params[:id])
restrict_access if @item.user_id != current_user.id
....
end
and add restrict_access method, for example in application_controller
def restrict_access
redirect_to root_path, :alert => "Access denied"
end
精彩评论