add CORS access for sanasto.app
This commit is contained in:
@@ -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
|
||||
|
||||
@@ -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
|
||||
Reference in New Issue
Block a user