forked from interagent/pliny
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cors.rb
46 lines (39 loc) · 1.32 KB
/
cors.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
module Pliny::Middleware
class CORS
ALLOW_METHODS =
%w( GET POST PUT PATCH DELETE OPTIONS ).freeze
ALLOW_HEADERS =
%w( * Content-Type Accept AUTHORIZATION Cache-Control ).freeze
EXPOSE_HEADERS =
%w( Cache-Control Content-Language Content-Type Expires Last-Modified Pragma ).freeze
def initialize(app)
@app = app
end
def call(env)
# preflight request: render a stub 200 with the CORS headers
if cors_request?(env) && env["REQUEST_METHOD"] == "OPTIONS"
[200, cors_headers(env), [""]]
else
status, headers, response = @app.call(env)
# regualar CORS request: append CORS headers to response
if cors_request?(env)
headers.merge!(cors_headers(env))
end
[status, headers, response]
end
end
def cors_request?(env)
env.has_key?("HTTP_ORIGIN")
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-Credentials' => "true",
'Access-Control-Max-Age' => "1728000",
'Access-Control-Expose-Headers' => EXPOSE_HEADERS.join(', ')
}
end
end
end