add CORS access for sanasto.app
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

This commit is contained in:
2026-02-05 23:52:21 +01:00
parent a2008e2ae3
commit 83320d4c9a
2 changed files with 52 additions and 0 deletions
+3
View File
@@ -1,6 +1,7 @@
require_relative "boot"
require "rails/all"
require_relative "../lib/middleware/sanasto_cors"
# Require the gems listed in Gemfile, including any gems
# you've limited to :test, :development, or :production.
@@ -24,5 +25,7 @@ module SanastoWiki
# config.time_zone = "Central Time (US & Canada)"
# config.eager_load_paths << Rails.root.join("extras")
config.active_record.schema_format = :sql
config.middleware.insert_before 0, Middleware::SanastoCors
end
end
+49
View File
@@ -0,0 +1,49 @@
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