Reputation: 15258
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?
Upvotes: 0
Views: 377
Reputation: 434845
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
Upvotes: 3
Reputation: 6740
You can use regex to validate it's a valid url without the '<', '>' url. And HTML encode it where it applies.
Upvotes: 0
Reputation: 230521
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
Upvotes: 1