From 467c76b2c03a69a5ab05806faa039e52320282f0 Mon Sep 17 00:00:00 2001 From: slainer68 Date: Mon, 22 Apr 2013 11:16:58 +0200 Subject: [PATCH] Implements support for rack-cors for API JavaScript access in end-user browser --- Gemfile | 2 ++ Gemfile.lock | 3 +++ config/environments/production.sample.rb | 7 +++++++ config/initializers/08-rack-cors.rb | 13 +++++++++++++ 4 files changed, 25 insertions(+) create mode 100644 config/initializers/08-rack-cors.rb diff --git a/Gemfile b/Gemfile index f929e9914..9ccb7dbdd 100644 --- a/Gemfile +++ b/Gemfile @@ -127,6 +127,8 @@ gem 'rack-mini-profiler', require: false # require: false #, git: 'git://github gem 'redis-rack-cache', require: false gem 'rack-cache', require: false +gem 'rack-cors', require: false + # perftools only works on 1.9 atm group :profile do # travis refuses to install this, instead of fuffing, just avoid it for now diff --git a/Gemfile.lock b/Gemfile.lock index 8b2e816e4..c200ba9fb 100644 --- a/Gemfile.lock +++ b/Gemfile.lock @@ -331,6 +331,8 @@ GEM rack (1.4.5) rack-cache (1.2) rack (>= 0.4) + rack-cors (0.2.7) + rack rack-mini-profiler (0.1.26) rack (>= 1.1.3) rack-openid (1.3.1) @@ -526,6 +528,7 @@ DEPENDENCIES pg pry-rails rack-cache + rack-cors rack-mini-profiler rails rails_multisite! diff --git a/config/environments/production.sample.rb b/config/environments/production.sample.rb index 807014e2b..e4dabbd35 100644 --- a/config/environments/production.sample.rb +++ b/config/environments/production.sample.rb @@ -55,6 +55,13 @@ Discourse::Application.configure do # allows admins to use mini profiler config.enable_mini_profiler = true + # allows Cross-origin resource sharing (CORS) for API access in JavaScript (default to false for security). + # See the initializer and https://github.com/cyu/rack-cors for configuration documentation. + # + # config.enable_rack_cors = false + # config.rack_cors_origins = ['*'] + # config.rack_cors_resource = ['*', { :headers => :any, :methods => [:get, :post, :options] }] + # Discourse strongly recommend you use a CDN. # For origin pull cdns all you need to do is register an account and configure # config.action_controller.asset_host = "http://YOUR_CDN_HERE" diff --git a/config/initializers/08-rack-cors.rb b/config/initializers/08-rack-cors.rb new file mode 100644 index 000000000..cf66e1594 --- /dev/null +++ b/config/initializers/08-rack-cors.rb @@ -0,0 +1,13 @@ +if Rails.configuration.respond_to?(:enable_rack_cors) && Rails.configuration.enable_rack_cors + require 'rack/cors' + + cors_origins = Rails.configuration.respond_to?(:rack_cors_origins) ? Rails.configuration.rack_cors_origins : ['*'] + cors_resource = Rails.configuration.respond_to?(:rack_cors_resource) ? Rails.configuration.rack_cors_resource : ['*', { headers: :any, methods: [:get, :post, :options] }] + + Rails.configuration.middleware.use Rack::Cors do + allow do + origins *cors_origins + resource *cors_resource + end + end +end