0

I am using rails 4 with has_secure_password which has password_digest in users table.i would like to store some unique value to cookie, password_digest is unique for user in users table? how to use it as unique token? can i?

Ritesh katare
  • 114
  • 2
  • 11

1 Answers1

1

As @JonathonReinhart said, don't re-use the password_digest, and since the authenticity_token for CSRF changes in the session for every form that is submitted, you can't use that here either. If you just need to generate a unique token for your User model, I recommend doing something like this:

rails generate migration AddAccessTokenToUser access_token:string:uniq:index

Then you can generate the token on create with a callback like so:

class User < ActiveRecord::Base

  # Call backs
  # ----------
  before_create :generate_access_token

  private

    def generate_access_token
      begin
        self.access_token = SecureRandom.hex
      end while self.class.exists?(access_token: access_token)
    end

end

The begin-end-while will check that the SecureRandom.hex value will always be unique in the table.

Once you have this token, you can use it in a cookie or wherever.

Community
  • 1
  • 1
rlarcombe
  • 2,748
  • 1
  • 14
  • 22