Sanitizing User Input with Ruby on Rails
- by phreakre
I'm writing a very simple CRUD app that takes user stories and stores them into a database so another fellow coder can organize them for a project we're both working on. However, I have come across a problem with sanitizing user input before it is saved into the database. I cannot call the sanitize() function from within the Story model to strip out all of the html/scripting. It requires me to do the following:
def sanitize_inputs
self.name = ActionController::Base.helpers.sanitize(self.name) unless self.name.nil?
self.story = ActionController::Base.helpers.sanitize(self.story) unless self.story.nil?
end
I want to validate that the user input has been sanitized and I am unsure of two things:
1) When should the user input validation take place? Before the data is saved is pretty obvious, I think, however, should I be processing this stuff in the Controller, before validation, or some other non-obvious area before I validate that the user input has no scripting/html tags?
2) Writing a unit test for this model, how would I verify that the scripting/html is removed besides comparing "This is a malicious code example" to the sanitize(example) output?
Thanks in advance.