Class: RubstApi::Middleware::CORSMiddleware
- Inherits:
-
Object
- Object
- RubstApi::Middleware::CORSMiddleware
- Defined in:
- lib/rubst_api/middleware.rb
Instance Method Summary collapse
- #call(env) ⇒ Object
-
#initialize(app, allow_origins: [], allow_methods: ["GET"], allow_headers: [], allow_credentials: false, expose_headers: [], max_age: 600, allow_origin_regex: nil) ⇒ CORSMiddleware
constructor
A new instance of CORSMiddleware.
Constructor Details
#initialize(app, allow_origins: [], allow_methods: ["GET"], allow_headers: [], allow_credentials: false, expose_headers: [], max_age: 600, allow_origin_regex: nil) ⇒ CORSMiddleware
Returns a new instance of CORSMiddleware.
6 7 8 9 10 |
# File 'lib/rubst_api/middleware.rb', line 6 def initialize(app, allow_origins: [], allow_methods: ["GET"], allow_headers: [], allow_credentials: false, expose_headers: [], max_age: 600, allow_origin_regex: nil) @app, @origins, @methods, @headers = app, allow_origins, allow_methods, allow_headers @credentials, @expose, @max_age, @origin_regex = allow_credentials, expose_headers, max_age, allow_origin_regex end |
Instance Method Details
#call(env) ⇒ Object
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 |
# File 'lib/rubst_api/middleware.rb', line 11 def call(env) origin = env["HTTP_ORIGIN"] return @app.call(env) unless origin allowed = @origins.include?("*") || @origins.include?(origin) || (@origin_regex && Regexp.new(@origin_regex).match?(origin)) return @app.call(env) unless allowed cors = { "access-control-allow-origin" => @credentials ? origin : (@origins.include?("*") ? "*" : origin), "vary" => "Origin" } if env["REQUEST_METHOD"] == "OPTIONS" && env["HTTP_ACCESS_CONTROL_REQUEST_METHOD"] cors.merge!("access-control-allow-methods" => @methods.join(", "), "access-control-allow-headers" => @headers.join(", "), "access-control-max-age" => @max_age.to_s) cors["access-control-allow-credentials"] = "true" if @credentials [200, cors.merge("content-length" => "2"), ["OK"]] else status, headers, body = @app.call(env) headers.merge!(cors) headers["access-control-expose-headers"] = @expose.join(", ") unless @expose.empty? headers["access-control-allow-credentials"] = "true" if @credentials [status, headers, body] end end |