Skip to content

Instantly share code, notes, and snippets.

@dmexs
Forked from TheKidCoder/example_controller.rb
Last active April 9, 2018 00:43
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dmexs/ebcfe76d9c282bb205ee to your computer and use it in GitHub Desktop.
Save dmexs/ebcfe76d9c282bb205ee to your computer and use it in GitHub Desktop.
Rails - Sanitize Ordering Params
class ClientsController
include OrderingHelpers
def index
# order_by sanitation should work fine here, with sanitation to created_by if invalid
@clients = Clients.order(sanitized_ordering).where(user_id: current_user.id)
# trying to order_by sales.date for example will fail here even if it's valid if the current controller is not ClientController
@clients = Clients.joins(:sales).order(sanitized_ordering.where(user_id: current_user.id)
# order_by sales.date here will work fine once we turn sanitation off
@clients = Clients.joins(:sales).order(sanitized_ordering(sanitize_column=false)).where(user_id: current_user.id)
end
end
module OrderingHelpers
extend ActiveSupport::Concern
def sanitized_ordering(sanitize_column=true)
if sanitize_column == true
"#{sanitize_column(params[:order_by])} #{sanitize_column_direction(params[:order])}"
else
"#{params[:order_by]} #{sanitize_column_direction(params[:order])}"
end
end
# Sanitation doesn't work for joined queries, because it depends on the active controller name
private
def sanitize_column(column)
resource.column_names.include?(column) ? column : "created_at"
end
def sanitize_column_direction(direction = "DESC")
direction = direction.upcase
['DESC', 'ASC'].include?(direction) ? direction : "DESC"
end
def resource
controller_name.camelize.singularize.safe_constantize
end
end
@joshuapinter
Copy link

Typo on Line #9 in example_controller.rb.

Also, not sanitizing the column kinda makes this whole thing pointless, no?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment