2011-10-15 14:00:00 -04:00
|
|
|
if GlobalSetting.enable_cors
|
2014-07-23 03:03:52 -04:00
|
|
|
class Discourse::Cors
|
|
|
|
def initialize(app, options = nil)
|
|
|
|
@app = app
|
2011-10-15 14:00:00 -04:00
|
|
|
if GlobalSetting.enable_cors && GlobalSetting.cors_origin.present?
|
|
|
|
@global_origins = GlobalSetting.cors_origin.split(',').map(&:strip)
|
|
|
|
end
|
2014-07-23 03:03:52 -04:00
|
|
|
end
|
|
|
|
|
|
|
|
def call(env)
|
2017-07-27 21:20:09 -04:00
|
|
|
if env['REQUEST_METHOD'] == ('OPTIONS') && env['HTTP_ACCESS_CONTROL_REQUEST_METHOD']
|
2015-05-14 11:14:29 -04:00
|
|
|
return [200, apply_headers(env), []]
|
|
|
|
end
|
|
|
|
|
2014-07-23 03:03:52 -04:00
|
|
|
status, headers, body = @app.call(env)
|
2015-05-14 11:14:29 -04:00
|
|
|
[status, apply_headers(env, headers), body]
|
|
|
|
end
|
|
|
|
|
2017-07-27 21:20:09 -04:00
|
|
|
def apply_headers(env, headers = nil)
|
2015-05-14 11:14:29 -04:00
|
|
|
headers ||= {}
|
|
|
|
|
2014-07-23 03:03:52 -04:00
|
|
|
origin = nil
|
2011-10-15 14:00:00 -04:00
|
|
|
cors_origins = @global_origins || []
|
|
|
|
cors_origins += SiteSetting.cors_origins.split('|') if SiteSetting.cors_origins
|
|
|
|
|
|
|
|
if cors_origins
|
|
|
|
if origin = env['HTTP_ORIGIN']
|
|
|
|
origin = nil unless cors_origins.include?(origin)
|
|
|
|
end
|
2014-07-23 03:03:52 -04:00
|
|
|
|
2011-10-15 14:00:00 -04:00
|
|
|
headers['Access-Control-Allow-Origin'] = origin || cors_origins[0]
|
2017-03-06 14:41:57 -05:00
|
|
|
headers['Access-Control-Allow-Headers'] = 'X-Requested-With, X-CSRF-Token, Discourse-Visible'
|
2015-05-14 12:46:36 -04:00
|
|
|
headers['Access-Control-Allow-Credentials'] = 'true'
|
2014-07-23 03:03:52 -04:00
|
|
|
end
|
|
|
|
|
2015-05-14 11:14:29 -04:00
|
|
|
headers
|
2013-04-22 05:16:58 -04:00
|
|
|
end
|
|
|
|
end
|
2014-07-23 03:03:52 -04:00
|
|
|
|
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
|