From 8e3955a97bccd47d9a195cdae9a8f4b32d0a4e41 Mon Sep 17 00:00:00 2001 From: Thibault Jouan Date: Fri, 1 May 2015 17:47:06 +0000 Subject: [PATCH] Refuse non-JSON queries on API --- app/controllers/api/application_controller.rb | 5 +++++ spec/integration/api/application_spec.rb | 8 ++++++++ 2 files changed, 13 insertions(+) diff --git a/app/controllers/api/application_controller.rb b/app/controllers/api/application_controller.rb index bf9073d..b8de05d 100644 --- a/app/controllers/api/application_controller.rb +++ b/app/controllers/api/application_controller.rb @@ -4,6 +4,7 @@ module API skip_before_filter :authenticate!, only: :cor_preflight before_filter :cor_filter + before_filter :json_filter! def cor_filter headers['Access-Control-Allow-Origin'] = request.headers['Origin'] ? @@ -28,5 +29,9 @@ module API def authenticate! head :unauthorized if current_user.nil? end + + def json_filter! + head :not_acceptable if request.format != :json + end end end diff --git a/spec/integration/api/application_spec.rb b/spec/integration/api/application_spec.rb index 1f2920d..8c7d26b 100644 --- a/spec/integration/api/application_spec.rb +++ b/spec/integration/api/application_spec.rb @@ -10,4 +10,12 @@ describe 'API application' do expect(json).to eq(pong: 'ok') end end + + describe 'formats handling' do + it 'responds with a 406 when request format is not JSON' do + get api_ping_path, format: :xml + expect(response.status).to be 406 + expect(response.body).to be_empty + end + end end