Created
March 18, 2013 13:42
-
-
Save tomas-stefano/5187217 to your computer and use it in GitHub Desktop.
Cross Origin Resource Sharing Rack middleware.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# This class should parse a yaml configuration file. | |
# | |
require 'ostruct' | |
class APISettings | |
def self.cross_origin_resource_sharing | |
OpenStruct.new(allow: ['http://127.0.0.1:8080', 'http://localhost:8080']) | |
end | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class CrossOriginResourceSharing | |
def initialize(app) | |
@app = app | |
@headers = { | |
'Access-Control-Request-Method' => 'GET, POST, PUT, DELETE, OPTIONS', | |
'Access-Control-Allow-Headers' => 'Content-Type, Accept, Cache-Control, Content-Language, Last-Modified, Expires, Origin, x-requested-with, Accept-Language, Access' | |
} | |
end | |
def call(env) | |
if env['HTTP_ORIGIN'] | |
@headers['Access-Control-Allow-Origin'] = access_control_allow_origin(env) | |
if env['REQUEST_METHOD'] == 'OPTIONS' | |
[200, @headers.merge('Content-Type' => 'text/plain', 'Content-Length' => '0'), []] | |
else | |
status, headers, body = @app.call(env) | |
[status, headers.merge(@headers), body] | |
end | |
else | |
@app.call(env) | |
end | |
end | |
def access_control_allow_origin(env) | |
if env['HTTP_ORIGIN'].in?(APISettings.cross_origin_resource_sharing.allow) | |
env['HTTP_ORIGIN'] | |
else | |
APISettings.cross_origin_resource_sharing.allow.first | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment