-
-
Save dmexs/ebcfe76d9c282bb205ee to your computer and use it in GitHub Desktop.
Rails - Sanitize Ordering Params
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Typo on Line #9 in
example_controller.rb
.Also, not sanitizing the column kinda makes this whole thing pointless, no?