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
@@additional_headers =
[]

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(app) ⇒ CORS

Returns a new instance of CORS.



18
19
20
# File 'lib/pliny/middleware/cors.rb', line 18

def initialize(app)
  @app = app
end

Class Method Details

.add_additional_header(header) ⇒ Object



14
15
16
# File 'lib/pliny/middleware/cors.rb', line 14

def self.add_additional_header(header)
  @@additional_headers << header
end

Instance Method Details

#allow_headersObject



42
43
44
# File 'lib/pliny/middleware/cors.rb', line 42

def allow_headers
  ALLOW_HEADERS + @@additional_headers
end

#call(env) ⇒ Object



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/pliny/middleware/cors.rb', line 22

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



46
47
48
49
50
51
52
53
54
55
# File 'lib/pliny/middleware/cors.rb', line 46

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)


38
39
40
# File 'lib/pliny/middleware/cors.rb', line 38

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