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?
            Asked
            
        
        
            Active
            
        
            Viewed 279 times
        
    0
            
            
        - 
                    2No. Generate a unique value if you need one. Don't abuse the password hash. – Jonathon Reinhart Nov 19 '15 at 08:43
- 
                    Thanks for quick reply @JonathonReinhart – Ritesh katare Nov 19 '15 at 08:46
- 
                    Can i use authenticity_token? which CSRF token authenticity uses. – Ritesh katare Nov 19 '15 at 09:00
1 Answers
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.
 
     
    