Auditing for attr_accessible
By now, you all know that you need to use attr_accessible to protect your application from having any old Active Record attribute changed by a malicious user. I find myself, in the course of consulting, looking at a great number of existing applications, and I've grown tired of having to open up every model and look. So, let's be a bit smart: here's a rake task that you can drop in any existing application to do the audit for you:
[sourcecode language='ruby']
namespace :utility do
desc 'Find models that are not using attr_accessible'
task :audit_attr_accessible => :environment do
all_models = Dir.glob(
File.join(Rails.root, 'app', 'models', '*.rb')
).map{|path| path[/.+\/(.+).rb/,1] }
ar_models = all_models.select{|m|
m.classify.constantize < ActiveRecord::Base}
ar_models.each do |model|
model_class = model.classify.constantize
if model_class.send("attr_accessible").empty? &&
model_class.send("attr_protected").empty?
puts model_class.class_name +
" allows unprotected mass assignment"
end
end
end
end
[/sourcecode]
(Hat tip Matt for the snippet to find all models).
[sourcecode language='ruby']
namespace :utility do
desc 'Find models that are not using attr_accessible'
task :audit_attr_accessible => :environment do
all_models = Dir.glob(
File.join(Rails.root, 'app', 'models', '*.rb')
).map{|path| path[/.+\/(.+).rb/,1] }
ar_models = all_models.select{|m|
m.classify.constantize < ActiveRecord::Base}
ar_models.each do |model|
model_class = model.classify.constantize
if model_class.send("attr_accessible").empty? &&
model_class.send("attr_protected").empty?
puts model_class.class_name +
" allows unprotected mass assignment"
end
end
end
end
[/sourcecode]
(Hat tip Matt for the snippet to find all models).