Class: RubyAPI::Plugins::CORS

Inherits:
RubyAPI::Plugin show all
Defined in:
lib/rubyapi/plugins/cors.rb

Class Method Summary collapse

Methods inherited from RubyAPI::Plugin

inherited, option, options, plugin_name, register_cli, register_routes

Class Method Details

.on_load(app) ⇒ Object



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/rubyapi/plugins/cors.rb', line 10

def self.on_load(app)
  allowed = options[:origins]
  methods = options[:methods].join(", ")
  headers = options[:headers].join(", ")
  credentials = options[:allow_credentials]
  max_age = options[:max_age]

  app.before do |ctx|
    origin = ctx.request.get_header("HTTP_ORIGIN")
    next unless allowed.include?("*") || allowed.include?(origin)

    ctx.response_headers["access-control-allow-origin"] = origin || "*"
    ctx.response_headers["access-control-allow-methods"] = methods
    ctx.response_headers["access-control-allow-headers"] = headers
    ctx.response_headers["access-control-allow-credentials"] = credentials.to_s if credentials
    ctx.response_headers["access-control-max-age"] = max_age.to_s

    if ctx.request.request_method == "OPTIONS"
      ctx.response_status = 204
      ctx.response_body = ""
    end
  end
end