Skip to content
This repository has been archived by the owner on Jun 21, 2019. It is now read-only.

drewolson/params_cleaner

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

37 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Params Cleaner

Build Status

Usage

Params cleaner allows you to protect your Rails application from mass assignment attacks at the controller level. In any controller, simply mix in the ParamsCleaner module and specify which sub-keys are allowed for a given root key. Then, access your params using the clean_params method.

class PlayersController < ApplicationController
  include ParamsCleaner

  allowed_params :player => [:name, :email]

  def create
    @player = Player.new(clean_params[:player])

    if @player.save
      redirect_to player_path(@player)
    else
      render :new
    end
  end
end

The root keys specified will be checked on every level of the params hash, so you can easily protect deeply nested params hashes as well. For example, assume the following allowed_params declaration:

  allowed_params :player => [:name, :email]
                 :name => [:first, :last]

Now, assume the following params hash:

{
  :player => {
    :email => "[email protected]"
    :bad_key => "nefarious stuff",
    :name => {
      :first => "Drew",
      :last => "Olson",
      :nested_bad_key => "more nefarious stuff"
    }
  }
}

Here's what you'd see when calling the clean_params method:

clean_params[:player]
# => {:email => "[email protected]", :name => {:first => "Drew", :last => "Olson"}}

clean_params[:player][:name]
# => {:first => "Drew", :last => "Olson"}

ParamsCleaner also supports validating top-level params.

  allowed_params(
    :game_id,
    :player => [:name, :email]
  )

Now, assume the following params hash:

{
  :game_id => "id",
  :rating_id => "id",
  :player => {
    :email => "[email protected]"
    :bad_key => "nefarious stuff",
    :name => "Drew Olson"
  }
}

Here's what you'd see when calling the clean_params method:

clean_params
# => {:game_id => "id", :player => {:email => "[email protected]", :name => "Drew Olson"}}

You can even specify valid params for a given action:

  allowed_params_for :create, :player => [:name, :email]
  allowed_params_for :update, :player => [:name]

About

Don't use this, use strong parameters

Resources

License

Stars

Watchers

Forks

Packages

No packages published

Languages