Sha256: f958ee81e6fd02c9786a895df69f3f9a7b250cf47c4c1fbfb71a6ca8156b8ab7

Contents?: true

Size: 1.37 KB

Versions: 6

Compression:

Stored size: 1.37 KB

Contents

module Rswag
  module Ui
    class Middleware < Rack::Static

      def initialize(app, config)
        @config = config
        super(app, urls: [ '' ], root: config.assets_root )
      end

      def call(env)
        if base_path?(env)
          redirect_uri = env['SCRIPT_NAME'].chomp('/') + '/index.html'
          return [ 301, { 'Location' => redirect_uri }, [ ] ]
        end

        if index_path?(env)
          return [ 200, { 'Content-Type' => 'text/html', 'Content-Security-Policy' => csp }, [ render_template ] ]
        end

        super
      end

      private

      def base_path?(env)
        env['REQUEST_METHOD'] == "GET" && env['PATH_INFO'] == "/"
      end

      def index_path?(env)
        env['REQUEST_METHOD'] == "GET" && env['PATH_INFO'] == "/index.html"
      end

      def render_template
        file = File.new(template_filename)
        template = ERB.new(file.read)
        template.result(@config.get_binding)
      end

      def template_filename
        @config.template_locations.find { |filename| File.exist?(filename) }
      end

      def csp
        <<~POLICY.gsub "\n", ' '
          default-src 'self';
          img-src 'self' data:;
          font-src 'self' https://fonts.gstatic.com;
          style-src 'self' 'unsafe-inline' https://fonts.googleapis.com;
          script-src 'self' 'unsafe-inline';
        POLICY
      end
    end
  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
rswag-ui-2.11.0 lib/rswag/ui/middleware.rb
rswag-ui-2.10.1 lib/rswag/ui/middleware.rb
rswag-ui-2.10.0 lib/rswag/ui/middleware.rb
rswag-ui-2.9.0 lib/rswag/ui/middleware.rb
rswag-ui-2.8.0 lib/rswag/ui/middleware.rb
rswag-ui-2.7.0 lib/rswag/ui/middleware.rb