Max
Max

Reputation: 15955

How to stop a user form adding forms to a field?

I have a form that allows a user to update their profile information, but I would like to prevent some information from being changed. I also would like to keep my controller code very simple. In the update action of my Users Controller, I have the following code:

def update
  @user = Users.find params[:id]

  if @user.update_attributes(params[:user])
    flash[:notice] = 'Update successful.'
    redirect_to user_path(@user)
  else
    render :action => :edit
  end
end

This is very clean and simple, and I like that. What I don't like, however, is that a user can add a field to the form, with the same name as an attribute, and use it to modify forbidden attributes. Is there a simple way to do this, or do I need to devise a way to do this myself?

One method I was considering was to generate a hash value, using a hash-based message authentication code, of all the form's element names. This message access code would be a hidden value in the form. Then, once the form is submitted, I would calculate the message access code (MAC) again using the names of the parameter Hash's keys. If the two MACs are different, or if the first MAC is missing from the parameter Hash, I would throw an error. I would rather not spend the time implementing this if there was already and easy solution out there.

Thanks.

Upvotes: 2

Views: 64

Answers (2)

Luke Chadwick
Luke Chadwick

Reputation: 1727

Rails will prevent mass assignment if you use attr_protected :protectedcolumn (blacklist) or attr_accessible :safecolumn (whitelist) within your model. More information on this topic can be found in the Ruby on Rails Security Guide (Section 6.1)

Upvotes: 1

Nate
Nate

Reputation: 16898

On your model you can use attr_protected or attr_accessible to blacklist or whitelist attributes when being set via mass assignment (like when a form is submitted).

Upvotes: 1

Related Questions