class Startback::Web::CorsHeaders

Sets Cross-Origin Response Headers on requests specifying an Origin HTTP header, according configuration passed at construction and/or environment variables.

Example:

# Default configuration, using environment variables when set
use CorsHeaders

# Force a bouncing of the origin, using the Origin request header
# as Access-Control-Allow-Origin response header
use CorsHeaders, bounce: true

# Overrides a specific header
use CorsHeaders, headers: { 'Access-Control-Allow-Methods' => 'POST' }

Constants

ALLOW_CREDENTIALS
ALLOW_HEADERS
ALLOW_METHODS
ALLOW_ORIGIN
DEFAULT_CORS_HEADERS
DEFAULT_OPTIONS
EXPOSE_HEADERS
MAX_AGE

Public Class Methods

new(app, options = {}) click to toggle source
# File lib/startback/web/cors_headers.rb, line 47
def initialize(app, options = {})
  @app = app
  @options = Startback::Support.deep_merge(DEFAULT_OPTIONS, options)
end

Public Instance Methods

call(env) click to toggle source
# File lib/startback/web/cors_headers.rb, line 52
def call(env)
  status, headers, body = @app.call(env)
  if origin = env['HTTP_ORIGIN']
    headers = cors_headers(origin).merge(headers)
  end
  if env['REQUEST_METHOD'] == 'OPTIONS'
    headers['Content-Length'] = '0'
    status, headers, body = [204, headers, []]
  end
  [status, headers, body]
end

Private Instance Methods

bounce?() click to toggle source
# File lib/startback/web/cors_headers.rb, line 74
def bounce?
  @options[:bounce]
end
cors_headers(origin) click to toggle source
# File lib/startback/web/cors_headers.rb, line 66
def cors_headers(origin)
  headers = @options[:headers].dup
  if bounce?
    headers['Access-Control-Allow-Origin'] = origin
  end
  headers
end