Rails 4 Options; how to reset a parameter to a set of values

I already read some posts, such as Match the whitelist using strong options in Rails 4 , but this is not quite what I need.

I have a controller that takes an identifier and loads a model. It also optionally receives a query string parameter ( style) which may be one of three values of, small, mediumor large. This is passed to the model method, which uses it to retrieve the attached image (using paperclip). I noticed that if I pass an invalid parameter (for example style=wibble), I get a 400 error and a notification that the internal file path does not exist. Brakeman also notes this as a security issue ...

def show
  style = params[:style] || :medium

  thing = Model.find(params[:id])

  path = "#{Rails.root}/public#{thing.image_url(style)}"
  content_type = thing.image.content_type || 'image/png'
  send_file path, type: content_type, disposition: 'inline'
end

We use ActionController Parameters elsewhere for a great effect; but I don’t see how it can be a “white list” of parameter parameters? Everywhere I saw it is said that it uses a model validator, but on the condition that I present a parameter for updating a model that I am not.

I know I can do something like:

return head :not_found unless %w(small medium large).include? style

Is this the best way?

+4
source share
2 answers

First you need to define a constant with a white list of all valid values style(I would say that size_typeis a more explicit name). (Watch out for character / string comparisons).

404, params[:style] , , 'medium':

style = Model::AVAILABLE_SIZE_TYPES.include?(params[:style]) ? params[:style] || Model::AVAILABLE_SIZE_TYPES.first

. - ( URL-, ..), , .

, , , -, . ModelDecorator, .

+4

, ActionController::Parameters : . . :

def model_params
  params.require(:model).permit(:style, :other_attribute).allow(style: %w[small medium large])
end

,

https://github.com/msimonborg/allowable

+4

Source: https://habr.com/ru/post/1682888/


All Articles