SimpleSpamPrevent¶ ↑
SimpleSpamPrevent is a gem to prevent repetetive requests from logged in users.
Their are many gems available to show captcha but they dont help us when a user is logged in. Using this GEM, You can configure each rails action to a limit ‘x’ in ‘y’ seconds. So if a user is logged in and he hits the same page more than ‘x’ number of times in the last ‘y’ seconds, then he will be redirected to a page where he needs to enter captcha.
Requirements¶ ↑
rails >= 3.0
Setup¶ ↑
Add to your Gemfile:
gem 'simple_spam_prevent'
Add the following line to config/routes.rb:
mount SimpleSpamPrevent::Engine => "/simple_spam_prevent", :as => 'simple_spam_prevent'
Run:
rake db:migrate
Usage¶ ↑
Let say you want to block repetetive requests if greater than 10 on index action of ‘HomeController’ in 2 sec.
Let say the model of logged_in entity in your app is User. Define a method in application controller current_user which gives you current logged in users id.
Then inside Home controller add
before_filter(only: [:action]) { prevent_spam_from(klass, max_times, interval) }
In our case:
before_filter(only: [:index]) { prevent_spam_from(User, 10, 2.second) }
Note: This assumes that you have a function “current_#{klass}” defined. (In this case current_user) which returns the ActiveRecord object of the logged in user.
If you have some other method defined instead of “current_#{klass}” which gives us the activerecord object, then use
before_filter(only: [:action]) { prevent_spam(:klass, #id_of_user, max_times, interval) }
If function “foo” gives us the active record obj for logged in user, then we can write,
before_filter(only: [:index]) { prevent_spam(:user, foo.id, 10, 2.second) }