Class: Jets::Controller::Middleware::Cors

Inherits:
Object
  • Object
show all
Extended by:
Memoist
Defined in:
lib/jets/controller/middleware/cors.rb

Instance Method Summary collapse

Constructor Details

#initialize(app) ⇒ Cors

Returns a new instance of Cors.



9
10
11
# File 'lib/jets/controller/middleware/cors.rb', line 9

def initialize(app)
  @app = app
end

Instance Method Details

#call(env) ⇒ Object



13
14
15
16
17
18
19
20
21
22
23
# File 'lib/jets/controller/middleware/cors.rb', line 13

def call(env)
  if env['REQUEST_METHOD'] == 'OPTIONS'
    return [200, cors_headers(true), StringIO.new]
  end

  status, headers, body = @app.call(env)
  cors_headers.each do |k,v|
    headers[k] ||= v
  end
  [status, headers, body]
end

#cors_headers(preflight = false) ⇒ Object



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/jets/controller/middleware/cors.rb', line 25

def cors_headers(preflight=false)
  headers = case Jets.config.cors
  when true
    {
      "access-control-allow-origin" => "*", # Required for CORS support to work
      "access-control-allow-credentials" => "true" # Required for cookies, authorization headers with HTTPS
    }
  when String
    {
      "access-control-allow-origin" => Jets.config.cors, # contains Hash with Access-Control-Allow-* values
      "access-control-allow-credentials" => "true" # Required for cookies, authorization headers with HTTPS
    }
  when Hash
    Jets.config.cors # contains Hash with Access-Control-Allow-* values
  else
    {}
  end

  headers.merge!(preflight_headers) if preflight
  headers
end