Ritesh katare
Ritesh katare

Reputation: 140

password_digest value is unique for user?

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?

Upvotes: 0

Views: 293

Answers (1)

rlarcombe
rlarcombe

Reputation: 2986

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.

Upvotes: 1

Related Questions