Skip to content

Instantly share code, notes, and snippets.

@boy-jer
Forked from ahawkins/cors_middleware.rb
Created May 24, 2012 14:11
Show Gist options
  • Save boy-jer/2781781 to your computer and use it in GitHub Desktop.
Save boy-jer/2781781 to your computer and use it in GitHub Desktop.
Cors Support
class CorsSupport
def initialize(app)
@app = app
end
def call(env)
if preflight?(env)
env['HTTP_ORIGIN'] = 'file://' if env['HTTP_ORIGIN'] == 'null'
env['HTTP_ORIGIN'] ||= env['HTTP_X_ORIGIN']
Rails.logger.debug "CORS Preflight Request from #{env['HTTP_ORIGIN']}"
Rails.logger.debug " Access-Control-Request-Method: #{env['HTTP_ACCESS_CONTROL_REQUEST_METHOD']}"
Rails.logger.debug " Access-Control-Request-Headers: #{env['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}"
headers = cors_headers(env)
headers['Content-Type'] = 'text/plain'
[200, headers, []]
else
status, headers, body = @app.call env
[status, headers.merge(cors_headers(env)), body]
end
end
def cors_headers(env)
headers = {}
headers['Access-Control-Allow-Origin'] = env['HTTP_ORIGIN']
headers['Access-Control-Allow-Methods'] = %w(GET POST PUT DELETE).join(", ")
headers['Access-Control-Allow-Headers'] = [
env['HTTP_ACCESS_CONTROL_REQUEST_HEADERS'],
'X-Radium-User-API-Key',
'X-Radium-Developer-API-key',
'Authorization'
].compact.join(', ')
headers['Access-Control-Expose-Headers'] = ['X-Request-Log-ID'].join(', ')
headers['Access-Control-Allow-Credentials'] = "true"
headers
end
def preflight?(env)
env['REQUEST_METHOD'] == "OPTIONS" &&
env['HTTP_ACCESS_CONTROL_REQUEST_METHOD'] &&
env['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']
end
end
Rails.application.config.middleware.insert 0, CorsSupport
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment