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