Class: Pliny::Middleware::CORS
- Inherits:
-
Object
- Object
- Pliny::Middleware::CORS
- Defined in:
- lib/pliny/middleware/cors.rb
Constant Summary collapse
- ALLOW_METHODS =
%w( GET POST PUT PATCH DELETE OPTIONS ).freeze
- ALLOW_HEADERS =
%w( Content-Type Accept Authorization Cache-Control If-None-Match If-Modified-Since Origin).freeze
- EXPOSE_HEADERS =
%w( Cache-Control Content-Language Content-Type Expires Last-Modified Pragma ).freeze
- @@additional_headers =
[]
Class Method Summary collapse
Instance Method Summary collapse
- #allow_headers ⇒ Object
- #call(env) ⇒ Object
- #cors_headers(env) ⇒ Object
- #cors_request?(env) ⇒ Boolean
-
#initialize(app) ⇒ CORS
constructor
A new instance of CORS.
Constructor Details
#initialize(app) ⇒ CORS
Returns a new instance of CORS.
17 18 19 |
# File 'lib/pliny/middleware/cors.rb', line 17 def initialize(app) @app = app end |
Class Method Details
.add_additional_header(header) ⇒ Object
13 14 15 |
# File 'lib/pliny/middleware/cors.rb', line 13 def self.add_additional_header(header) @@additional_headers << header end |
Instance Method Details
#allow_headers ⇒ Object
41 42 43 |
# File 'lib/pliny/middleware/cors.rb', line 41 def allow_headers ALLOW_HEADERS + @@additional_headers end |
#call(env) ⇒ Object
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
# File 'lib/pliny/middleware/cors.rb', line 21 def call(env) # preflight request: render a stub 200 with the CORS headers if cors_request?(env) && env["REQUEST_METHOD"] == "OPTIONS" [200, cors_headers(env), [""]] else status, headers, response = @app.call(env) # regular CORS request: append CORS headers to response if cors_request?(env) headers.merge!(cors_headers(env)) end [status, headers, response] end end |
#cors_headers(env) ⇒ Object
45 46 47 48 49 50 51 52 53 54 |
# File 'lib/pliny/middleware/cors.rb', line 45 def cors_headers(env) { 'Access-Control-Allow-Origin' => env["HTTP_ORIGIN"], 'Access-Control-Allow-Methods' => ALLOW_METHODS.join(', '), 'Access-Control-Allow-Headers' => allow_headers.join(', '), 'Access-Control-Allow-Credentials' => "true", 'Access-Control-Max-Age' => "1728000", 'Access-Control-Expose-Headers' => EXPOSE_HEADERS.join(', ') } end |
#cors_request?(env) ⇒ Boolean
37 38 39 |
# File 'lib/pliny/middleware/cors.rb', line 37 def cors_request?(env) env.has_key?("HTTP_ORIGIN") end |