Sha256: 338f5c45cf716410aeab278a8246f360a0e5b680fb3b436d0beac10ac6ff50db

Contents?: true

Size: 1.91 KB

Versions: 1

Compression:

Stored size: 1.91 KB

Contents

# encoding: utf-8
module SoaringSimpleCaptcha
  class Middleware
    include SoaringSimpleCaptcha::ImageHelpers
    
    DEFAULT_SEND_FILE_OPTIONS = {
      :type         => 'application/octet-stream'.freeze,
      :disposition  => 'attachment'.freeze,
    }.freeze
    
    def initialize(app, options={})
      @app = app
      self
    end
    
    def call(env) # :nodoc:
      if env["REQUEST_METHOD"] == "GET" && captcha_path?(env['PATH_INFO'])
        make_image(env)
      else
        @app.call(env)
      end
    end
    
    protected
      def make_image(env, headers = {}, status = 404)
        request = Rack::Request.new(env)
        code = request.params["code"]
        body = []
        
        if !code.blank? && SoaringSimpleCaptcha::Utils::simple_captcha_value(code)
          #status, headers, body = @app.call(env)
          #status = 200
          #body = generate_simple_captcha_image(code)
          #headers['Content-Type'] = 'image/jpeg'
          
          return send_file(generate_simple_captcha_image(code), :type => 'image/jpeg', :disposition => 'inline', :filename =>  'simple_captcha.jpg')
        end
        
        [status, headers, body]
      end
      
      def captcha_path?(request_path)
        request_path.include?('/soaring_simple_captcha') || request_path.include?('/simple_captcha')
      end
      
      def send_file(path, options = {})
        # raise MissingFile, "Cannot read file #{path}" unless File.file?(path) and File.readable?(path)

        options[:filename] ||= File.basename(path) unless options[:url_based_filename]

        status = options[:status] || 200
        headers = {"Content-Disposition" => "#{options[:disposition]}; filename='#{options[:filename]}'", "Content-Type" => options[:type], 'Content-Transfer-Encoding' => 'binary', 'Cache-Control' => 'private'}
        response_body = File.open(path, "rb")
        
        [status, headers, response_body]
      end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
soaring_simple_captcha-0.1.6 lib/soaring_simple_captcha/middleware.rb