Files
sanasto-wiki/lib/middleware/sanasto_cors.rb
Runar Ingebrigtsen 83320d4c9a
CI / scan_ruby (push) Successful in 17s
CI / scan_js (push) Successful in 12s
CI / lint (push) Failing after 20s
CI / test (push) Successful in 48s
add CORS access for sanasto.app
2026-02-05 23:52:21 +01:00

50 lines
1.3 KiB
Ruby

module Middleware
class SanastoCors
ALLOWED_APP_ID = ENV.fetch("SANASTO_APP_ID", "app.sanasto").freeze
APP_ID_HEADER = "HTTP_X_SANASTO_APP"
def initialize(app)
@app = app
end
def call(env)
if allow_cors_for?(env)
return preflight_response(env["HTTP_ORIGIN"]) if env["REQUEST_METHOD"] == "OPTIONS"
end
status, headers, body = @app.call(env)
if allow_cors_for?(env)
apply_cors_headers(headers, env["HTTP_ORIGIN"])
end
[status, headers, body]
end
private
def allow_cors_for?(env)
origin = env["HTTP_ORIGIN"].to_s
return false if origin.empty?
app_id = env[APP_ID_HEADER].to_s
return false if app_id.empty?
app_id == ALLOWED_APP_ID
end
def preflight_response(origin)
headers = {}
apply_cors_headers(headers, origin)
headers["Access-Control-Max-Age"] = "86400"
[204, headers, []]
end
def apply_cors_headers(headers, origin)
headers["Access-Control-Allow-Origin"] = origin
headers["Access-Control-Allow-Methods"] = "GET, POST, PUT, PATCH, DELETE, OPTIONS"
headers["Access-Control-Allow-Headers"] =
"Origin, Content-Type, Accept, Authorization, X-Sanasto-App"
headers["Vary"] = [headers["Vary"], "Origin, X-Sanasto-App"].compact.join(", ")
end
end
end