class Rack::CorsGate

Public Class Methods

new(app, opts = {}, &forbidden_handler) click to toggle source
# File lib/classes/cors_gate.rb, line 5
def initialize(app, opts = {}, &forbidden_handler)
  @app = app

  @simulation = opts[:simulation] || false
  @strict = opts[:strict] || false
  @allow_safe = opts[:allow_safe] || false
  @forbidden_handler = forbidden_handler
end
use(middleware, opts = {}, &forbidden_handler) click to toggle source
# File lib/classes/cors_gate.rb, line 33
def self.use(middleware, opts = {}, &forbidden_handler)
  middleware.insert_before Rack::Cors, Rack::CorsGateOriginProcessor, opts
  middleware.insert_after Rack::Cors, Rack::CorsGate, opts, &forbidden_handler
end

Public Instance Methods

call(env) click to toggle source
# File lib/classes/cors_gate.rb, line 14
def call(env)
  origin = env['HTTP_X_ORIGIN'] || env['HTTP_ORIGIN']
  method = env['REQUEST_METHOD']

  if is_allowed(env, origin, method)
    # valid request
    @app.call(env)
  else
    # allow logging, etc
    @forbidden_handler.call(env, origin, method) if @forbidden_handler

    # if we're simulating, forbidden_handler will have been called, but we continue with app-execution
    return @app.call(env) if @simulation

    # 403 Forbidden
    [403, {}, []]
  end
end

Private Instance Methods

is_allowed(env, origin, method) click to toggle source
# File lib/classes/cors_gate.rb, line 40
def is_allowed(env, origin, method)
  return true if @allow_safe && ['GET', 'HEAD'].include?(method.upcase)
  return true if !@strict && origin.nil?
  env['rack.cors'].hit?
end