Question

I am using Ruby on Rails 3.1.0 and I would like to know what is a common practice to prevent to store "malicious" values in the database.

For example, I have a database table column means to store URLs. A user, passing the validation (just a length check), can submit a URL like http://<script>alert('hello!');</script>. I would like to do not permit to store links like the above... how can I make that?

Was it helpful?

Solution

The proper thing to do is use URI to parse the supposed URL and then check each component:

validate :url_check

def url_check
    u = URI.parse(self.url)
    # check u.scheme, u.userinfo, etc. and  call errors.add(:url, '...')
    # if something is invalid.
rescue URI::InvalidURIError
    errors.add(:url, 'You are being naughty.')
end

OTHER TIPS

While those links are in the database, they do no harm. Problems might occur when you try to render them. Rails does a good job in escaping most things that you output (I didn't dare to say "everything", 'cause I don't know for sure).

You can be extra sure and escape a string yourself:

CGI.escape your_link_url

Link: CGI.escape

You can use regex to validate it's a valid url without the '<', '>' url. And HTML encode it where it applies.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top