diff --git a/Gemfile b/Gemfile index 7e8688e..c6085ab 100644 --- a/Gemfile +++ b/Gemfile @@ -11,6 +11,7 @@ gem 'net-http-persistent' gem 'airbrake' gem 'rack-contrib' gem 'jbuilder' +gem 'rack-cors' gem 'us_states', :git => 'git://github.com/GSA/us_states.git' diff --git a/Gemfile.lock b/Gemfile.lock index 4bc8464..7a4bbb7 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -94,6 +94,7 @@ GEM rack (>= 0.4) rack-contrib (1.1.0) rack (>= 0.9.1) + rack-cors (0.3.1) rack-ssl (1.3.3) rack rack-test (0.6.2) @@ -189,6 +190,7 @@ DEPENDENCIES nokogiri oj rack-contrib + rack-cors rails (= 3.2.13) rails-api rspec diff --git a/config/application.rb b/config/application.rb index a319ea7..af49ffd 100644 --- a/config/application.rb +++ b/config/application.rb @@ -24,5 +24,11 @@ class Application < Rails::Application config.middleware.use Rack::JSONP + config.middleware.insert_before 0, "Rack::Cors" do + allow do + origins '*' + resource '*', headers: :any, methods: [:get, :options] + end + end end end diff --git a/spec/cors_spec.rb b/spec/cors_spec.rb new file mode 100644 index 0000000..862475e --- /dev/null +++ b/spec/cors_spec.rb @@ -0,0 +1,34 @@ +require 'spec_helper' + +class DummyController < ApplicationController + def show + render text: 'text' + end +end + +describe DummyController, type: :request do + describe '#show' do + before do + Rails.application.routes.draw do + match '/show' => 'dummy#show' + end + + get 'show', nil, { 'HTTP_ORIGIN' => 'http://www.example.com' } + end + + after do + Rails.application.reload_routes! + end + + it 'should respond with an "Access-Control-Allow-Origin" header' do + expect(headers.keys).to include('Access-Control-Allow-Origin') + end + + %w[GET OPTIONS].each do |verb| + it "should respond with a 'Access-Control-Allow-Methods' header allowing #{verb}" do + allowed_methods = headers['Access-Control-Allow-Methods'].split(', ') + expect(allowed_methods).to include(verb) + end + end + end +end