daddyz / evercookie

evercookie gem for Ruby on Rails
MIT License
49 stars 27 forks source link

Evercookie is being deleted immediately #11

Closed EhsanZ closed 9 years ago

EhsanZ commented 9 years ago

Hi

I want to prevent visitors from voting multiple times using Evercookie, I followed README instructions to setup the gem but I'm having a weird issue.

Everytime I vote it creates a new evercookie, it looks like it is just a temporary cookie that being deleted immediately, I don't know if I forgot something that haven't been mentioned in README or if I should add a specific JS files to get it works, or if I missed some setup steps.

Here it is my voting code

def vote
     if evercookie_is_set?(:voting_ever_cookie)
          old_voting = Vote.where(["voter = ? and item_id = ?",\
                       evercookie_get_value(:voting_ever_cookie), item.id])
                       .first

          if !old_rating.nil?
            redirect_to :back,
                        :error => translate("messages.already_voted")
            return
          end

    else
          set_evercookie(:voting_ever_cookie, SecureRandom.uuid)
    end

    voter = evercookie_get_value(:voting_ever_cookie)

    new_voting = Vote.new({:value => 1, :voter => voter})
end

My Gemfile

source 'https://rubygems.org'
ruby '2.2.0'

gem 'rails', '4.2.1'
gem 'evercookie'

My config file

Evercookie.setup do |config|
  # path for evercookie controller
  config.namespace = :evercookie

  # name of javascript class to be used for evercookie
  config.js_class = :evercookie

  # hash name base for session storage variables
  config.hash_name = :evercookie

  # cookie name for cache storage
  config.cookie_cache = :evercookie_cache

  # cookie name for png storage
  config.cookie_png = :evercookie_png

  # cookie name for etag storage
  config.cookie_etag = :evercookie_etag

  # enable/disable http basic auth (leads to problems if your app uses http basic auth)
  config.basic_auth = true
end

Ruby version 2.0.0, Rails 4.2.1.

daddyz commented 9 years ago

@EhsanZ You placed everything in single action, and it should be in different actions. Since it's all javascript what evercookie.js is doing is restoring normal cookie from evercookie values. First of all set_evercookie must be called in view. View that you are showing with vote options (the one before the posted action is done) should include check_evercookie, it will execute javascript to check for evercookie and will restore normal cookie. After that you will be able to use evercookie_is_set? and evercookie_get_value. Anyway you should take into consideration, that evercookie can be blocked. So you still will be able to get multiple votes if user will block it, because whole library stores data on client side. Additionally check this section. I described there how I used it with registration. Your case is almost the same.