Skip to content

Instantly share code, notes, and snippets.

@lorddoig
Last active December 18, 2015 21:29
Show Gist options
  • Select an option

  • Save lorddoig/5847280 to your computer and use it in GitHub Desktop.

Select an option

Save lorddoig/5847280 to your computer and use it in GitHub Desktop.
Rails: deal with HTTP OPTIONS requests in middleware
module AppName
# ...
class Application < Rails::Application
# ...
config.middleware.use "OptionRequests"
# ...
end
# ...
end
# lib/option_requests.rb
class OptionRequests
def initialize(app)
@app = app
end
def call(env)
if env['REQUEST_METHOD'] == "OPTIONS"
if access_allowed?(env['HTTP_ORIGIN'])
[200, cor_headers(env['HTTP_ORIGIN']), []]
else
[403, { 'Content-Type' => 'text/html', 'Content-Length' => '0' }, []]
end
else
@app.call(env)
end
end
private
def access_allowed?(origin)
/^https?:\/\/(.*)\.subdomain\.site\.com$/i.match(origin)
end
def cor_headers(origin)
{
'Access-Control-Allow-Origin' => origin,
'Access-Control-Expose-Headers' => 'ETag',
'Access-Control-Allow-Methods' => 'GET, POST, PATCH, PUT, DELETE, OPTIONS, HEAD',
'Access-Control-Allow-Headers' => '*,x-requested-with,Content-Type,If-Modified-Since,If-None-Match,Auth-User-Token',
'Access-Control-Max-Age' => '86400',
'Access-Control-Allow-Credentials' => 'true'
}
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment