How can I code to prevent spam posts in Rails3? - ruby-on-rails

I fully understand captcha, and already implemented to my app. It's working fine so far.
Obviously, it'll be annoying if it asks you captcha code to type in every time you wanna post:(
Now I'm thinking of the way comparing current time with the time the user posed last time.
If it's Post model, and it has its created_at(Timestamp)
How can I write in my controller? I'd like to use 'before filter' checking when it does create.
and I want user to wait at least 1 min to post next post.
should it be something like this below? I'm so newbie to Rails. Please help!
def spam_check
#post = Post.find_by_user_id(current_user.id)
lasttime = #post.created_at.last
end

In your Post model :
validate :spam_check?, :on => :create
def spam_check?
#post = Post.find_all_by_user_id(current_user.id).last
last_time = #post.created_at
Time.now - last_time > 1.minute
end

You can use JS to fill some automatically fill some hidden fields in your form before send. And if someone has disabled JS then simply view the captcha.
EDIT: It is good idea in addition to #sub_stantial's post.

Related

Ruby on Rails devise, how to put a limit on how often a user can change their username

`I have recently started working on a rails app and using devise as authentication. but I have ran into a wall. I would like to know if there's a way to set a period limit on how often a user may update their username. For example, if a User update their username today, they shouldn't be able to update it again until a 30day period has passed.
I have looked through devise docs, but nothing address that functionality, I have also search SO and the web but to no avail.
Any help would be very much be appreciated on how to go about it, or at least be pointed in the right direction. Thanks in advance!
I have added to the user model
after_save :name_last_updated
def name_last_updated
if self.username_changed?
self.name_last_updated_at = Time.now
end
but this does not update the colunm name_last_updated_at. any clues of what i am doing wrong will be helpful ^^ thanks!
so, after messing around with a few codes i figured an alternative way to go about this. I created a new column to track new time the user should be able to see the form to update his username.
def username_next_update
self.username_next_update_at = self.username_last_update_at + 2.minutes
end
for learning and testing purposes i added +2.minutes
and i did a before_save on it.
In my view i wrapped it around an if and else statement although i am quite confuse with the logic.
<% if current_user.username_next_update_at < time.zone.now %>
********
<% end %>
but i expected to it to work only if it was > sign instead of <. any tips will be helpful or any better alternatives :)
You need to create it from scratch.
Create a new column in the users table, call it name_last_updated, when the user updates their name for the first time, set that column to today's date. then every time a user wants to update their name, check that column and compare with today's date and see if 30 days have passed:
if Date.today - user.name_last_update < 30
#display error
end
We can use user updated_at column created by the devise gem and add a callback method in the user model to make sure that we call this method every time the user model is updated.
before_update { |user| user.write_attribute if user.is_permitted? }
def write_attribute
self.user_name = params[:user][:user_name]
end
def is_permitted?
if self.username_changed?
Date.today - updated_at < 30
end
end
You should use the before_update and specify which record has to activate the callback instead of using after_save.
I would do something like this:
before_update :name_last_updated, if: :username_changed?
def name_last_updated
if (self.name_last_updated_at.to_date + 30.days) < Date.today
self.update(name_last_updated_at: Time.now)
end
end

How can I protect my site from the multiple post requests?

Any user can 'like' photos on my site. But if he presses the button many times (10 for example), the 10 post requests will be sent to the server.
I tried to solve with the help of sessions.
I thought this code would take likes only each 5 seconds. But it doesnt! There are my action and before_filter:
def like
photo.create_like if session[:voted].nil?
session[:voted] = Time.now.to_a.first(3).reverse.join
redirect_to root_path
end
def check_session
a = Time.now.to_a.first(3).reverse.join
b = a.to_i - session[:voted].to_i
session[:voted] = nil if b >= 5
end
You can't do this with sessions (at least not with the default session store): by default rails stores the session in a cookie.
Cookies are sent by the browser as part of the request, and the response from your server can optionally update them. If you click on your like button several times in quick succession then you'll fire off several requests, each containing cookie data representing the current state of the session. Your response updates the session, but it's too late for the requests that have already been sent - their session data has been already been sent to the server and won't include any changes made by the responses.
As others have said, a bandaid is to use Javascript to restrict multiple submission but the only robust way to deal with this is at the database level ( with a unique index on the likes table).
You forgot reverse in your like method, so the comparison doesn't work. It should be:
session[:voted] = Time.now.to_a.first(3).reverse.join
Also in like you're using session[:voted] and in check_session you're using session[:time].
Although this won't work perfectly either. It would be better to use a Unix timestamp for this and let check_session return a boolean. Something like this:
def like
photo.create_like if check_session
session[:voted] = Time.now.to_i
redirect_to root_path
end
def check_session
session[:voted].blank? || (Time.now.to_i - session[:voted]) > 5
end
disable the button with
<%= submit_tag "Login", 'data-disable-with' => "Please wait.." %>
You could add a conditional in your views to show voted or want to vote? if the user voted already

How to prevent actions at specific date and time?

I would like to allow the users to 'create' and 'update' their submissions (bets) until a specific date and time at which point their bets are final (can no longer be created or updated). This process would repeat each week.
I'm fairly new to Rails and I'm not sure if there is a term for this or what to search for.
Can anyone point me in the right direction?
Probably the easiest way to achieve this is just to add a before_filter (Rails 3.x) or before_action (Rails 4.x) to your controller. You can do so like this:
Assume you have submissions_controller.rb with create/update actions like so - add a before filter that will only apply to the create and update actions. You can then implement a private method in the controller to redirect the user back to your root_path or elsewhere and give a flash message as to why.
class PagesController < ApplicationController
before_filter :check_if_bets_are_final, :only => [:create, :update]
def create
...
end
def update
...
end
private
def check_if_bets_are_final
if Time.now >= Time.new(2014, 02, 20)
flash[:error] = "You can no longer modify or submit new bets!"
redirect_to root_path
end
end
end
Aside from your controller action though, it will probably be safer to implement a model-level validation/check to reject it if the date is past, just to be safe (or if you have other ways to update that object in the future). You can do this through the model hook before_save, in which you can pretty much do a similar check that I have given above.
Also, the other caveat is that comparing Time.now could be in a different timezone depending on where your server is. Just be cognisant of this when you do your checks, and cast the time properly with this in mind.
Since you didn't provide a specific implementation, I'm not quite sure if you're having trouble specifically with Ruby or Rails. However, given your question, I would store a datetime variable in your database when the user creates the bet. Every time the user tries to 'update' the bet, check in the database whether or not it's been past that specific time away from the bet creation. Hope this helps.

Create a logic captcha from scratch

I haven't touched a scrap of code yet, but here's my thoughts on how to do this:
Create a :interactions entry in my session hash. This will contain an array of time stamps. Every time a user goes through any action, the time they did this will be appended to the :interactions entry. The array will be initialized in my sessions controller, and timestamps appended to it via a filter in my application controller:
class SessionsController < ApplicationController
def create
create_session
session[:interactions] = []
end
end
class ApplicationController < ActionController::Base
after_action :log_time
private
def log_time
session[:interactions] << Time.now.to_i
end
end
Then, create another action in my application controller, the one tasked with launching the recaptcha if the user's behaviour is suspicious. All it does is see when we have 20 entries in our session[:interactions] array, find out the time elapsed between each pair of consecutive entries, and then find the average time elapsed between these interactions. If the average time is under two minutes, the recaptcha is launched. The session[interactions] array is then reset.
class ApplicationController < ActionController::Base
after_action :log_time
before_action :launch_captcha
private
def launch_captcha
if session[:interactions].length == 20
elapsed = []
session[:interactions].each_slice(2) do |a, b|
elapsed << b - a
end
total = elapsed.inject(:+)
average = total / 20
if total < 120
# this a part I'm really not sure how to do:
# various instance variables should be populated here
redirect_to 'application/launch_captcha.html.erb'
end
session[:interactions] = []
end
end
def log_time
session[:interactions] << Time.now
end
end
Now, the fact the session[:interactions] is reset may be a bit of a weakness; all bets are off for those twenty interactions. But I want to build on the above logic, maybe add session[:captchas_sent], to the session hash (or even have captchas_sent as a column and save it to the user's record), and if the session[:captchas_sent] is x amount or y amount, warnings or temporary bans could come into effect.
What are your thoughts on the above way of monitoring user behaviour?
Here's where my knowledge of rails is starting to break down though. Once I've redirected the user to the recaptcha page, how should I proceed? I have two tables, questions and answers with a has_many belongs_to relationship between them respectively.
So a random question will come from my questions table, and then I'll have a form that pertains to an answer. It will be an ajax form, and have just one field, a text field for the answer. The action the form links to, human test, will see if the answer given is equal to one of the question's answers. But how should the question's id be passed into this action? It couldn't be a simple hidden field, because once the spammer knows the answer to one question, his script could always set the id to that one question. So the params hash or the sessions hash maybe? I need some advice here guys.
I also don't really know how the human test method should proceed once the it finds the user's answer is equal to one of the question's answers:
Let's say the user is submitting a comment. They fill in the comment, hit the submit button, the launch_captcha action kicks in, and redirects them to 'application/launch_captcha.html.erb'. What has happened to the data in the comment create form? Once they've answered the captcha correctly, how should the human_test method proceed? How could it go on to submit their comment as usual? I just don't know how to do that...I need to create an action that is called before the create action of a form...and..argh I just don't know. Help guys!

Showing if someone is reading a post

I want to show the list of people who are reading a post.
Before attempting to implement the function, I wanted to ask for some advice. I would start by checking users who invoke the show action in the PostsController; every time a person views a post, he will be recorded onto the list of people who are reading the post. However, I am not sure how to remove the person from the list when he navigates away from reading the post. Is there a way to use cookies or sessions to notice if the user navigates away from a certain page? A little bit of help would help me get started right away!
I appreciate any advice. Thank you!
To be more accurate
in routes.rb
post "/posts/:id/being_read" => "posts#being_read", :defaults => { :format => "json"}
in controller
PostsController < ApplicationController
def being_read
current_user && #post.being_read_by current_user
head :ok
end
end
on show page
function beingRead(){
$.post("/posts/<%=#post.id%>/being_read", function(data) {
setTimeout(beingRead,10000);
});
}
in post.rb
def being_read_by user=nil
# making use of rails low level cache
readers_ids = Rails.cache.fetch("Post #{id} being read", :expires_in => 5.minutes) || []
readers_ids = Rails.cache.fetch("Post #{id} being read", :expires_in => 5.minutes) (readers_ids << user.id) if user
readers_ids
end
Usually, a system of timeout is used.
Rather than store a boolean "is reading post", we can store the date on which the user has read the post.
No, you can easily set a timeout (for example 5 minutes) to know who are reading the post. This is an approximation, but this is almost realistic.
Advantages :
you can delete the finished dates when you want (with a cron, each day, or something else), with a single query rather than one a each view.
you resolve the problem of the user who close its browser (when no next page is open)

Resources