Validate that API article params are a Hash (#5963)
* Add check for article param being a Hash & spec * Remove unnecessary blank line * Move logic to private method and before_action call * Change check_if to validate * Use is_a? to type check * Fix type check for specs
This commit is contained in:
parent
c41d66e900
commit
78a25dfd54
2 changed files with 29 additions and 0 deletions
|
|
@ -7,6 +7,8 @@ module Api
|
|||
before_action :authenticate!, only: :me
|
||||
before_action -> { doorkeeper_authorize! :public }, only: %w[index show], if: -> { doorkeeper_token }
|
||||
|
||||
before_action :validate_article_param_is_hash, only: %w[create update]
|
||||
|
||||
before_action :set_cache_control_headers, only: %i[index show]
|
||||
|
||||
before_action :cors_preflight_check
|
||||
|
|
@ -116,6 +118,13 @@ module Api
|
|||
@user.any_admin?
|
||||
end
|
||||
end
|
||||
|
||||
def validate_article_param_is_hash
|
||||
return if params.to_unsafe_h.dig(:article).is_a?(Hash)
|
||||
|
||||
message = "article param must be a JSON object. You provided article as a #{params[:article].class.name}"
|
||||
render json: { error: message, status: 422 }, status: :unprocessable_entity
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
|
|
|||
|
|
@ -474,6 +474,16 @@ RSpec.describe "Api::V0::Articles", type: :request do
|
|||
expect(response).to have_http_status(:unprocessable_entity)
|
||||
end
|
||||
|
||||
it "fails if params are not a Hash" do
|
||||
# Not using the nifty post_article helper method because it expects a Hash
|
||||
headers = { "api-key" => api_secret.secret, "content-type" => "application/json" }
|
||||
string_params = "this_string_is_definitely_not_a_hash"
|
||||
post api_articles_path, params: { article: string_params }.to_json, headers: headers
|
||||
|
||||
expect(response).to have_http_status(:unprocessable_entity)
|
||||
expect(response.parsed_body["error"]).to be_present
|
||||
end
|
||||
|
||||
it "creates an article belonging to the user" do
|
||||
post_article(title: Faker::Book.title)
|
||||
expect(response).to have_http_status(:created)
|
||||
|
|
@ -941,6 +951,16 @@ RSpec.describe "Api::V0::Articles", type: :request do
|
|||
expect(response).to have_http_status(:ok)
|
||||
expect(article.reload.organization).to eq(organization)
|
||||
end
|
||||
|
||||
it "fails if params are not a Hash" do
|
||||
# Not using the nifty put_article helper method because it expects a Hash
|
||||
headers = { "api-key" => api_secret.secret, "content-type" => "application/json" }
|
||||
string_params = "this_string_is_definitely_not_a_hash"
|
||||
put path, params: { article: string_params }.to_json, headers: headers
|
||||
|
||||
expect(response).to have_http_status(:unprocessable_entity)
|
||||
expect(response.parsed_body["error"]).to be_present
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue