public
Description: Keep the riff raff out. Mass Assignment protection at the controller level.
Homepage:
Clone URL: git://github.com/quamen/bouncer.git
Gareth Townsend (author)
Tue Apr 28 03:31:15 -0700 2009
commit  894af7b5ae6ab432ad5f791a19694aa3399085e4
tree    08ad896fc626e6389b70e87d594b4db116b18b17
parent  dadd9842aba7e42cd991aacee2b155dda9247ac3
name age message
file MIT-LICENSE Mon Apr 27 16:44:36 -0700 2009 First time lucky [Gareth Townsend]
file README.textile Loading commit data...
file Rakefile Mon Apr 27 16:44:36 -0700 2009 First time lucky [Gareth Townsend]
file init.rb Mon Apr 27 16:44:36 -0700 2009 First time lucky [Gareth Townsend]
file install.rb
directory lib/
directory tasks/
directory test/
file uninstall.rb
README.textile

Bouncer
===

Your rails app is like a club. Everyone wants in. Most users are fine, but every now and again someone wants to cause trouble.

You need a bouncer to keep the riff raff out.

Bouncer allows you to filter the params passed into your controller so that you can safely manage mass assignment at the controller level.

Example
===

Take a user model with the following attributes: login, password, admin.

admin is a boolean that signifies whether the user has the ability to perform admin tasks.

You probably use the following code throughout your application in controllers.


  @user = User.new(params[:user])

This code is problematic. Should a user decide to fiddle with your parameters and pass in admin=true you could have a bit of a problem on your hands.

You need a bouncer with a door list.


class UsersController < ApplicationController
  allow_assignment :user => [ :login, :password ]
end

Now you can safely use User.new(params[:user]) in your controller to mass assign only the attributes you’ve said are safe.

You should use allow_assignment in every controller within your application. By default bouncer will strip everything from the params hash that isn’t required by rails to operate.

Why Not Use attr_accessible?
======

attr_accessible is great. But it’s handled at the model level.

You might want to allow assignment of the admin attribute from an admin specific user interface.

You end up with code like this:


class AdminUsersController < ApplicationController

  ...
  @user = User.new(params[:user])
  @user.admin = params[:user][:admin]
  ...
  
end

The following is much nicer:


class UsersController < ApplicationController
  allow_assignment :user => [ :login, :password ]
end

class AdminUsersController < ApplicationController
  allow_assignment :user => [ :login, :password, :admin ]
end

Copyright © 2009 Gareth Townsend, released under the MIT license

Thanks to Josh Bassett for helping nut out self.request.env['rack.routing_args'].keys and other refactorings.