Class: Rack::Cors

Inherits:
Object
  • Object
show all
Defined in:
lib/rack/cors.rb,
lib/rack/cors/version.rb

Defined Under Namespace

Classes: Resource, Resources, Result

Constant Summary collapse

ENV_KEY =
'X_RACK_CORS'.freeze
ORIGIN_HEADER_KEY =
'HTTP_ORIGIN'.freeze
PATH_INFO_HEADER_KEY =
'PATH_INFO'.freeze
VERSION =
"0.3.0"

Instance Method Summary collapse

Constructor Details

#initialize(app, opts = {}, &block) ⇒ Cors

Returns a new instance of Cors.



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

def initialize(app, opts={}, &block)
  @app = app
  @debug_mode = !!opts[:debug]

  if logger = opts[:logger]
    if logger.respond_to? :call
      @logger_proc = opts[:logger]
    else
      @logger = logger
    end
  end

  if block_given?
    if block.arity == 1
      block.call(self)
    else
      instance_eval(&block)
    end
  end
end

Instance Method Details

#allow(&block) ⇒ Object



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

def allow(&block)
  all_resources << (resources = Resources.new)

  if block.arity == 1
    block.call(resources)
  else
    resources.instance_eval(&block)
  end
end

#call(env) ⇒ Object



45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
# File 'lib/rack/cors.rb', line 45

def call(env)
  env[ORIGIN_HEADER_KEY] ||= env['HTTP_X_ORIGIN']

  add_headers = nil
  if env[ORIGIN_HEADER_KEY]
    debug(env) do
      [ 'Incoming Headers:',
        "  Origin: #{env[ORIGIN_HEADER_KEY]}",
        "  Access-Control-Request-Method: #{env['HTTP_ACCESS_CONTROL_REQUEST_METHOD']}",
        "  Access-Control-Request-Headers: #{env['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}"
        ].join("\n")
    end
    if env['REQUEST_METHOD'] == 'OPTIONS' and env['HTTP_ACCESS_CONTROL_REQUEST_METHOD']
      if headers = process_preflight(env)
        debug(env) do
          "Preflight Headers:\n" +
              headers.collect{|kv| "  #{kv.join(': ')}"}.join("\n")
        end
        return [200, headers, []]
      end
    else
      add_headers = process_cors(env)
    end
  else
    Result.miss(env, Result::MISS_NO_ORIGIN)
  end

  status, headers, body = @app.call env

  if add_headers
    headers = headers.merge(add_headers)

    # http://www.w3.org/TR/cors/#resource-implementation
    unless headers['Access-Control-Allow-Origin'] == '*'
      vary = headers['Vary']
      headers['Vary'] = ((vary ? vary.split(/,\s*/) : []) + ['Origin']).uniq.join(', ')
    end
  end

  if debug? && result = env[ENV_KEY]
    result.append_header(headers)
  end

  [status, headers, body]
end

#debug?Boolean

Returns:

  • (Boolean)


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

def debug?
  @debug_mode
end