Use rack-cors

We will only return Access-Control headers if request includes an
Origin header

Fixes #18
This commit is contained in:
Hakan Ensari 2016-05-09 11:50:56 +01:00
parent 07781b6d76
commit 250095d262
4 changed files with 17 additions and 24 deletions

View File

@ -7,6 +7,7 @@ ruby '2.3.1'
gem 'fixer'
gem 'newrelic_rpm'
gem 'oj'
gem 'rack-cors'
gem 'rake'
gem 'sequel_pg'
gem 'sinatra'

View File

@ -22,6 +22,7 @@ GEM
method_source (~> 0.8.1)
slop (~> 3.4)
rack (1.6.4)
rack-cors (0.4.0)
rack-protection (1.5.3)
rack
rack-test (0.6.3)
@ -57,6 +58,7 @@ DEPENDENCIES
newrelic_rpm
oj
pry
rack-cors
rack-test
rake
sequel_pg

View File

@ -2,22 +2,9 @@
require 'oj'
require 'sinatra'
require 'rack/cors'
require 'quote'
configure do
set :options_response_headers,
'Allow' => 'GET, HEAD, OPTIONS',
'Access-Control-Allow-Headers' => 'X-Requested-With, X-HTTP-Method-Override, Content-Type, Cache-Control, Accept'
set :cors_response_headers,
'Access-Control-Allow-Credentials' => 'true',
'Access-Control-Allow-Headers' => '*, Content-Type, Accept, AUTHORIZATION, Cache-Control',
'Access-Control-Allow-Methods' => 'GET, HEAD, OPTIONS',
'Access-Control-Allow-Origin' => '*',
'Access-Control-Expose-Headers' => 'Cache-Control, Content-Language, Content-Type, Expires, Last-Modified, Pragma',
'Access-Control-Max-Age' => '1728000'
end
configure :development do
set :show_exceptions, :after_handler
end
@ -60,26 +47,28 @@ helpers do
end
end
# https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS#Preflighted_requests
use Rack::Cors do
allow do
origins '*'
resource '*'
end
end
options '*' do
headers settings.options_response_headers
200
end
get '/' do
enable_cross_origin
last_modified App.released_at
jsonp details: 'http://fixer.io', version: App.version
end
get '/latest' do
enable_cross_origin
last_modified quote[:date]
jsonp quote
end
get(/(?<date>\d{4}-\d{2}-\d{2})/) do
enable_cross_origin
last_modified quote[:date]
jsonp quote
end

View File

@ -51,16 +51,17 @@ describe 'the API' do
it 'allows cross-origin requests' do
%w(/ /latest /2012-11-20).each do |path|
header 'Origin', '*'
get path
assert_equal '*', headers['Access-Control-Allow-Origin']
refute_empty headers['Access-Control-Allow-Methods']
end
end
it 'responds to preflight requests' do
options '/'
refute_empty headers['Allow']
refute_empty headers['Access-Control-Allow-Headers']
last_response.must_be :ok?
%w(/ /latest /2012-11-20).each do |path|
header 'Origin', '*'
options path
refute_empty headers['Access-Control-Allow-Methods']
end
end
end