Last active
December 18, 2015 21:29
-
-
Save lorddoig/5847280 to your computer and use it in GitHub Desktop.
Rails: deal with HTTP OPTIONS requests in 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
| module AppName | |
| # ... | |
| class Application < Rails::Application | |
| # ... | |
| config.middleware.use "OptionRequests" | |
| # ... | |
| 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
| # 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