Class: Stipa::Middleware::Cors
- Inherits:
-
Object
- Object
- Stipa::Middleware::Cors
- Defined in:
- lib/stipa/middleware.rb
Overview
Simple CORS headers. Handles OPTIONS preflight automatically. Pass origins: [‘*’] to allow all, or a specific list for allowlisting.
Instance Method Summary collapse
- #call(req, res) ⇒ Object
-
#initialize(next_app, origins: ['*'], methods: %w[GET POST PUT PATCH DELETE OPTIONS])) ⇒ Cors
constructor
A new instance of Cors.
Constructor Details
#initialize(next_app, origins: ['*'], methods: %w[GET POST PUT PATCH DELETE OPTIONS])) ⇒ Cors
Returns a new instance of Cors.
97 98 99 100 101 102 |
# File 'lib/stipa/middleware.rb', line 97 def initialize(next_app, origins: ['*'], methods: %w[GET POST PUT PATCH DELETE OPTIONS]) @next_app = next_app @origins = Array(origins) @methods = methods.join(', ') end |
Instance Method Details
#call(req, res) ⇒ Object
104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 |
# File 'lib/stipa/middleware.rb', line 104 def call(req, res) origin = req['origin'] wildcard = @origins.include?('*') allowed = wildcard || (origin && @origins.include?(origin)) if allowed # Never reflect an arbitrary Origin back. When the allowlist is '*', # set the header to the literal '*'. When using an explicit list, only # echo origins that are actually in the list (already guaranteed by # the `allowed` check above). res.set_header('Access-Control-Allow-Origin', wildcard ? '*' : origin) res.set_header('Access-Control-Allow-Methods', @methods) res.set_header('Access-Control-Allow-Headers', 'Content-Type, Authorization, X-Request-Id') # Vary tells caches that the response differs by Origin res.set_header('Vary', 'Origin') unless wildcard end # OPTIONS preflight: respond immediately without hitting the router if req.method == 'OPTIONS' res.status = 204 return res end @next_app.call(req, res) end |