Prev | Current Page 195 | Next

Brad Ediger

"Advanced Rails"

If
new attributes are added to the model, they will be blocked by default.
class Person < ActiveRecord::Base
attr_accessible :first_name, :last_name, :email
end
Application Issues | 133
Hidden form fields
Rails makes simple CRUD (create, read, update, delete) operations on a single model
object so easy that it is easy to ignore the security implications. Here??™s an example of
how not to process a form.
app/models/comment.rb
class Comment < ActiveRecord::Base
belongs_to :user
end
app/views/comment/new.rhtml
<% form_for :comment do |f| %>
<%= f.hidden_field :user_id %>
Comment: <%= f.text_field :comment %>
<% end %>
app/controllers/comments_controller.rb
class CommentsController < ApplicationController
def new
@comment = Comment.new :user_id => get_current_user( )
end
def create
# Danger Will Robinson!
@comment = Comment.create params[:comment]
end
end
This looks innocuous enough, but it has one problem: the hidden field is trusted! By
not verifying that the params[:comment][:user_id] value received in the create
method is sane, we have just allowed anyone to create a comment attached to an
arbitrary user.
Rails can only handle so much for you. The params object is CGI-unescaped and
parsed into nested hashes, but that??™s as much as the framework can do for you. Any
time you use the params object, realize that it can contain anything the user wants.


Pages:
183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207