Class: RubstApi::Middleware::TrustedHostMiddleware

Inherits:
Object
  • Object
show all
Defined in:
lib/rubst_api/middleware.rb

Instance Method Summary collapse

Constructor Details

#initialize(app, allowed_hosts: ["*"], www_redirect: true) ⇒ TrustedHostMiddleware

Returns a new instance of TrustedHostMiddleware.



56
57
58
# File 'lib/rubst_api/middleware.rb', line 56

def initialize(app, allowed_hosts: ["*"], www_redirect: true)
  @app, @hosts, @redirect = app, allowed_hosts, www_redirect
end

Instance Method Details

#call(env) ⇒ Object



59
60
61
62
63
64
# File 'lib/rubst_api/middleware.rb', line 59

def call(env)
  host = env["HTTP_HOST"].to_s.split(":").first
  allowed = @hosts.include?("*") || @hosts.any? { |pattern| pattern.start_with?("*.") ? host.end_with?(pattern.delete_prefix("*")) : host == pattern }
  return PlainTextResponse.new("Invalid host header", status_code: 400).finish unless allowed
  @app.call(env)
end