Sha256: c16695c658a5c456fa721ffde671e99c4984eae2680fb4ce60206ef9ec0eeb93

Contents?: true

Size: 1.85 KB

Versions: 5

Compression:

Stored size: 1.85 KB

Contents

# encoding: utf-8
module SimpleCaptcha
  class Middleware
    include SimpleCaptcha::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? && Utils::simple_captcha_value(code)
          return send_file(generate_simple_captcha_image(code), :type => 'image/jpeg', :disposition => 'inline', :filename =>  'simple_captcha.jpg')
        else
          [500, {
             "Content-Type" => 'text/plain',
          }, ["captcha error"]]
        end
      end
      
      def captcha_path?(request_path)
        request_path.include?('/simple_captcha')
      end
      
      def send_file(path, options = {})
        unless File.file?(path) and File.readable?(path)
          puts "[simple captcha] Cannot read file #{path}"
          raise MissingFile, "Cannot read file #{path}"
        end

        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").read]
        File.delete(path)
        
        [status, headers, response_body]
      end
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
glebtv-simple_captcha-0.8.1 lib/simple_captcha/middleware.rb
glebtv-simple_captcha-0.8.0 lib/simple_captcha/middleware.rb
glebtv-simple_captcha-0.7.0 lib/simple_captcha/middleware.rb
glebtv-simple_captcha-0.6.7 lib/simple_captcha/middleware.rb
glebtv-simple_captcha-0.6.5 lib/simple_captcha/middleware.rb