Gem-idea: Automatic spam protection with captcha in before_filter when HTTP-method is post,put or delete

喜夏-厌秋 提交于 2019-12-03 21:00:02

One way this could be put together:

  • Middleware/rails metal component that monitors the requests and adds the information to the rack session.

  • Controller helpers for before_filters on things that might need captchas

  • View helpers for displaying the captchas

You could make the captcha rate adjustable through the args passing mechanism of use

#config/environment.rb
config.middleware.use 'CaptchaMiddleware',:period=>5.minutes,:limit=>50,:captcha_url=>'/captcha'

Also, this should not rely on hidden form fields because a determined bot writer could just change the value they are posting to your server code.

Simple middleware example code(slightly better than a stab in the dark, but still)

class CaptchaMiddleware
  def initialize app,options
    @app = app
    @options=options
  end

  def update_stats!
    #session based,on account of laziness
    session[:reqs] ||= []
    session[:reqs].reject!{ |request| request < Time.now - @options[:period]}
    session[:reqs] << Time.now
  end

  def over_limit?
    session[:reqs].length > @options[:limit]
  end

  def call env
    @env = env
    if @env["REQUEST_METHOD"]!='GET'
      update_stats!
      if over_limit?
        return [302,{"Location: #{options[:captcha_url]}"},'']
      end
    end
    @app.call env
  end

  def session
    @env["rack.session"]
  end
end

First, i would like to say that this is a very good ideea of a feature.

My qs/remarks:

  • this should not pass through all the ActiveRecord stack; can't it be implemented as a middleware hook (Rails Rack)?
  • what about file uploads? (you can not store it in a hidden file)
  • what about Ajax posting?
  • why only POST and not also PUT and DELETE?

Anyway, i would be more interested to see the number of posts in last 5 mins, for example, that the date of the last request. I believe it is more relevant.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!