Class: Pliny::Middleware::CORS

Inherits:
Object
  • Object
show all
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

Instance Method Summary collapse

Constructor Details

#initialize(app) ⇒ CORS

Returns a new instance of CORS.



11
12
13
# File 'lib/pliny/middleware/cors.rb', line 11

def initialize(app)
  @app = app
end

Instance Method Details

#call(env) ⇒ Object



15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/pliny/middleware/cors.rb', line 15

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)

    # regualar 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



35
36
37
38
39
40
41
42
43
44
# File 'lib/pliny/middleware/cors.rb', line 35

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

Returns:

  • (Boolean)


31
32
33
# File 'lib/pliny/middleware/cors.rb', line 31

def cors_request?(env)
  env.has_key?("HTTP_ORIGIN")
end