2017-12-06 18:30:50 -05:00
|
|
|
# frozen_string_literal: true
|
|
|
|
|
|
|
|
class Discourse::Cors
|
|
|
|
ORIGINS_ENV = "Discourse_Cors_Origins"
|
|
|
|
|
|
|
|
def initialize(app, options = nil)
|
|
|
|
@app = app
|
|
|
|
if GlobalSetting.enable_cors && GlobalSetting.cors_origin.present?
|
|
|
|
@global_origins = GlobalSetting.cors_origin.split(',').map(&:strip)
|
2014-07-23 03:03:52 -04:00
|
|
|
end
|
2017-12-06 18:30:50 -05:00
|
|
|
end
|
2014-07-23 03:03:52 -04:00
|
|
|
|
2017-12-06 18:30:50 -05:00
|
|
|
def call(env)
|
|
|
|
|
|
|
|
cors_origins = @global_origins || []
|
|
|
|
cors_origins += SiteSetting.cors_origins.split('|') if SiteSetting.cors_origins.present?
|
|
|
|
cors_origins = cors_origins.presence
|
2015-05-14 11:14:29 -04:00
|
|
|
|
2017-12-06 18:30:50 -05:00
|
|
|
if env['REQUEST_METHOD'] == ('OPTIONS') && env['HTTP_ACCESS_CONTROL_REQUEST_METHOD']
|
|
|
|
return [200, Discourse::Cors.apply_headers(cors_origins, env, {}), []]
|
2015-05-14 11:14:29 -04:00
|
|
|
end
|
|
|
|
|
2017-12-06 18:30:50 -05:00
|
|
|
env[Discourse::Cors::ORIGINS_ENV] = cors_origins if cors_origins
|
2015-05-14 11:14:29 -04:00
|
|
|
|
2017-12-06 18:30:50 -05:00
|
|
|
status, headers, body = @app.call(env)
|
|
|
|
headers ||= {}
|
2011-10-15 14:00:00 -04:00
|
|
|
|
2017-12-06 18:30:50 -05:00
|
|
|
Discourse::Cors.apply_headers(cors_origins, env, headers) if cors_origins
|
2014-07-23 03:03:52 -04:00
|
|
|
|
2017-12-06 18:30:50 -05:00
|
|
|
[status, headers, body]
|
|
|
|
end
|
|
|
|
|
|
|
|
def self.apply_headers(cors_origins, env, headers)
|
|
|
|
origin = nil
|
|
|
|
|
|
|
|
if cors_origins
|
|
|
|
if origin = env['HTTP_ORIGIN']
|
|
|
|
origin = nil unless cors_origins.include?(origin)
|
2014-07-23 03:03:52 -04:00
|
|
|
end
|
|
|
|
|
2017-12-06 18:30:50 -05:00
|
|
|
headers['Access-Control-Allow-Origin'] = origin || cors_origins[0]
|
|
|
|
headers['Access-Control-Allow-Headers'] = 'X-Requested-With, X-CSRF-Token, Discourse-Visible'
|
|
|
|
headers['Access-Control-Allow-Credentials'] = 'true'
|
2013-04-22 05:16:58 -04:00
|
|
|
end
|
2017-12-06 18:30:50 -05:00
|
|
|
|
|
|
|
headers
|
2013-04-22 05:16:58 -04:00
|
|
|
end
|
2017-12-06 18:30:50 -05:00
|
|
|
end
|
2014-07-23 03:03:52 -04:00
|
|
|
|
2017-12-06 18:30:50 -05:00
|
|
|
if GlobalSetting.enable_cors
|
2017-03-06 12:24:57 -05:00
|
|
|
Rails.configuration.middleware.insert_before ActionDispatch::Flash, Discourse::Cors
|
2013-04-22 05:16:58 -04:00
|
|
|
end
|