Skip to content

Commit

Permalink
Merge pull request #320 from bigkevmcd/allow-additional-headers
Browse files Browse the repository at this point in the history
Add mechanism for additional headers.
  • Loading branch information
gudmundur authored Dec 4, 2017
2 parents 5165e8f + 2458a60 commit 26eef13
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 2 deletions.
14 changes: 12 additions & 2 deletions lib/pliny/middleware/cors.rb
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,12 @@ class CORS
EXPOSE_HEADERS =
%w( Cache-Control Content-Language Content-Type Expires Last-Modified Pragma ).freeze

@@additional_headers = []

def self.add_additional_header(header)
@@additional_headers << header
end

def initialize(app)
@app = app
end
Expand All @@ -19,7 +25,7 @@ def call(env)
else
status, headers, response = @app.call(env)

# regualar CORS request: append CORS headers to response
# regular CORS request: append CORS headers to response
if cors_request?(env)
headers.merge!(cors_headers(env))
end
Expand All @@ -32,11 +38,15 @@ def cors_request?(env)
env.has_key?("HTTP_ORIGIN")
end

def allow_headers
ALLOW_HEADERS + @@additional_headers
end

def cors_headers(env)
{
'Access-Control-Allow-Origin' => env["HTTP_ORIGIN"],
'Access-Control-Allow-Methods' => ALLOW_METHODS.join(', '),
'Access-Control-Allow-Headers' => ALLOW_HEADERS.join(', '),
'Access-Control-Allow-Headers' => allow_headers.join(', '),
'Access-Control-Allow-Credentials' => "true",
'Access-Control-Max-Age' => "1728000",
'Access-Control-Expose-Headers' => EXPOSE_HEADERS.join(', ')
Expand Down
11 changes: 11 additions & 0 deletions spec/middleware/cors_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -39,4 +39,15 @@ def app
assert_equal "http://localhost",
last_response.headers["Access-Control-Allow-Origin"]
end

it "allows additional headers to be added to every response" do
Pliny::Middleware::CORS.add_additional_header("X-Origin")

header "Origin", "http://localhost"
get "/"
assert_equal 200, last_response.status
assert_equal "hi", last_response.body

assert last_response.headers["Access-Control-Allow-Headers"].include?("X-Origin")
end
end

0 comments on commit 26eef13

Please sign in to comment.