diff --git a/lib/rack/honeypot.rb b/lib/rack/honeypot.rb index 96c8f56..3793235 100644 --- a/lib/rack/honeypot.rb +++ b/lib/rack/honeypot.rb @@ -22,19 +22,25 @@ def call(env) @logger.warn("[Rack::Honeypot] Spam bot detected; responded with null") unless @logger.nil? null_response else - status, headers, body = @app.call(env) - - if @always_enabled || honeypot_header_present?(headers) - body = insert_honeypot(body) - headers = response_headers(headers, body) + @status, @headers, @response = @app.call(env) + if @headers["Content-Type"] and @headers["Content-Type"].include?("text/html") and (@always_enabled || honeypot_header_present?(@headers)) + body = insert_honeypot(response_body(@response)) + @headers.merge("Content-Length" => body.length.to_s) + [@status, @headers, [body]] + else + [@status, @headers, @response] end - - [status, headers, body] end end private + def response_body(response) + body = response.respond_to?(:body) ? response.body : response + body = body.inject("") { |i, a| i << a } if body.respond_to?(:each) + body.to_s + end + def spambot_submission?(form_hash) form_hash && form_hash[@input_name] && form_hash[@input_name] != @input_value end @@ -43,26 +49,16 @@ def honeypot_header_present?(headers) header = headers.delete(HONEYPOT_HEADER) header && header.index("enabled") end - + def null_response [200, {'Content-Type' => 'text/html', "Content-Length" => "0"}, []] end - - def response_body(response) - body = "" - - # The body may not be an array, so we need to call #each here. - response.each {|part| body << part } - body - end - def response_headers(headers, body) headers.merge("Content-Length" => body.length.to_s) end def insert_honeypot(body) - body = response_body(body) body.gsub!(/<\/head>/, css + "\n") body.gsub!(//, '' + "\n" + div) body diff --git a/rack-honeypot.gemspec b/rack-honeypot.gemspec index 3e62b4a..dd62e0f 100644 --- a/rack-honeypot.gemspec +++ b/rack-honeypot.gemspec @@ -22,5 +22,6 @@ Gem::Specification.new do |s| s.add_dependency(%q, ["= 0.0.4"]) s.add_dependency(%q, [">= 0"]) + s.add_development_dependency('rack-test') end diff --git a/test/test_honeypot.rb b/test/test_honeypot.rb index f46fe13..d30d386 100644 --- a/test/test_honeypot.rb +++ b/test/test_honeypot.rb @@ -1,6 +1,6 @@ require 'rack/test' require 'test/unit' -require 'mocha' +require 'mocha/setup' require 'unindentable' require File.expand_path(File.dirname(__FILE__) + '/../lib/rack/honeypot') @@ -30,7 +30,7 @@ def app BLOCK headers = { - 'Content-Type' => 'text/plain', + 'Content-Type' => 'text/html', 'Content-Length' => content.length.to_s, }