Sanitizing user input for a message box - ruby-on-rails

I am developing a crypto-related application and since those people who deal in crypto will always try some sort of scam or script kiddie "hack" I'd like to figure out the best way to clean up content in user-to-user chat boxes and comments fields.
I don't want any HTML/CSS/JS in there.
I want to leave email addresses, URLs, phone numbers and "normal" text untouched.
Right now I am doing a .gsub(/[^0-9a-zA-Z\#\;\:\-\_\,\.\ ]/i, '') before_save but it removes the newlines.
I tried adding .gsub(/[^0-9a-zA-Z\R\#\;\:\-\_\,\.\ ]/i, '') to make it leave newlines alone but it does not seem to work.
Would prefer not having to add any gems.

Rails has an excellent sanitizer built in, that I would recommend you use instead of trying to figure out your own regular expressions.
See:
http://api.rubyonrails.org/classes/ActionView/Helpers/SanitizeHelper.html
Before you render any user's input out the page wrap it in santize
<%= sanitize #comment.body %>
If you want to sanitize before saving to the database, you can include the helper into your controller
class MyController < ApplicationController
include ActionView::Helpers::SanitizeHelper
def create
content = sanitize(params[:content])
Thing.save(content: content)
end
end

Related

where in rails to put common text used by lots of files?

We have lots of templates that use a common paragraph of text (the description of our company services). The paragraph is currently duplicated among 10 different view templates.
Where should I create a variable like 'company_services_description' that I can use in all the different templates (to DRY it up).
Would defining it in application_controller.rb be the way to go?
Or perhaps would config/application.rb would be the right spot?
It depends how long the text it. I would suggest either storing the text in a partial and using it in your templates as follows:
<%= render "shared/company_services_description_partial" %>
or using an application helper method that you can call wherever you need it.
module ApplicationHelper
def company_services_description
"This is our company services description"
end
end

Embedded Ruby not being read when calling html_safe

I'm developing a simple app that teaches people english. The app is based on 5 modules of 34 classes each - 170 total. Each class has its own html page.
Since i dont want to create a view for each class, i scaffolded an Aula model ("class" in portuguese) and saved the html of each class in the model's DB, so i could use only the standard Show view paths to show the classes using their individual id's.
Controller code:
def show
#aula = set_aula
end
These HTML pages are being stored in the database as strings and then being outputted on the Show view using the html_safe method.
#show view code:
<%= #aula.aula.html_safe %>
#"aula" is the DB attribute with the html of each class
It rendered the HTML with no problems, and i got what i wanted. But since i'm creating a rails app, i decided to use embedded Ruby code like <%= link_to %> and <% image_tag %> mixed with the HTML of the classes to create links and show images, and the problem is that these links are being outputted as strings as well, just like any other line, instead of being read and executed as actual Ruby code.
I've been doing a lot of research, but so far I can't find exactly how to make the ERB code be read properly.
Maybe I need to save the HTML in the DB using another data type, or I need to use another method to render the HTML.
First, I'll answer your question, then make a suggestion that you think very carefully before using this approach.
The answer in the post https://stackoverflow.com/a/14351129/483133 shows how to render ERB directly from stored HTML text. Modifying this, here is some code you could use:
def show_html
html = #aula.aula
template = ERB.new(html)
template.result.html_safe
end
# Run this from your controller action, for example, with
def show
#aula = set_aula
end
# inside your view show.erb.html
<%= show_html %>
Warning
I would strongly recommend against finding a solution that allows Ruby code stored in the database to be run. If the pages are able to be written in any way by end users, rather than trusted software developers, then you have opened a huge security hole. Any Ruby code could be run on your server.
I would suggest you consider using a client-side rendering solution (such as Handlebars: http://handlebarsjs.com/ ), which allows for basic rendering of data dynamically in HTML, while not allowing code to be run on your server.

Rails: form generation based on conditions

I've got a form to build a Document. That form needs adjusting depending on what type of Document a user has chosen. At this point I've got a deferring kind of method in new.html.erb that goes like this:
<%= render 'form_'+#template.label.downcase.parameterize.underscore %>
Which works fine but it's kinda difficult to manage though because when new types of documents are added I need to create actual HTML files and upload them.
Is there a better way to manage this kind of form generation? A view with hundreds of if statements in it feels cumbersome too.
You can push it to document_helper or decorator like :
module DocumentHelper
def form_render
return 'form_#{type}'
end
end

Dividing text article to smaller parts with paging in Ruby on Rails

This time I've got problem with dividing text article into smaller parts. I don't need to figure out "automatic" algorithm based on words counting or something. All I need is something similar to function which is build-in Wordpress WYSIWYG editor (special breaking page tag).
I thought out only one solution so far. I don't want to divide specific article inside my database. I just want to place some tag inside article and divide it to array in show method.
Sample code:
#controller
#art = Article.find(:id)
if #art.value.contains?('<breaker>')
#parts = art.value.split('<breaker'>)
end
session[:current_part] = params[:current_part] ? params[:current_part] : #parts.first
...
render
#view
<%=h #parts[session[:current_part]] %>
How it sounds for you? It makes any sense? Cant wait for some advices.
It may be better to use an HTML comment so it does not affect the validation of the page.
In your Rails views, in the templates that show text before the breaker, you can split your content like what you have in the example code. I would perform this in a Rails helper module so it can be reused.
To view the full article, your helper method will return the full content if the parameter "more" is passed. The code may look something like this:
# controller
def show
#article = 'Before the break<!--more-->After the break'
end
# app/helpers/application_helper.rb
def show_more(article)
params[:more] ? article : article.split('<!--more-->').first
end
# show.html.erb
<%= show_more(#article) %>
It is generally good practice to keep the application logic in the model and helper files, and keep your controllers as simple as possible.

Any danger in calling flash messages html_safe?

I want a flash message that looks something like:
"That confirmation link is invalid or expired. Click here to have a new one generated."
Where "click here" is of course a link to another action in the app where a new confirmation link can be generated. Two drawbacks: One, since link_to isn't defined in the controller where the flash message is being set, I have to put the link html in myself. No big deal, but kind of messy.
Number two: In order for the link to actually display properly on the page I have to html_safe the flash display function in the view, so now it looks like (using Haml):
- flash.each do |name, message|
= content_tag :div, message.html_safe
This gives me pause. Everything else I html_safe has been HTML I've written myself in helpers and whatnot, but the contents of the flash hash are stored in a cookie client-side, and could conceivably be changed. I've thought through it, and I don't see how this could result in an XSS attack, but XSS isn't something I have a great understanding of anyway.
So, two questions:
1. Is there any danger in always html_safe-ing all flash contents like this?
2. The fact that this solution is so messy (breaking MVC by using HTML in the controller, always html_safe-ing all flash contents) make me think I'm going about this wrong. Is there a more elegant, Rails-ish way to do this?
I'm using Rails 3.0.0.beta3.
It depends on how sure you are where the contents for the message come from. If there is any possibility that any user could manipulate that message, then you should not do this!
I wouldn't do it either way. Because it could happen that you now know that every string is safe, but than you change one controller and add a message which could contain user input, than you have a possible vulnerability.
I would set any message html_safe when it is added to the flash and you know for sure it is safe.
For example
class SomeController < ApplicationController
def some_action
flash[:info] = 'Some safe text!'.html_safe
flash[:unsecure] = User.find(1).signature #//evil code
end
end
And in your view you can do it like this:
- flash.each do |name, message|
= content_tag :div, message
This way you make sure that if you add a new flash message that isn't safe, it would be made safe in the view by mistake.
In this case the flash[:info] message is printed as html_safe and flash[:unsecure] will be escaped, so the user evil javascript code will not be executed.
If you know there is no possibility that there is any unfiltered user input in the message it should be safe to use html_safe on the flash messages.
I didn't want to tempt fate by html_safe-ing all flash messages universally, so I decided to just redirect failed confirmation link attempts directly to the url I would have linked them to anyway. It's a simpler, more elegant solution, I think.

Resources