Programming in Paradise

Sunday, January 08, 2006

Sanitizing Form Data

I love JJ because I give him something which works and he quickly pokes it so full of holes that it would sink if placed in water. The particular issue at hand is sanitizing incoming form data. Put simply, I wasn't doing it for Pecuniarius and now I am. The fix was actually quite simple. I created two methods in my application controller which handle the sanitizing:

def sanitize_params
sanitize_hash(@params)
end

def sanitize_hash(hash)
hash.each do |key, value|
if value.kind_of? Hash
sanitize_hash(value)
elsif value.kind_of? Array
hash[key] = value.collect {|x| sanitize(x)}
else
logger.info("Sanitizing #{key}")
hash[key] = sanitize(value)
logger.info("After sanitize: #{hash[key]}")
end
end
end
Then in any controller which has user input I added the following filter:
  before_filter :sanitize_params
Et, voila! The sanitize_params method calls the sanitize_hash method passing the paramters. The sanitize_hash method will then handle nested hashes, arrays or plain values. One minor addition which I might add in the future is the ability to omit certain parameters from sanitizing, but at the moment that isn't a necessity. Feedback is always welcome. If you are doing this in a different fashion then I'd love to hear about it.

P.S. Another good blog entry on handling form data this can be found in the Rails Diary.

0 Comments:

Post a Comment

Links to this post:

Create a Link

<< Home